Java之斗地主案例
2021/12/10 12:16:37
本文主要是介绍Java之斗地主案例,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
import java.util.*; /* 模拟斗地主发牌 */ public class Test { public static void main(String[] args) { //1.生成一副牌 //定义一个双列集合,键:表示牌的编号,值:表示具体的牌,规则:编号越小,牌越小 Map<Integer,String> pokers = new HashMap<>(); //定义一个单列集合,用来存储所有牌的编号 List<Integer> list = new ArrayList<>(); //具体生成牌的操作 //52张普通牌 String[] colors = {"♠","♥","♣","♦"}; String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"}; int num = 0; //表示编号 //通过循环嵌套生成普通牌 for (String number : numbers) {//外循环获取所有的点数 for (String color : colors) {//内循环获取所有的花色 String poker = color + number; //将牌的编号,具体的牌放到双列集合中 pokers.put(num,poker); //将牌的编号放到单列集合中 list.add(num); //没添加一张牌,编号自增1 num++; } } //2张大小王 //添加小王 pokers.put(num, "小王"); list.add(num++); //添加大王 pokers.put(num, "大王"); list.add(num); //打印牌 System.out.println("所有的牌: " + pokers); System.out.println("牌的编号: " + list); //洗牌 Collections.shuffle(list); System.out.println("洗好牌后,编号为: " + list); //发牌 //定义四个集合,表示3个玩家和底牌 List<Integer> liuyifei = new ArrayList<>(); List<Integer> zhaobenshan = new ArrayList<>(); List<Integer> myself = new ArrayList<>(); List<Integer> dipai = new ArrayList<>(); //具体的发牌操作,将索引与3取余,决定发给谁 for (int i = 0; i < list.size(); i++) { //获取编号 Integer pokerNum = list.get(i); // System.out.println(pokerNum); if (i >= list.size() - 3) { //底牌 dipai.add(pokerNum); }else if (i % 3 == 0) { liuyifei.add(pokerNum); }else if (i % 3 == 1) { zhaobenshan.add(pokerNum); }else if (i % 3 == 2) { myself.add(pokerNum); } } //查看玩家,底牌的编号 /*System.out.println("liuyifei: " + liuyifei); System.out.println("zhaobenshan: " + zhaobenshan); System.out.println("myself: " + myself); System.out.println("dipai: " + dipai);*/ //查看具体的牌 System.out.println("___________________________________________________"); /*String s1 = printPoker(liuyifei, pokers); System.out.println(s1);*/ System.out.println("liuyifei: " + printPoker(liuyifei, pokers)); System.out.println("zhaobenshan: " + printPoker(zhaobenshan, pokers)); System.out.println("myself: " + printPoker(myself, pokers)); System.out.println("dipai: " + printPoker(dipai, pokers)); } /* 定义一个方法,用来看牌 方法名: printPoker 参数列表: List<Integer>,Map<Integer,String> 返回值:String */ public static String printPoker(List<Integer> nums, Map<Integer,String> pokers) { //1.对牌的编号升序排列 Collections.sort(nums); //2.遍历牌的编号集合,获取到每一个编号 StringBuilder sb = new StringBuilder(); for (Integer num : nums) { //num就是要查找的具体牌的编号 //3.根据编号去双列集合中查找该编号对应的具体牌 String poker = pokers.get(num); sb.append(poker + " " ); } //4.将获取到的牌进行拼接 //5.将最后拼接结果返回即可 String str = sb.toString(); return str.trim(); } }
作者所有随笔仅为学习笔记,仅供参考
这篇关于Java之斗地主案例的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-23Springboot应用的多环境打包入门
- 2024-11-23Springboot应用的生产发布入门教程
- 2024-11-23Python编程入门指南
- 2024-11-23Java创业入门:从零开始的编程之旅
- 2024-11-23Java创业入门:新手必读的Java编程与创业指南
- 2024-11-23Java对接阿里云智能语音服务入门详解
- 2024-11-23Java对接阿里云智能语音服务入门教程
- 2024-11-23JAVA对接阿里云智能语音服务入门教程
- 2024-11-23Java副业入门:初学者的简单教程
- 2024-11-23JAVA副业入门:初学者的实战指南