思路:
1.先要实现洗牌;
2.然后去实现给每一个玩家发牌;
3.最后,再到每一个玩家看牌。
代码如下:
import java.util.*;public class Poker {public static void main(String[] args) {HashMap<Integer, String> hm = new HashMap<Integer, String>();ArrayList<Integer> array = new ArrayList<Integer>();
// 字符串数组来装牌的花色String[] color = {"♦","♣","♥","♠"};
// 字符串数组来装牌的大小String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};int index = 0;
// 一定是外层循环是牌的大小,内层循环是花色for (String num1 : num) {for (String color1 : color) {hm.put(index,color1+num1);array.add(index);index++;}}hm.put(index,"小王");array.add(index);index++;hm.put(index,"大王");array.add(index);
// 实现洗牌Collections.shuffle(array);
// 用TreeSet来实现对牌的排序TreeSet<Integer> player1 = new TreeSet<Integer>();TreeSet<Integer> player2 = new TreeSet<Integer>();TreeSet<Integer> player3 = new TreeSet<Integer>();TreeSet<Integer> dp = new TreeSet<Integer>();for (int i = 0; i < array.size() ; i++) {int s = array.get(i);
// 最后三张就是底牌if (i >= array.size()-3) {dp.add(s);}else if (i % 3 == 0) {player1.add(s);}else if (i % 3 == 1) {player2.add(s);}else if (i % 3 == 2) {player3.add(s);}}lookPoker("张三",player1,hm);lookPoker("李四",player2,hm);lookPoker("王二麻子",player3,hm);lookPoker("底牌",dp,hm);}public static void lookPoker(String name,TreeSet<Integer> t,HashMap<Integer,String> hm) {System.out.println(name+"的牌是:");for (Integer key : t) {String poker = hm.get(key);System.out.print(poker + " ");}System.out.println();}
}
运行结果如下:
总结:
定义一个HashMap和ArrayList,HashMap用来装牌的索引和牌,ArrayList装牌的索引,运用数组将索引与牌的大小相结合;再用Collections中的方法来实现洗牌,用TreeSet集合来接收三个玩家的牌和底牌,实现发牌,最后定义看牌的方法,再调用,这样就实现斗地主的简单版了。