java模拟斗地主发牌功能
本文实例为大家分享了java模拟斗地主发牌的具体代码,供大家参考,具体内容如下
1.案例介绍
规则:
- 组装54张扑克牌
- 54张牌顺序打乱
- 三个玩家参与游戏,三人交替摸牌,每人17张牌,后三张留作底牌
- 查看三人各自手中的牌(按照牌的大小排序)、底牌
2. 分析
1)、准备牌:
完成数字与纸牌的映射关系:
使用双列Map(HashMap)集合,完成一个数字与字符串纸牌的对应关系(相当于一个字典)。
2)、洗牌:
通过数字完成洗牌发牌
发牌: 将每个人以及底牌设计为ArrayList,将后3张牌直接存放于底牌,剩余牌通过对3取模依次发牌。
存放的过程中要求数字大小与斗地主规则的大小对应。
将代表不同纸牌的数字分配给不同的玩家与底牌。
3)、看牌:
通过Map集合找到对应字符展示。
通过查询纸牌与数字的对应关系,由数字转成纸牌字符串再进行展示。
3.代码
public class Test7 { public static void main(String[] args) { //定义一个Map集合和List集合来存取牌号和索引 Map<Integer, String> map = new HashMap(); List<Integer> pokerindex = new ArrayList<>(); //定义牌 String[] num = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; String[] color = {"♥", "♠", "♣", "♦"}; //存牌号和与之对应的索引 int index = 0; for (String s : num) { for (String c : color) { map.put(index, c + s); pokerindex.add(index); index++; } } //存大小王 map.put(index, "大王"); pokerindex.add(index); index++; map.put(index, "小王"); pokerindex.add(index); //打乱牌组; Collections.shuffle(pokerindex); //创建四个集合 List<Integer> dipai = new ArrayList<>(); List<Integer> player1 = new ArrayList<>(); List<Integer> player2 = new ArrayList<>(); List<Integer> player3 = new ArrayList<>(); //将打乱的索引数组分配给三个人 for (int i = 0; i < pokerindex.size(); i++) { if (i > 50) { dipai.add(pokerindex.get(i)); } else if (i % 3 == 0) { player1.add(pokerindex.get(i)); } else if (i % 3 == 2) { player2.add(pokerindex.get(i)); } else if (i % 3 == 1) { player3.add(pokerindex.get(i)); } } //给每个人的牌组排序 Collections.sort(player1); Collections.sort(player2); Collections.sort(player3); Collections.sort(dipai); //显示每个人的牌组 show("张三", map, player1); show("李四", map, player2); show("王五", map, player3); show("底牌", map, dipai); } //定义一个方法用来显示牌组 public static void show(String name, Map<Integer, String> map, List<Integer> player) { System.out.print(name); for (int i = 0; i < player.size(); i++) { Integer ii = player.get(i); System.out.print(map.get(ii) + " "); } System.out.println(); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
相关文章
Java Web开发常用框架Spring MVC Struts示例解析
这篇文章主要为大家介绍了Java Web开发常用框架Spring MVC Struts示例解析,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪2023-06-06IDEA mybatis-generator逆向工程生成代码
这篇文章主要介绍了IDEA mybatis-generator逆向工程生成代码,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧2018-06-06java的SimpleDateFormat线程不安全的几种解决方案
但我们知道SimpleDateFormat是线程不安全的,处理时要特别小心,要加锁或者不能定义为static,要在方法内new出对象,再进行格式化,本文就介绍了几种方法,感兴趣的可以了解一下2021-08-08
最新评论