目录
一、创建扑克牌Poker
二、游戏玩法创建
2.1买牌
2.2洗牌
2.3揭牌
三、测试游戏代码
在游戏开始之前要创建扑克牌,其中扑克牌要具有花色和数字,而且要记住除了大小王以外,扑克牌工有四种花色,52张牌。要重写toString方法!!
代码如下:
public class Poker {
private String suit;//花色
private int rank;//数字
public Poker(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public String getSuit() {
return suit;
}
public void setSuit(String suit) {
this.suit = suit;
}
public int getRank() {
return rank;
}
public void setRank(int rank) {
this.rank = rank;
}
@Override
public String toString() {
return "{ "+suit+" "+rank+"}";
}
}
要先将52张扑克牌创建出来,并添加到集合中,以便于后续操作。
private static final String[] suits = {"♥","♣","♦","♠"};
public List buyPoker(){
List pokers = new ArrayList<>();
for (int i = 0; i < 4; i++) {
for (int j = 1; j <= 13; j++) {
Poker poker = new Poker(suits[i], j);
pokers.add(poker);
}
}
return pokers;
}
在玩之前,要将买来的牌用Random函数进行重新打乱,以便于每个人手中的牌大小不一样。
public void shuffle(List pokers){
for (int i = pokers.size()-1; i > 0; i--) {
Random random = new Random();
int index = random.nextInt(i);
swap(pokers,i,index);
}
}
private void swap(List pokers, int i, int j){
Poker tmp = pokers.get(i);
pokers.set(i,pokers.get(j));
pokers.set(j,tmp);
}
每个人要进行抓牌,设置每个人手中抓五张牌,三个人进行游戏。
public List> game(List pokers){
List> hand = new ArrayList<>();
List hand1 = new ArrayList<>();
List hand2 = new ArrayList<>();
List hand3 = 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++) {
Poker removePoker = pokers.remove(0);
hand.get(j).add(removePoker);
}
}
return hand;
}
public static void main(String[] args) {
Game game = new Game();
List pokers = game.buyPoker();
System.out.println(pokers);
//洗牌
game.shuffle(pokers);
System.out.println("洗牌:");
System.out.println(pokers);
//揭牌
List> hand = game.game(pokers);
System.out.println("揭牌:");
for (int i = 0; i < hand.size(); i++) {
System.out.println("第 "+(i+1)+"个人的牌:"+hand.get(i));
}
System.out.println("剩下的牌");
System.out.println(pokers);
}