定义了一个名为demo的包,然后在包里面有三个文件:
- Test.java 文件
- Poker.java 文件
- Game.java 文件
有了上面三个文件作为基础,请跟着笔者来实现炸金花游戏吧!!
在Poker.java 文件中,有着花色与数字的定义的内容:
private String suit; //花色
private int rank; //数字
Test.java文件里面的代码为:
package demo;
import java.util.List;
public class Test {
public static void main(String[] args) {
//生成52张牌
Game game = new Game();
List<Poker> pokers = game.buyPoker();
System.out.println(pokers);
//洗牌
game.shuffle(pokers);
System.out.println("洗牌!");
System.out.println(pokers);
//揭牌
List<List<Poker>> 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);
}
}
Game.java 文件里面的代码为:
package demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class Game {
private static final String[] suit ={"♠","♥","♣","♦"};
//生成52张牌
public List<Poker>buyPoker(){
List<Poker> pokers = new ArrayList<>();
for (int i = 0; i < 4; i++) { //四种花色
for (int j = 1; j <= 13; j++) {
//扑克牌中的数字大小(从1到13,进行简单的区分)
Poker poker = new Poker(suit[i], j);
pokers.add(poker);
}
}
return pokers;
}
//实现洗牌操作 仅仅打乱顺序即可!!
public void shuffle(List<Poker> pokers) {
for (int i = pokers.size()-1; i > 0; i--) {
//当i等于0的时候,就不用换牌了!
Random random = new Random();
int index =random.nextInt(i);//生成随机数[0,i)
swap(pokers,i,index);//交换
}
}
//交换
private void swap(List<Poker> pokers , int i, int j) {
Poker tmp =pokers.get(i);
pokers.set(i,pokers.get(j));
pokers.set(j,tmp);
}
//揭牌的简单实现
public List<List<Poker>> game(List<Poker> pokers) {
List<List<Poker>> hand =new ArrayList<>();
List<Poker> hand1 =new ArrayList<>();
List<Poker> hand2 =new ArrayList<>();
List<Poker> hand3 =new ArrayList<>();
hand.add(hand1);
hand.add(hand2);
hand.add(hand3);
//最外层循环控制轮数
for (int i = 0; i < 3; i++) {
//三个人
for (int j = 0; j < 3; j++) {
//每个人只能摸三张牌
Poker removePoker =pokers.remove(0);//返回0下标所对应的这张牌
//删除哪个下标,就会把哪个下标所对应的值进行返回
hand.get(j).add(removePoker);
}
}
return hand;
}
}
Poker.java 文件里面的代码为:
package demo;
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;
}
//重写toString方法
@Override
public String toString() {
return "{" +suit +" "+rank+"}";
}
}
运行结果