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]