分别实现扑克牌的买牌,洗牌,以及拿牌操作:
完整代码:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
class Card{
private String color;//花色
private int number;//牌面
public Card(String color, int number) {
this.color = color;
this.number = number;
}
@Override
public String toString() {
return ("花色:"+color+"牌面:"+number);
}
}
public class TestCard {
public static List<Card> buyCard(){//买牌
String[] colors={"♥","♠","♣","♦"};
List<Card> cards=new ArrayList<>();
for (int i=0;i<4;i++){
for (int j=0;j<13;j++){
Card card=new Card(colors[i],j);
cards.add(card);
}
}
return cards;
}
public static List<Card> washCard(List<Card> cards){//洗牌
Random random=new Random();
for (int i=cards.size()-1;i>=0;i--){
int index=random.nextInt(cards.size());
Card temp=cards.get(i);
cards.set(i,cards.get(index));
cards.set(index,temp);
}
return cards;
}
public static List<List<Card>> handOut(List<Card> cards){//相当于二维数组
List<List<Card>> hands=new ArrayList<>();
for (int i=0;i<4;i++){
List<Card> hand=new ArrayList<>();
hands.add(hand);
}
for (int i=0;i<5;i++){
for (int j=0;j<3;j++){
hands.get(j).add(cards.remove(0));//拿第一个位置的牌,拿起后该牌相当于删除
}
}
return hands;
}
public static void main(String[] args) {
System.out.println("买牌:"+buyCard());
System.out.println("洗牌:"+washCard(buyCard()));
System.out.println("三人拿牌"+handOut(buyCard()));
}
}