通过集合的方式使得实现对三个玩家斗地主的洗牌、发牌、看牌。具体实现如下:
public static void main(String[] args) {
//1 创建牌盒子
HashMap<Integer , String> hm = new HashMap<Integer , String>();
// 存储hashmap的键
ArrayList<Integer> array = new ArrayList<Integer>();
// 花色
String[] colors = {"♠","♥","♣","♦"};
// 牌点数
String[] numbers = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
int index =0;
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实现玩家
TreeSet<Integer> play1 = new TreeSet<Integer>();
TreeSet<Integer> play2 = new TreeSet<Integer>();
TreeSet<Integer> play3 = new TreeSet<Integer>();
TreeSet<Integer> deepPokers = new TreeSet<Integer>();
for(int i = 0 ; i < array.size() ; i++) {
if (i >= array.size() - 3) {
deepPokers.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 if (i % 3 == 2) {
play3.add(array.get(i));
}
}
// 定义看牌
lookPoker("玩家1", hm, play1);
lookPoker("玩家2", hm, play2);
lookPoker("玩家3", hm, play3);
lookPoker("底", hm, deepPokers);
}
public static void lookPoker(String name , HashMap<Integer, String> hm , TreeSet<Integer> treeSet) {
System.out.print(name+"牌是:");
Iterator<Integer> iterator = treeSet.iterator();
while(iterator.hasNext()) {
System.out.print(hm.get(iterator.next())+" ");
}
System.out.println();
}
输出:
玩家1牌是:♠3 ♦3 ♣4 ♠5 ♥5 ♦7 ♥8 ♦8 ♥10 ♥J ♠Q ♥A ♣A ♦A ♠2 ♥2 小王
玩家2牌是:♠4 ♥4 ♦5 ♦6 ♣7 ♠8 ♠9 ♣9 ♦9 ♦10 ♠J ♣J ♥Q ♣Q ♣K ♠A 大王
玩家3牌是:♥3 ♣3 ♦4 ♣5 ♠6 ♥6 ♣6 ♠7 ♣8 ♠10 ♣10 ♦J ♠K ♥K ♦K ♣2 ♦2
底牌是:♥7 ♥9 ♦Q