JavaSE-16.3.2【案例-模拟斗地主(升级版本)】

 

 

 

 

 1 package day7.lesson3;
 2 
 3 import java.util.*;
 4 
 5 /*
 6 3.1 案例-模拟斗地主(升级版本)
 7     需求
 8         通过程序实现斗地主过程中的洗牌,发牌和看牌
 9         +给玩家顺排,即对牌进行排序
10 */
11 public class PokerDemo2 {
12     public static void main(String[] args) {
13         //创建HashMap,键是编号,值是牌
14         HashMap<Integer, String> hashMap = new HashMap<>();
15 
16         //创建ArrayList,存储编号
17         ArrayList<Integer> arrayList = new ArrayList<>();
18 
19         //创建花色数组和点数数组
20         String[] colors = {"♦", "♣", "♥", "♠"};
21         String[] numbers = {"3", "4", "5", "6", "7", "8", "9", "J", "Q", "K", "A", "2"};
22 
23         //牌盒装牌
24         int index = 0;
25         for (String number: numbers){
26             for (String color: colors){
27                 hashMap.put(index, color+number);
28                 arrayList.add(index);
29                 index++;
30             }
31         }
32         hashMap.put(index, "小王");
33         arrayList.add(index);
34         index++;
35         hashMap.put(index, "大王");
36         arrayList.add(index);
37 
38         //洗牌(洗的是编号)
39         Collections.shuffle(arrayList);
40 
41         //发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
42         TreeSet<Integer> player1 = new TreeSet<>();
43         TreeSet<Integer> player2 = new TreeSet<>();
44         TreeSet<Integer> player3 = new TreeSet<>();
45         TreeSet<Integer> dipai = new TreeSet<>();
46 
47         for (int i=0; i<arrayList.size(); i++){
48             int poker_index = arrayList.get(i);
49             if(i >= arrayList.size()-3){
50                 dipai.add(poker_index);
51             }else if(i%3 == 0){
52                 player1.add(poker_index);
53             }else if(i%3 == 1){
54                 player2.add(poker_index);
55             }else if(i%3 == 2){
56                 player3.add(poker_index);
57             }
58         }
59 
60         //看牌
61         lookPoker("玩家1", player1, hashMap);
62         lookPoker("玩家2", player2,hashMap);
63         lookPoker("玩家3", player3, hashMap);
64         lookPoker("底牌", dipai, hashMap);
65     }
66 
67     //(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
68     public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer,String> hm){
69         System.out.println(name + "的牌:");
70         for (Integer key: ts){
71             String poker = hm.get(key);
72             System.out.print(poker + " ");
73         }
74         System.out.println();
75     }
76 
77 }

 

posted @ 2021-06-02 19:43  yub4by  阅读(63)  评论(0编辑  收藏  举报