老师在课堂上讲了斗地主的发牌机制。不过是为了讲解map而强行使用map的,代码上效率不高。因为一副扑克牌的数量和每个序号对应的牌都是固定的!
这就说明用一个数组就可以实现基本扑克牌的存放。
而当长度不固定,索引不连续,非简单序列时,才是Map大显身手的地方!
而冯佳老师讲解的发牌过程写得对逻辑要求比较高,可以换一种简单的角度去思考:先发17轮牌,每轮发每人一张,最后剩下三张牌再放入底牌。
使用该思路则将循环的判断次数减少了(54-17)次,每次循环中也省去调用除法库的繁重工作。其实洗牌发牌的过程大家应该都懂了~我这个代码的价值感觉不算很大~不知道我对集合和数组的理解过关不~有理解不对的希望大家指正哈~
public static void main(String[] args) {
String[] str1 = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] str2 = {"草花","黑桃","方块","红桃"};
String[] str3 = new String[54];
//-------------------------第一处不同处----------------------
int count = 0;
for (String string1 : str1) {
for (String string2 : str2) {
str3[count++] = string2 + string1;
}
}
str3[count++] = "小王";
str3[count++] = "大王";
ArrayList<Integer> arrlist = new ArrayList<>();
for (int i = 0; i < str3.length; i++) {
arrlist.add(i);
}
Collections.shuffle(arrlist);
TreeSet<Integer> play1 = new TreeSet<>();
TreeSet<Integer> play2 = new TreeSet<>();
TreeSet<Integer> play3 = new TreeSet<>();
TreeSet<Integer> rest = new TreeSet<>();
//-------------------------第二处不同处----------------------
count = 0;
for (int i = 0; i < 17; i++) {
play1.add(arrlist.get(count++));
play2.add(arrlist.get(count++));
play3.add(arrlist.get(count++));
}
for (int i = 0; i < 3; i++) {
rest.add(arrlist.get(count++));
}
showPoke(str3,play1,"Play1");
showPoke(str3,play2,"Play2");
showPoke(str3,play3,"Play3");
showPoke(str3,rest,"剩下");
}
private static void showPoke(String[] str3, TreeSet<Integer> play,
String string) {
System.out.print(string + "的牌是:");
for (Integer integer : play) {
System.out.print(str3[integer] + " ");
}
System.out.println(".");
}
|