当前位置: 代码迷 >> 综合 >> 使用HashMap实现斗地主发牌、按照大小读牌,总结Collection与Map的使用方法
  详细解决方案

使用HashMap实现斗地主发牌、按照大小读牌,总结Collection与Map的使用方法

热度:30   发布时间:2023-10-21 07:52:24.0

 Main方法:

public static void main(String[] args) {//利用字典, 1-54 大王....?3Map<Integer,String> poker = new HashMap<>();//添加 第一张牌大王,第二张牌小王int index = 0;poker.put(++index,"大王");poker.put(++index,"小王");//创建花色ArrayList<String> colors = new ArrayList<>();//创建数字ArrayList<String> numbers = new ArrayList<>();Collections.addAll(colors, "?", "?", "?", "?");Collections.addAll(numbers,"2","A","K","Q","J","10","9","8","7","6","5","4","3");//组合花色//因为花色之间相差1,所以color的循环在里面for (String number : numbers)for (String color : colors)//因为玩牌习惯叫 ?花 几poker.put(++index,color+number);ArrayList<Integer> pokerIndex = new ArrayList<>();//使用addAll实现 List-Set的转换pokerIndex.addAll(poker.keySet());//洗牌就是打乱索引Collections.shuffle(pokerIndex);ArrayList<Integer> player1 = new ArrayList<>();ArrayList<Integer> player2 = new ArrayList<>();ArrayList<Integer> player3 = new ArrayList<>();ArrayList<Integer> dipai = new ArrayList<>();//发牌for (int i = 0; i < pokerIndex.size(); i++) {if(i<=2)dipai.add(pokerIndex.get(i));else{if(i%3==1)player1.add(pokerIndex.get(i));if(i%3==2)player2.add(pokerIndex.get(i));if(i%3==0)player3.add(pokerIndex.get(i));}}//Collections工具类的排序方法Collections.sort(player1);Collections.sort(player2);Collections.sort(player3);Collections.sort(dipai);//读牌方法printPai(poker, player1,"张三");printPai(poker, player2,"李四");printPai(poker, player3,"王五");}private static void printPai(Map<Integer, String> poker, ArrayList<Integer> player,String playName) {StringBuffer stringBuffer = new StringBuffer();//输出玩家姓名stringBuffer.append(playName+": [");for (Integer playerIndex : player) {//每一张牌用","分割stringBuffer.append(poker.get(playerIndex)).append(",");}//获取最后一个 ”,“索引int i = stringBuffer.lastIndexOf(",");//替换”,“->"]"          (开始位置-包含 ,结束位置-不包含) 所以从i开始,往后查一位。stringBuffer.replace(i,i+1,"]");
//        String substring = stringBuffer.substring(0, i);System.out.println(stringBuffer);}

 输出结果:

张三: [大王,?2,?A,?K,?K,?K,?Q,?J,?10,?9,?7,?7,?6,?5,?3,?3,?3]
李四: [小王,?2,?A,?J,?J,?10,?9,?9,?8,?8,?8,?7,?6,?6,?6,?5,?4]
王五: [?2,?A,?A,?Q,?Q,?J,?10,?10,?9,?8,?7,?5,?5,?4,?4,?4,?3]Process finished with exit code 0

总结:

利用<K,V>生成牌的字典。使用Map中的entrySet()获得单列结合Set(里面存放的是牌的索引),使用Collection中的addAll将Set集合转换成List集合,使用Collection中的AddAll,一次向集合中添加多个元素,使用Collection的sort对牌进行排序。使用StringBuffer中的AppendsubString对字符串进行增减,使用lastIndexOf获取索引位置,使用replace进行字符串的替换。

  相关解决方案