用java模拟斗地主洗牌和发牌:
利用集合来完成洗牌发牌的动作
准备工作也就是思路:
/*准备:
* 花色:♠♥♦♣ ArrayList
* 数字:3,4,5,6,7,8,9,10,J,Q,K,A,2 ArrayList
* 大小王:☺☻
* !!!!!!!!定义一个map集合:用来将数字与每一张牌进行对应
* 得有一副54张的牌 ArrayList里边为1-54的数
* 洗牌:
* 打乱这副牌的顺序
* 发牌:
* 将54张牌分发到4个TreeSet手中,前三个17张,最后一个3张
* player TreeSet
* player2 TreeSet
* player3 TreeSet
* dipai TreeSet
*/
思路的分析图:
代码的实现:
public static void main(String[] args) {
//准备花色
ArrayList<String> color = new ArrayList<String>();
color.add("♠");
color.add("♥");
color.add("♦");
color.add("♣");
//准备数字
ArrayList<String> number = new ArrayList<String>();
Collections.addAll(number, "3","4","5","6","7","8","9","10","J","Q","K","A","2");
//定义一个map集合:用来将数字与每一张牌进行对应
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
int index = 1;
for (String thisNumber : number) {
for (String thisColor : color) {
hashMap.put(index++, thisNumber+thisColor);
}
}
//加入大小王
hashMap.put(index++, "小☺");
hashMap.put(index++, "大☻");
System.out.println(hashMap);
//得有一副54张的牌 ArrayList里边为1-54的数的新牌
ArrayList<Integer> cards = new ArrayList<Integer>();
for (int i = 1; i <= 54; i++) {
cards.add(i);
}
//洗牌
Collections.shuffle(cards);
//创建三个玩家和底牌
TreeSet<Integer> player = new TreeSet<Integer>();
TreeSet<Integer> player2 = new TreeSet<Integer>();
TreeSet<Integer> player3 = new TreeSet<Integer>();
TreeSet<Integer> dipai = new TreeSet<Integer>();
//遍历这副洗好的牌,遍历过程中,将牌发到三个玩家和dipai手中
for (int i = 0; i < cards.size(); i++) {
if(i>=51) {
dipai.add(cards.get(i));
} else {
if(i%3==0) {
player.add(cards.get(i));
}else if(i%3==1) {
player2.add(cards.get(i));
}else {
player3.add(cards.get(i));
}
}
}
//看牌
for (Integer key : dipai) {
System.out.print(hashMap.get(key)+", ");
}
System.out.println();
for (Integer key : player) {
System.out.print(hashMap.get(key)+", ");
}
System.out.println();
for (Integer key : player2) {
System.out.print(hashMap.get(key)+", ");
}
System.out.println();
for (Integer key : player3) {
System.out.print(hashMap.get(key)+", ");
}
}