- 创建一个牌盒,用ArrayList集合实现
- 往牌盒里面装牌
- 用Collections的shuffle()方法实现洗牌
- 把牌发给三个玩家
- 三个玩家分别看牌
package CollectionsStudy; import java.util.ArrayList; import java.util.Collections; //模拟斗地主 public class Demo2 { public static void main(String[] args) { //创建ArrayList对象 ArrayList二、升级 1.需求poker = new ArrayList<>(); //添加牌 String[] colors = {"♠", "♥", "♣", "♦"};//花色数组 String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};//数字数组 for (String color : colors) { for (String number : numbers) { poker.add(color + number); } } poker.add("大王"); poker.add("小王"); //洗牌 Collections.shuffle(poker); //发牌 ArrayList player1 = new ArrayList<>(); ArrayList player2 = new ArrayList<>(); ArrayList player3 = new ArrayList<>(); ArrayList dipai = new ArrayList<>(); for (int i = 0; i < poker.size(); i++) { if (i >= poker.size() - 3) { dipai.add(poker.get(i)); } else if (i % 3 == 0) { player1.add(poker.get(i)); }else if (i % 3 == 1) { player2.add(poker.get(i)); }else { player3.add(poker.get(i)); } } //查看手牌 lookPoker("玩家一",player1); lookPoker("玩家二",player2); lookPoker("玩家三",player3); lookPoker("底牌",dipai); } //定义查看手牌的方法 public static void lookPoker(String name , ArrayList arrayList){ System.out.print(name + "的牌为:"); for (String s : arrayList) { System.out.print(s); } System.out.println(); } }
对牌进行排序
2.思路- 创建HashMap集合,键是编号,值是牌
- 创建ArrayList集合存储编号
- 从0开始往HashMap中存储数据,同时也往ArrayList中存储编号
- 用Collections的shuffle()方法实现洗牌
- 发牌时为了保证顺序用TreeSet接收
- 定义看牌方法(遍历TreeSet集合获取编号并到HashMap中找对应的牌)
- 调用看牌方法
package CollectionsStudy; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.TreeSet; //斗地主升级 public class Demo3 { public static void main(String[] args) { //创建 HashMaphm = new HashMap<>(); // 创建ArrayList对象 ArrayList array = new ArrayList<>(); //添加牌 int index = 0; String[] colors = {"♠", "♥", "♣", "♦"};//花色数组 String[] numbers = {"2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"};//数字数组 //按数字排序 for (String number : numbers) { for (String color : colors) { hm.put(index, color + number); array.add(index); index++; } } hm.put(index,"小王"); array.add(index); index++; hm.put(index,"大王"); array.add(index); //洗牌 Collections.shuffle(array); //发牌 TreeSet play1 = new TreeSet<>(); TreeSet play2 = new TreeSet<>(); TreeSet play3 = new TreeSet<>(); TreeSet dipai = new TreeSet<>(); for(int i = 0 ; i < array.size() ; i++){ if(i >= array.size() - 3 ) { dipai.add(array.get(i)); }else if(i % 3 == 0 ){ play1.add(array.get(i)); }else if(i % 3 == 1 ){ play2.add(array.get(i)); }else { play3.add(array.get(i)); } } //看牌 lookPoker("玩家一" , play1 , hm); lookPoker("玩家二" , play2 , hm); lookPoker("玩家三" , play3 , hm); lookPoker("底牌" , dipai , hm); } static void lookPoker(String name , TreeSet ts , HashMap hm){ System.out.print(name + "的牌:"); for (Integer t : ts) { System.out.print(hm.get(t)); } System.out.println(); } }
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)