【案例6-4】斗地主模拟
【案例介绍】
1.任务描述
斗地主的扑克牌游戏,相信许多人都会玩,本例要求编写一个斗地主的洗牌发牌程序,要求按照斗地主的规则完成洗牌发牌的过程。一副扑克总共有54张牌,牌面由花色和数字组成(包括J、Q、K、A字母)组成,花色有♠、♥、♦、♣ 四种,分别表示黑桃、红桃、方块、梅花,小☺、大☻分别表示小王和大王。斗地主游戏共有三位玩家参与,首先将这54张牌的顺序打乱每人轮流摸一次牌,剩余3张留作底牌,然后在控制台打印三位玩家的牌和三张底牌。
```package com.j2se.myInstances.example6_4;
import java.util.*;
public class Poker {
public static void main(String[] args) {
String[] pokerNumArr = {
"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
String[] colorArr = {
"♦", "♣", "♠", "♥"};
HashMap<Integer, String> pokerSet = new HashMap<>();
// 装牌
int index = 0;
String pokerNum = null;
for (int i = 0; i < colorArr.length; i++) {
for (int j = 0; j < pokerNumArr.length; j++) {
pokerNum = colorArr[i] + pokerNumArr[j];
pokerSet.put(index++, pokerNum);
}
}
pokerSet.put(index, "小☺");
index++;
pokerSet.put(index, "大☻");
// System.out.println(pokerSet.toString());
ArrayList<Integer> numSet = new ArrayList<>();
for (int i = 0; i < 54; i++) numSet.add(i);
// xipai
Collections.shuffle(numSet);
// System.out.println(numSet.toString());
// 发牌
ArrayList<Integer> a1 = new ArrayList<>();
ArrayList<Integer> a2 = new ArrayList<>();
ArrayList<Integer> a3 = new ArrayList<>();
ArrayList<Integer> athree = new ArrayList<>();
for (int i = 0; i < numSet.size(); i++) {
Integer idx = numSet.get(i);
if (i >=51 ) {
athree.add(idx);
} else if (i % 3 == 0) {
a1.add(idx);
} else if (i%3==1) {
a2.add(idx);
} else {
a3.add(idx);
}
}
Collections.sort(a1);
Collections.sort(a2);
Collections.sort(a3);
Collections.sort(athree);
ArrayList<String> p1 = new ArrayList<>();
ArrayList<String> p2 = new ArrayList<>();
ArrayList<String> p3 = new ArrayList<>();
ArrayList<String> three = new ArrayList<>();
for (Integer idx : a1) {
String value = pokerSet.get(idx);
p1.add(value);
}
for (Integer idx : a2) {
String value = pokerSet.get(idx);
p2.add(value);
}
for (Integer idx : a3) {
String value = pokerSet.get(idx);
p3.add(value);
}
for (Integer idx : athree) {
String value = pokerSet.get(idx);
three.add(value);
}
System.out.println("玩家1:\n" + p1.toString());
System.out.println("玩家2:\n" + p2.toString());
System.out.println("玩家3:\n" + p3.toString());
System.out.println("底牌:\n" + three.toString());
}
}