本文摘自:https://funyan.cn/p/403.html
需求分析
按照鬥地主的規則,完成洗牌發牌的動作。
具體規則:
使用54張牌打亂順序,三個玩家參與遊戲,三人交替摸牌,每人17張牌,最後三張留作底牌。
代碼實作
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
/**
*
**/
public class Poker
{
public static void main(String[] args) {
//準備牌,54張牌,其中兩張大小王,其他為不同花色的牌
//一盒牌的集合
ArrayList<String> PokerBox=new ArrayList<>();
//把大小王加進去
PokerBox.add("大王");
PokerBox.add("小王");
//将其他牌加進來
//定義兩個數組
String[] colors={"♥","♠","♦","♣"};
String[] num={"A","2","K","Q","J","10","9","8","7","6","5","4","3"};
for (int i = 0; i < num.length; i++) {
for (int j = 0; j < colors.length; j++) {
PokerBox.add(colors[j]+num[i]);
}
}
//洗牌
Collections.shuffle(PokerBox);
//發牌
//發51張牌,剩餘當做底牌不發
//建立四個集合,用于接收牌
ArrayList<String> zhangsan=new ArrayList<>();
ArrayList<String> lisi=new ArrayList<>();
ArrayList<String> wangwu=new ArrayList<>();
ArrayList<String> bottomPoker=new ArrayList<>();
for (int i = 0; i < PokerBox.size(); i++) {
if(i<51){
//正常發牌
switch (i%3){
case 0: zhangsan.add(PokerBox.get(i));break;
case 1: lisi.add(PokerBox.get(i));break;
case 2: wangwu.add(PokerBox.get(i));break;
}
}else{
bottomPoker.add(PokerBox.get(i));
}
}
//看牌
System.out.println("張三的牌:"+zhangsan);
System.out.println("李四的牌:"+lisi);
System.out.println("王五的牌:"+wangwu);
System.out.println("底牌:"+bottomPoker);
}
}
結果
張三的牌:[♣6, ♠2, ♣10, ♥10, ♠3, ♠5, ♥7, ♥J, ♦9, ♠J, ♦10, ♥A, ♠10, ♥Q, ♣9, ♣K, ♠Q]
李四的牌:[♥9, ♦K, ♥8, ♠4, ♦Q, ♥2, ♦7, ♦2, ♦J, ♠A, ♦8, ♥4, 小王, ♥3, ♠9, ♣8, ♥6]
王五的牌:[♣Q, ♣3, ♣A, ♦A, ♠K, ♦4, ♠6, ♣J, ♦5, ♥5, ♦3, ♣4, ♦6, ♥K, 大王, ♣2, ♣5]
底牌:[♣7, ♠7, ♠8]