摸牌是需要一副牌的,所以首先我们需要构造出一个纸牌类card,之后再用顺序表构造出一副牌
public class Card {
private int rank;
private String suit;
public Card(int rank, String suit) {
this.rank = rank;
this.suit = suit;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
@Override
public String toString() {
return "数字:" + rank + ", 花色:" + suit ;
}
}
下面的代码是洗牌类,中间包括构建一副牌,然后通过随机数random来随机洗牌
public class ShuffleCard {
//买一副牌
public ArrayList<Card> buyCard(){
//四种花色
final String [] suit=new String[]{"♥","♠","♣","♦"};
//十四张牌
final int[] rank=new int[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14};
//创建一个顺序表,当一副牌
ArrayList<Card> cardList=new ArrayList<>();
for (int j = 0; j < 14; j++) {
for (int i = 0; i < 4; i++) {
Card card=new Card(rank[j],suit[i]);
cardList.add(card);
}
}
return cardList;
}
public static void swap(ArrayList<Card>cardList,int i,int j){
Card temp=cardList.get(i);
cardList.set(i,cardList.get(j));
cardList.set(j,temp);
}
//洗牌
public ArrayList<Card> shuffleCard(ArrayList<Card> cardList){
Random r=new Random();
for (int i = 0; i < cardList.size()-2; i++) {
int j=r.nextInt(i+1);
swap(cardList,i,j);
}
return cardList;
}
}
好了,以上就已经完成了类的构建,然后只需要在 main方法中创建三个人再完成摸牌的过程就好啦。
import ArrayCard.*;
import java.util.ArrayList;
public class Main {
public static void main(String[] args) {
ShuffleCard cardDome=new ShuffleCard();
//买牌
ArrayList<Card> cardList= cardDome.buyCard();
System.out.println("买的牌如下:");
System.out.println(cardList);
//洗牌
cardDome.shuffleCard(cardList);
System.out.println("洗牌:");
System.out.println(cardList);
//创建一个三个人的顺序表
ArrayList<ArrayList<Card>> hands=new ArrayList<>();
hands.add(new ArrayList<Card>());
hands.add(new ArrayList<Card>());
hands.add(new ArrayList<Card>());
//摸牌
for(int i=0;i<5;i++){
for(int j=0;j<3;j++){
//每个人依次从cardList中拿牌
hands.get(j).add(cardList.remove(0));
}
}
System.out.println("这是摸牌后剩余的牌");
System.out.println(cardList);
System.out.println("这是每个人的牌");
for (int i = 0; i < 3; i++) {
System.out.println("第" + (i+1)+"个人:");
System.out.println(hands.get(i));
}
}
}
难点在于对顺序表方法的应用,在创建三个人的时候,要注意到每一个人都是一个顺序表,所以相当于一个顺序表数组。