未排序前:
package File;
import java.util.ArrayList;
import java.util.Collections;
public class Poker {
/**
* 模拟斗地主
*
* @param args
*/
public static void main(String[] args) {
// 买一幅扑克,卡牌点数。
String[] num = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
// 四种花色
String[] color = {"方片", "梅花", "红桃", "黑桃"};
ArrayList<String> poker = new ArrayList<>();
// 两层foreach循环把花色和扑克牌拼接起来。
for (String s1 : color) {
for (String s2 : num) {
poker.add(s1.concat(s2));// 数组中concat拼接方法,意思就是方片A,方片2,方片3,以此类推。
}
}
// 因为小王和大王和他们没有任何关系,所有单独加上去。
poker.add("小王");
poker.add("大王");
System.out.println(poker.size());
// 下一步洗牌吧。
Collections.shuffle(poker);// shuffle方法是洗牌,让54张牌交换位置嘞。
// System.out.println(poker);
// 洗完后发牌了吧;三个人玩,所以创建三个集合。
ArrayList<String> gaojin = new ArrayList<>();// 高进同学的第一个人的牌。
ArrayList<String> longwu = new ArrayList<>();// 龙武同学的牌
ArrayList<String> me = new ArrayList<>();// 我的牌。
ArrayList<String> dipai = new ArrayList<>();//底牌三张
//发牌了!
for (int i = 0; i < poker.size(); i++) {
if (i >= poker.size() - 3) { // 54张牌嘛,最后三张你懂得,如果最后的底牌就添加到底牌集合中。
dipai.add(poker.get(i));
} else if (i % 3 == 0) { // 0 3 6 9 嘛,就发给高进。
gaojin.add(poker.get(i));
} else if (i % 3 == 1) { // 4 7 10 13 嘛,就发给龙武同学。。
longwu.add(poker.get(i));
} else {
me.add(poker.get(i));
}
}
// 有牌了,接下来就是看牌把。
System.out.println("高进同学的牌:"+gaojin);
System.out.println("龙武同学的牌:"+longwu);
System.out.println("我的牌:"+me);
System.out.println("底牌:"+dipai);
}
}
运行结果:
排序后:
package File;
import java.util.*;
public class Poker02 {
public static void main(String[] args) {
// 买一幅扑克,卡牌点数。
String[] num = {"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"};
// 四种花色
String[] color = {"方片", "梅花", "红桃", "黑桃"};
HashMap<Integer, String> hm = new HashMap<>();
ArrayList<Integer> list = new ArrayList<>();
int index = 0;
for (String s1 : num) {
for (String s2 : color) {
hm.put(index,s2.concat(s1));
list.add(index);
index++;
}
}
hm.put(index,"小王");
list.add(index);
index++;
hm.put(index,"大王");
list.add(index);
// 洗牌
Collections.shuffle(list);
// 发牌
TreeSet<Integer> gaojin = new TreeSet<>();
TreeSet<Integer> longwu = new TreeSet<>();
TreeSet<Integer> me = new TreeSet<>();
TreeSet<Integer> dipai = new TreeSet<>();
for (int i = 0; i <list.size() ; i++) {
if (i >= list.size() - 3) { // 54张牌嘛,最后三张你懂得,如果最后的底牌就添加到底牌集合中。
dipai.add(list.get(i));
} else if (i % 3 == 0) { // 0 3 6 9 嘛,就发给高进。
gaojin.add(list.get(i));
} else if (i % 3 == 1) { // 4 7 10 13 嘛,就发给龙武同学。。
longwu.add(list.get(i));
} else {
me.add(list.get(i));
}
}
// 看牌
lookPoker("高进",gaojin,hm);
lookPoker("龙武",longwu,hm);
lookPoker("我",me,hm);
lookPoker("底牌",dipai,hm);
}
public static void lookPoker(String name,TreeSet<Integer> ts,HashMap<Integer,String> hm){
System.out.println(name+"的牌是:");
for (Integer index : ts) {
System.out.print(hm.get(index)+" ");
}
System.out.println();
}
}
运行结果