ArrayList的使用方法:
public class Card {
? ? public int rank;//牌面色
? ? public String suit;//花色
? ? public Card(String suit,int rank) {
? ? ? ? this.rank = rank;
? ? ? ? this.suit = suit;
? ? }
? ? @Override
? ? public String toString() {
? ? ? ? return suit + " " + rank;
? ? }
}
public class Test {
? ? //花色: 紅桃 黑桃 梅花 方片
? ? private static final String[] SUITS = {"?","?","?","?"};
? ? public static void main(String[] args) {
? ? ? ? List<Card> cards = buyCard();//買牌
? ? ? ? System.out.println(cards);
? ? ? ? System.out.println("洗牌:");
? ? ? ? shuffle(cards);
? ? ? ? System.out.println(cards);
? ? ? ? //三個人每個人輪流揭5張牌
? ? ? ? List<Card> hand1 = new ArrayList<>();
? ? ? ? List<Card> hand2 = new ArrayList<>();
? ? ? ? List<Card> hand3 = new ArrayList<>();
? ? ? ? List<List<Card>> hand = new ArrayList<>();
? ? ? ? hand.add(hand1);
? ? ? ? hand.add(hand2);
? ? ? ? hand.add(hand3);
? ? ? ? for (int i = 0; i < 5; i++) {
? ? ? ? ? ? for (int j = 0; j < 3; j++) {
? ? ? ? ? ? ? ? //揭牌動作
? ? ? ? ? ? ? ? Card card = cards.remove(0);
? ? ? ? ? ? ? ? //如何翻到指定人的手里呢?
? ? ? ? ? ? ? ? hand.get(j).add(card);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? System.out.println("第1個人的牌:");
? ? ? ? System.out.println(hand1);
? ? ? ? System.out.println("第2個人的牌:");
? ? ? ? System.out.println(hand2);
? ? ? ? System.out.println("第3個人的牌:");
? ? ? ? System.out.println(hand3);
? ? }
? ? private static void shuffle(List<Card> cards) {
? ? ? ? Random random = new Random();
? ? ? ? for (int i = cards.size() - 1; i > 0; i--) {
? ? ? ? ? ? int j = random.nextInt(i);
? ? ? ? ? ? //交換
? ? ? ? ? ? Card card = cards.get(i);
? ? ? ? ? ? cards.set(i,cards.get(j));
? ? ? ? ? ? cards.set(j,card);
? ? ? ? }
? ? }
? ? private static List<Card> buyCard() {
? ? ? ? List<Card> cards = new ArrayList<>();
? ? ? ? for (int i = 0; i < SUITS.length; i++) {
? ? ? ? ? ? for (int j = 1; j <= 13; j++) {
? ? ? ? ? ? ? ? Card card = new Card(SUITS[i],j);
? ? ? ? ? ? ? ? cards.add(card);
? ? ? ? ? ? }
? ? ? ? }
? ? ? ? return cards;
? ? }
}
輸出結果:
? ? [? 1, ? 2, ? 3, ? 4, ? 5, ? 6, ? 7, ? 8, ? 9, ? 10, ? 11, ? 12, ? 13, ? 1, ? 2, ? 3, ? 4, ? 5, ? 6, ? 7, ? 8, ? 9, ? 10, ? 11, ? 12, ? 13, ? 1, ? 2, ? 3, ? 4, ? 5, ? 6, ? 7, ? 8, ? 9, ? 10, ? 11, ? 12, ? 13, ? 1, ? 2, ? 3, ? 4, ? 5, ? 6, ? 7, ? 8, ? 9, ? 10, ? 11, ? 12, ? 13]
? ? 洗牌:
? ? [? 11, ? 7, ? 8, ? 2, ? 9, ? 10, ? 1, ? 11, ? 7, ? 12, ? 6, ? 3, ? 4, ? 12, ? 5, ? 13, ? 10, ? 3, ? 11, ? 12, ? 6, ? 7, ? 5, ? 6, ? 13, ? 4, ? 13, ? 6, ? 12, ? 8, ? 9, ? 5, ? 3, ? 10, ? 8, ? 4, ? 8, ? 13, ? 2, ? 2, ? 5, ? 1, ? 10, ? 3, ? 11, ? 9, ? 1, ? 1, ? 7, ? 2, ? 4, ? 9]
? ? 第1個人的牌:
? ? [? 11, ? 2, ? 1, ? 12, ? 4]
? ? 第2個人的牌:
? ? [? 7, ? 9, ? 11, ? 6, ? 12]
? ? 第3個人的牌:
? ? [? 8, ? 10, ? 7, ? 3, ? 5]
?