斗地主案例
*步骤:1.准备牌;
2.洗牌;
3.发牌;
4.排序;
5.看牌。
代码示例:
public class DoudizhuTest { public static void main(String[] args) { //1.准备牌 //创建一个Map集合,储存洗好的牌和索引 Map<Integer, String> map = new HashMap<Integer, String>(); //创建一个List集合,用于存储牌的索引 List<Integer> pokerList = new ArrayList<Integer>(); //创建牌,一个花色集合,和一个牌的序号集合 List<String> colors = new ArrayList<>(); colors.add("♠"); colors.add("♥"); colors.add("♣"); colors.add("♦"); List<Integer> numbers = new ArrayList<>(); numbers.add(2); numbers.add(1); for (int i = 13; i >= 3; i--) { numbers.add(i); } //将牌和索引存入Map集合 int index = 0; map.put(index, "大"); pokerList.add(index); index++; map.put(index, "小"); pokerList.add(index); index++; for (String color : colors) { for (Integer number : numbers) { String s = number + color; map.put(index, s); pokerList.add(index++); } } // System.out.println("所有的扑克牌:"+map); // System.out.println("所有的pokerList:"+pokerList); //2.洗牌 //使用Collections的shuffle()方法可以打烂集合 Collections.shuffle(pokerList); // System.out.println("打乱后的的pokerList:"+pokerList); //3.发牌 //给三个玩家和底牌分配牌 List<Integer> dipan = new ArrayList<Integer>(); List<Integer> player1 = new ArrayList<Integer>(); List<Integer> player2 = new ArrayList<Integer>(); List<Integer> player3 = new ArrayList<Integer>(); for (int i = 0; i < pokerList.size(); i++) { //先发底牌 if (i >= 51) { dipan.add(pokerList.get(i)); } else if (i % 3 == 0) { player1.add(pokerList.get(i)); } else if (i % 3 == 1) { player2.add(pokerList.get(i)); } else if (i % 3 == 2) { player3.add(pokerList.get(i)); } } //4.排序 //使用Collections的sort()方法排序 Collections.sort(dipan); Collections.sort(player1); Collections.sort(player2); Collections.sort(player3); //5.看牌 System.out.print("玩家1:"); for (Integer x : player1) { System.out.print(map.get(x)+" "); } System.out.println(); System.out.print("玩家2:"); for (Integer x : player2) { System.out.print(map.get(x)+" "); } System.out.println(); System.out.print("玩家3"); for (Integer x : player3) { System.out.print( map.get(x)+" "); } System.out.println(); System.out.print("底牌:"); for (Integer x : dipan) { System.out.print(map.get(x)+" "); } } }
测试结果1:
玩家1:10♠ 5♠ 4♠ 2♥ 11♥ 10♥ 7♥ 6♥ 3♥ 1♣ 9♣ 5♣ 3♣ 1♦ 8♦ 5♦ 4♦
玩家2:2♠ 13♠ 12♠ 11♠ 8♠ 7♠ 13♥ 12♥ 8♥ 4♥ 2♣ 13♣ 11♣ 8♣ 6♣ 13♦ 11♦
玩家3大 小 9♠ 6♠ 3♠ 1♥ 9♥ 5♥ 12♣ 10♣ 7♣ 4♣ 2♦ 12♦ 10♦ 9♦ 3♦
底牌:1♠ 7♦ 6♦
测试结果2:
玩家1:12♠ 11♠ 10♠ 6♠ 4♠ 10♥ 8♥ 6♥ 3♥ 2♣ 13♣ 1♦ 11♦ 10♦ 8♦ 5♦ 4♦
玩家2:2♠ 1♠ 7♠ 2♥ 12♥ 1♣ 10♣ 9♣ 8♣ 7♣ 6♣ 4♣ 3♣ 2♦ 13♦ 6♦ 3♦
玩家3小 13♠ 9♠ 8♠ 5♠ 3♠ 1♥ 9♥ 7♥ 5♥ 4♥ 12♣ 11♣ 5♣ 12♦ 9♦ 7♦
底牌:大 13♥ 11♥
原文地址:https://www.cnblogs.com/jasonjson/p/12409041.html
时间: 2024-10-21 09:19:21