思路:
首先我们定义一个Card类,类成员有花色(suit),牌面值(rank)。
class Card{
private String suit;//花色
private int rank;//牌面值
public Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
然后我们“买牌”,“洗牌”等方法。
(1)买牌
牌的花色是固定且不变的,所以我们将其定义为static final,其次我们用List<Card>类型来接收
public static final String[] suits = {"♥","♠","♦","♣"};
// 买一副牌
public static List<Card> buyCard(){
List<Card> cards = new ArrayList<>();
for (int i = 0; i <4 ; i++) {
for (int j = 1; j <=13 ; j++) {
cards.add(new Card(suits[i],j ));
}
}
return cards;
}
(2)洗牌
从后往前洗
// 洗牌
public static void shuffle(List<Card> cards){
Random random = new Random();
for (int i =cards.size()-1; i >0 ; i--) {
int index = random.nextInt(i);
// 交换
Card tmp = cards.get(i);
cards.set(i,cards.get(index));
cards.set(index,tmp);
}
}
(3)抓牌
定义一个List<List<Card>>来接收每个人的牌(List<Card>)
/ 开始抓牌
List<List<Card>> hands = new ArrayList<>();
List<Card> hand1 = new ArrayList<>();
List<Card> hand2 = new ArrayList<>();
List<Card> hand3 = new ArrayList<>();
hands.add(hand1);
hands.add(hand2);
hands.add(hand3);
//每人轮流抓一张牌,一共抓五张
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
hands.get(j).add(cards.remove(0));
}
}
完整代码
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Card{
private String suit;//花色
private int rank;//牌面值
public Card(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
@Override
public String toString() {
return "花色:"+suit+"面值:"+rank;
}
}
public class CardDemo {
public static final String[] suits = {"♥","♠","♦","♣"};
// 买一副牌
public static List<Card> buyCard(){
List<Card> cards = new ArrayList<>();
for (int i = 0; i <4 ; i++) {
for (int j = 1; j <=13 ; j++) {
cards.add(new Card(suits[i],j ));
}
}
return cards;
}
// 洗牌
public static void shuffle(List<Card> cards){
Random random = new Random();
for (int i =cards.size()-1; i >0 ; i--) {
int index = random.nextInt(i);
// 交换
Card tmp = cards.get(i);
cards.set(i,cards.get(index));
cards.set(index,tmp);
}
}
public static void main(String[] args) {
List<Card> cards = buyCard();
System.out.println("刚买的牌");
System.out.println(cards);
System.out.println("洗过的牌");
shuffle(cards);
System.out.println(cards);
// 开始抓牌
List<List<Card>> hands = new ArrayList<>();
List<Card> hand1 = new ArrayList<>();
List<Card> hand2 = new ArrayList<>();
List<Card> hand3 = new ArrayList<>();
hands.add(hand1);
hands.add(hand2);
hands.add(hand3);
//每人轮流抓一张牌,一共抓五张
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 3; j++) {
hands.get(j).add(cards.remove(0));
}
}
System.out.println("A手中的牌");
System.out.println(hand1);
System.out.println("B手中的牌");
System.out.println(hand2);
System.out.println("C手中的牌");
System.out.println(hand3);
System.out.println("剩余的牌");
System.out.println(cards);
}
}
运行结果