import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class zjh {
private String suit;//花色
private int rank;//数字
public zjh(String suit, int rank) {
this.suit = suit;
this.rank = rank;
}
public zjh() {
// TODO Auto-generated constructor stub
}
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+"}"; //重写toString方法,调用时产生花色与牌号
}
private static final String[] suits = {"♥","♣","♦","♠"};
public List<zjh> takePoker(){
List<zjh> pokers = new ArrayList<>();
for (int i = 0; i < 4; i++) { //外循环为4种花色
for (int j = 1; j <= 13; j++) { //内循环为A~K13张牌
zjh poker = new zjh(suits[i], j);
pokers.add(poker); //通过循环产生52张牌并放入集合中
}
}
return pokers;
}
public void shuffle(List<zjh> pokers){
for (int i = pokers.size()-1; i > 0; i--) {
Random random = new Random(); //用random随机函数打乱牌序
int index = random.nextInt(i);
swap(pokers,i,index);
}
}
private void swap(List<zjh> pokers, int i, int j){
zjh tmp = pokers.get(i);
pokers.set(i,pokers.get(j)); //调用时,产生随机的花色和数字
pokers.set(j,tmp);
}
public List<List<zjh>> game(List<zjh> pokers){
List<List<zjh>> hand = new ArrayList<>();
List<zjh> hand1 = new ArrayList<>();
List<zjh> hand2 = new ArrayList<>();
List<zjh> 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++) {
zjh removePoker = pokers.remove(0); //循环控制三个人轮流摸牌,一人摸五张,一共15张
hand.get(j).add(removePoker);
}
}
return hand;
}
public static void main(String[] args) {
zjh game = new zjh();
List<zjh> pokers = game.takePoker();
System.out.println(pokers);
//洗牌
game.shuffle(pokers);
System.out.println("洗牌:");
System.out.println(pokers);
//揭牌
List<List<zjh>> 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);
}
}
炸金花作业
最新推荐文章于 2024-10-27 19:55:47 发布