/**
* 需求:模拟实现斗地主的分牌情形
* 分析:1 模拟牌盒,存储54张牌,0-53 每个数字分别对应一张牌,用Map存储
* 2 将0-53序号随机分发到三个人手中,欲实现序号的随机排序,考虑使用Collections.shuffle()
* 因此序号使用ArrayList存储
* 3 看牌,并且实现玩家手上的拍由小到大排序,所以考虑使用TreeSet存储
*/
package fmi1;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
public class PokerSimulate {
/**
* @param args
*/
public static void main(String[] args) {
//建立牌盒
String[] color = {"♦","♣","♥","♠"};//花色
String[] size ={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};//大小
//建立集合存牌
HashMap<Integer, String> hm = new HashMap<Integer,String>();
//循环组牌并存至集合
int key = 0;
for(String s1:size){
for(String s2:color){
String value = s2 + s1;
hm.put(key, value);
key++;
}
}
hm.put(key++, "LKing");
hm.put(key, "BKing");
//输出牌
printPoke(hm);
//建立ArrayList实现牌的序号的随机分布
ArrayList<Integer> al = new ArrayList<Integer>();
//存序号
for(int i = 0;i < 54;i++){
al.add(i);
}
//洗牌
Collections.shuffle(al);
//新建3个玩家和一个底牌,即TreeSet集合
TreeSet<Integer> gamer1 = new TreeSet<Integer>();
TreeSet<Integer> gamer2 = new TreeSet<Integer>();
TreeSet<Integer> gamer3 = new TreeSet<Integer>();
TreeSet<Integer> dipai = new TreeSet<Integer>();
//发牌
for(int i = 0;i<al.size();i++){
if(i >= al.size()-3)
dipai.add(al.get(i));
else if(i%3==0)
gamer1.add(al.get(i));
else if(i%3==1)
gamer2.add(al.get(i));
else
gamer3.add(al.get(i));
}
//System.out.println(gamer1);
//System.out.println(gamer2);
//System.out.println(gamer3);
//System.out.println(dipai);
//看牌
System.out.println("玩家1:");
checkPoker(gamer1,hm);
System.out.println("玩家2:");
checkPoker(gamer2,hm);
System.out.println("玩家3:");
checkPoker(gamer3,hm);
System.out.println("底牌:");
checkPoker(dipai,hm);
}
private static void checkPoker(TreeSet<Integer> gamer,
HashMap<Integer, String> hm) {
for(int key:gamer){
//System.out.print(key+" ");
System.out.print(hm.get(key)+" ");
}
System.out.println();
}
private static void printPoke(HashMap<Integer, String> hm) {
System.out.print("扑克牌:");
for (int i = 0; i < hm.size(); i++) {
if (i % 4 == 0)
System.out.println();
System.out.print(hm.get(i) + "\t");
}
System.out.println();
}
}
运行结果
扑克牌:♦3♣3♥3♠3♦4♣4♥4♠4♦5♣5♥5♠5♦6♣6♥6♠6♦7♣7♥7♠7♦8♣8♥8♠8♦9♣9♥9♠9♦10♣10♥10♠10♦J♣J♥J♠J♦Q♣Q♥Q♠Q♦K♣K♥K♠K♦A♣A♥A♠A♦2♣2♥2♠2LKingBKing玩家1:♣3 ♦4 ♠5 ♦6 ♣7 ♥7 ♠7 ♦9 ♣10 ♠J ♣Q ♥Q ♦K ♦A ♦2 ♠2 LKing 玩家2:♦3 ♥3 ♠4 ♦5 ♣6 ♦8 ♣9 ♥9 ♥10 ♦J ♣J ♥J ♠Q ♣K ♣A ♥A ♣2 玩家3:♠3 ♣4 ♥4 ♣5 ♥5 ♥6 ♦7 ♥8 ♠8 ♠9 ♦10 ♦Q ♥K ♠K ♠A ♥2 BKing 底牌:♠6 ♣8 ♠10