创建HashMap,键是编号,值是牌
创建ArrayList,存储编号
创建花色数组和点数数组
从0开始往HashMap里面存储编号,并存储对应的牌。同时往ArrayList里面存储编号
洗牌(洗的是编号),用Collections的shuffle()方法实现
发牌(发的也是编号,为了保证编号是排序的,创建TreeSet集合接收)
定义方法看牌(遍历TreeSet集合,获取编号,到HashMap集合找对应的牌)
调用方法
代码如下:
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
public class ChinesePoker {
public static void main(String[] args) {
//创建HashMap,键是编号,值是牌
HashMap<Integer, String> hm = new HashMap<Integer, String>();
//创建ArrayList,存储编号
ArrayList<Integer> arr = new ArrayList<Integer>();
//创建花色数组
String[] Colors = {"♦", "♣", "♥", "♠"};
//牌数组
String[] Numbers = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "k", "A", "2"};
//从0开始往HashMap里面存储编号,并存储对应的牌。同时往ArrayList里面存储编号
int index = 0;
for (String color : Colors) {
for (String Number : Numbers) {
hm.put(index, color + Number);
//存储编号到arr集合
arr.add(index);
index++;
}
}
hm.put(index, "小王");
arr.add(index);
index++;
hm.put(index, "大王");
arr.add(index);
//洗牌、该方法随机打乱
Collections.shuffle(arr);
//发牌,为了保证编号是排序的,创建TreeSet集合接收
TreeSet<Integer> lYset = new TreeSet<Integer>();
TreeSet<Integer> llFset = new TreeSet<Integer>();
TreeSet<Integer> WZXset = new TreeSet<Integer>();
TreeSet<Integer> DPset = new TreeSet<Integer>();
for (int i = 0; i < arr.size(); i++) {
int x = arr.get(i);
//后三张为底牌
if (i >= arr.size() - 3) {
DPset.add(x);
} else if (i % 3 == 0) { //为玩家一发牌
lYset.add(x);
} else if (i % 3 == 1) {//为玩家二发牌
llFset.add(x);
} else if (i % 3 == 2) {//为玩家三发牌
WZXset.add(x);
}
}
//调用方法
lookPoker("刘洋", lYset, hm);
lookPoker("刘亦菲", llFset, hm);
lookPoker("王祖贤", WZXset, hm);
lookPoker("底牌", DPset, hm);
}
public static void lookPoker(String name, TreeSet<Integer> ts, HashMap<Integer, String> hm) {
System.out.print(name + "的牌是:");
for (Integer key : ts) {
//通过键获取对应值,即编号对应的牌
String poker = hm.get(key);
System.out.print(poker + " ");
}
System.out.println();
}
}
运行效果如下: