斗地主案例
分析:
1.准备牌
特殊牌:大王,小王
52张牌: 循环嵌套遍历两个集合/数组,组装52张牌
List<String> colors = List.of(“♠”,"♥","♣","♦");
List<String> numbers = List.of("2","A","K"..."3");
2.洗牌
使用Collection中的方法shuffle(List)
3. 发牌
一人一张轮流发牌,每人17张
集合索引%3
剩余3张给底牌
4.排序
使用Collection中的方法
soft(List)
5.看牌:可以使用查表方法
遍历一个集合,获取到另一个集合的key,通过key查找到value
遍历玩家和底牌的List集合,获取到Map集合的key,通过key找到value值
public static void main(String[] args) { HashMap<Integer, String> map = new HashMap<>(); ArrayList<Integer> list = new ArrayList<>(); //创建花色 String[] color = {"♦","♠","♥","♣"}; //创建点数 String[] num = {"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; //存入HasMap int index = 0; for (String numa : num){ for (String col : color){ map.put(index,col+numa); list.add(index); index++; } } //存储小王和大王,最后一次index++比索引多一了 map.put(index,"小王"); list.add(index); index++; map.put(index,"大王"); list.add(index); //洗牌 Collections.shuffle(list); //玩家和底牌 TreeSet<Integer> Tset1 = new TreeSet<>(); TreeSet<Integer> Tset2 = new TreeSet<>(); TreeSet<Integer> Tset3 = new TreeSet<>(); TreeSet<Integer> Dset4 = new TreeSet<>(); //分牌 for (int i = 0; i < list.size(); i++) { Integer integer = list.get(i); if (i>=list.size()-3){ Dset4.add(integer); }else if (i%3==0){ Tset1.add(integer); }else if (i%3==1){ Tset2.add(integer); }else if (i%3==2){ Tset3.add(integer); } } lookPoker("张三",Tset1,map); lookPoker("李四",Tset2,map); lookPoker("王五",Tset3,map); lookPoker("底牌",Dset4,map); } public static void lookPoker(String name, TreeSet<Integer> play, HashMap<Integer, String> hm) { System.out.print(name + "的牌是:"); for (Integer i : play) { String x = hm.get(i); System.out.print(x + " "); } System.out.println(""); }