package 扑克牌分发; import java.util.Arrays; import java.util.Comparator; import java.util.Random; public class PaiHe { private ArrayList pais = new ArrayList(53); public PaiHe() { for (HuaSe tmp : HuaSe.values()) { for (int k = 4; k < 17; k++) { pais.add(new Pai(k, tmp)); } } } public Pai[] faPai() { Random r = new Random(); Pai[] res = new Pai[16]; for (int i = 0; i < res.length; i++) { int pos = r.nextInt(pais.size()); Object p = pais.delete(pos); if (p != null && p instanceof Pai) { Pai pp = (Pai) p; res[i] = pp; } } return res; } public static void main(String[] args) { PaiHe ph = new PaiHe(); for (int i = 0; i < 3; i++) { Pai[] arr = ph.faPai(); Arrays.sort(arr, new ComparatorPai.java文件() { public int compare(Pai o1, Pai o2) { int res = o1.getNum() - o2.getNum(); if (res == 0) { res = o1.getColor().compareTo(o2.getColor()); } return res; } }); System.out.println(Arrays.toString(arr)); } System.out.println("底牌:"); System.out.println(Arrays.toString(ph.getPais().getData())); } public ArrayList getPais() { return pais; } }
package 扑克牌分发; public class Pai implements ComparableArrayList.java文件{ private final int num; // 1-13 private final HuaSe color; public Pai(int num, HuaSe color) { this.num = num; this.color = color; } public int getNum() { return num; } public HuaSe getColor() { return color; } public String toString() { String aa = "" + num; if (num > 10) { if (num == 11) aa = "J"; else if (num == 12) { aa = "Q"; } else if (num == 13) aa = "K"; else if(num==14) aa="A"; else if(num==15) aa="2"; else if(num==16) aa="3"; } String res = "(" + aa + ":" + color + ")"; return res; } @Override public int compareTo(Pai o) { // TODO Auto-generated method stub return 0; } }
package 扑克牌分发; import java.util.Arrays; public class ArrayList { private Comparable[] arr; private int size = 0; public ArrayList() { this(10); } public ArrayList(int length) { arr = new Comparable[length]; } public void add(Comparable data) { arr[size++] = data; if (size >= arr.length) resize(); } public Comparable delete(int index) { if (index >= size || size < 0) throw new ArrayIndexOutOfBoundsException(); Comparable res = arr[index]; System.arraycopy(arr, index + 1, arr, index, arr.length - index - 1); arr[size - 1] = null; size--; return res; } public void update(int index, Comparable data) { if (index >= size || size < 0) throw new ArrayIndexOutOfBoundsException(); arr[index] = data; } public Comparable[] getData() { return this.arr; } public String toString() { return Arrays.toString(arr); } private void resize() { Comparable[] res = new Comparable[arr.length * 3 / 2]; System.arraycopy(arr, 0, res, 0, arr.length); this.arr = res; } public int size() { return this.size; } public Comparable[] sort() { Comparable[] res = getData(); Arrays.sort(res); return res; } }HuaSe.java文件
package 扑克牌分发; public enum HuaSe { HEI("黑桃"), HONG("红桃"), MEI("梅花"), FANG("方块"); private String name; private HuaSe(String name) { this.name = name; } public String toString() { return this.name; } }实现