public class Poker implements Comparable<Poker>{ /*每张牌包含花色和数字两个属性*/ private String colour; private String figure; //id private int id; @Override public int compareTo(Poker o) { return this.id - o.id; } public Poker() { } public Poker(String colour, String figure, int id) { this.colour = colour; this.figure = figure; this.id = id; } /** * 获取 * @return colour */ public String getColour() { return colour; } /** * 设置 * @param colour */ public void setColour(String colour) { this.colour = colour; } /** * 获取 * @return figure */ public String getFigure() { return figure; } /** * 设置 * @param figure */ public void setFigure(String figure) { this.figure = figure; } /** * 获取 * @return id */ public int getId() { return id; } /** * 设置 * @param id */ public void setId(int id) { this.id = id; } public String toString() { return colour + figure; } }
上面的是创建一个Poker的类 私有化成员变量
import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Room { public void poker (){ List<Poker> list = new ArrayList<>(); String[] numbers = new String[]{"3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A", "2"}; String[] colors = new String[]{"♠", "♥", "♣", "♦"}; list.add(new Poker("大王", "", 0)); list.add(new Poker("小王", "", 1)); // id从2开始 因为0 1 分别给大小王 int id = 2; // 利用增强for 循环嵌套 外部循环numbers一次 内部循环color花色循环一轮 // 使数字呈现 ♠3, ♥3, ♣3, ♦3, ♠4, ♥4, ♣4, ♦4,这样的格式 for (String number : numbers) { for (String color : colors) { // id代表着这个数的编号 可以理解为数组的索引 就算洗牌洗乱了 这个编号还是一样的 Poker poker = new Poker(color, number, id); list.add(poker); id++; } } System.out.println(list); // 洗牌 运用Collections.shuffle 打乱顺序 Collections.shuffle(list); System.out.println("洗牌后:" + list); // 发牌 ArrayList<Poker> player01 = new ArrayList<>(); ArrayList<Poker> player02 = new ArrayList<>(); ArrayList<Poker> player03 = new ArrayList<>(); ArrayList<Poker> dipai = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { Poker poker = list.get(i); // 判断i要是大于或者等于的时候 这时候代表是最后的三张牌 作为地主牌 如果你想要首三张 同理 if (i >= 51) { dipai.add(poker); // 对i磨3 如果磨3的数等于0 那就发给1号玩家 } else if (i % 3 == 0) { player01.add(poker); // 对i磨3 如果磨3的数等于1 那就发给1号玩家 } else if (i % 3 == 1) { player02.add(poker); // 对i磨3 如果磨3的数等于2 那就发给1号玩家 } else if (i % 3 == 2) { player03.add(poker); } } // 给玩家手上的牌 排序 Collections.sort(player01); Collections.sort(player02); Collections.sort(player03); // 看牌 System.out.println("玩家1的牌: " + player01); System.out.println("玩家2的牌: " + player02); System.out.println("玩家3的牌: " + player03); System.out.println("地主牌: " + dipai); } }