斗地主综合案例:有序版本

mac2022-06-30  31

ge com.itcast;import java.util.ArrayList;import java.util.Collections;import java.util.HashMap;import java.util.Map;/** * @author newcityman * @date 2019/7/21 - 0:22 * 斗地主综合案例:有序版本 * 1、准备牌 * 2、洗牌 * 3、发牌 * 4、排序 * 5、看牌 */public class DouDizhu {public static void main(String[] args) {//1、准备牌 //准备一个map集合,存储牌的索引和组装好的牌 HashMap<Integer,String> poker = new HashMap<>(); //准备一个List结合,存储牌的索引 ArrayList<Integer> pokerIndex = new ArrayList<>(); //准备两个集合用来存放花色和牌的序号 ArrayList<String> colors = new ArrayList<>(); colors.add("♥"); colors.add("♠"); colors.add("♣"); colors.add("♦"); ArrayList<String> nums=new ArrayList<>(); nums.add("2"); nums.add("3"); nums.add("4"); nums.add("5"); nums.add("6"); nums.add("7"); nums.add("8"); nums.add("9"); nums.add("10"); nums.add("J"); nums.add("Q"); nums.add("K"); nums.add("A"); //把大王和小王存储到集合中去 //先定义一个牌的索引 int index = 0; poker.put(index,"大王"); pokerIndex.add(index); index++; poker.put(index,"小王"); pokerIndex.add(index); index++; //循环嵌套遍历两个集合,组装52张牌。存放到集合中 for (String num : nums) {for (String color : colors) { poker.put(index,color+num); pokerIndex.add(index); index++; } }//2、洗牌 Collections.shuffle(pokerIndex); //3、发牌 //首先需要定义四个集合,用来存放三个玩家,一个底牌 ArrayList<Integer> player01 = new ArrayList<>(); ArrayList<Integer> player02 = new ArrayList<>(); ArrayList<Integer> player03 = new ArrayList<>(); ArrayList<Integer> dipai = new ArrayList<>(); for (int i = 0; i < pokerIndex.size(); i++) { Integer in = pokerIndex.get(i); if(i>50){ dipai.add(in); }else if(i%3==0){ player01.add(in); }else if(i%3==1){ player02.add(in); }else if(i%3==2){ player03.add(in); } }//整牌 Collections.sort(player01); Collections.sort(player02); Collections.sort(player03); Collections.sort(dipai); lookPoker("周润发",poker,player01); lookPoker("周星驰",poker,player02); lookPoker("刘德华",poker,player03); lookPoker("底牌",poker,dipai); }/* * 定义一个方法,增加代码的复用性 * 参数: * String name;玩家名称 * HashMap<Integer,String> poker:存储牌的map结合 * ArrayList<Integer> list :存储玩家和底牌的list集合 * 查表法: * 遍历玩家或者底牌的集合,获取牌的索引 * 使用牌的索引,去Map集合中,找到对应位置的牌 */ public static void lookPoker(String name, Map<Integer,String> poker,ArrayList<Integer> list){//输出玩家的名称 System.out.print(name+": "); for (Integer key : list) { String value = poker.get(key); System.out.print(value+" "); }

转载于:https://www.cnblogs.com/newcityboy/p/11220169.html

最新回复(0)