java鬥地主範例_Java鬥地主範例

package com.chunzhi.Test04Poker;

import java.util.ArrayList;

import java.util.Collections;

/*

鬥地主綜合範例:

1.準備牌

2.洗牌

3.發牌

4.看牌

*/

public class DouDiZhu {

public static void main(String[] args) {

// 1.準備牌

// 定義一個儲存54張牌的ArrayList集合,泛型使用String

ArrayList poker = new ArrayList<>();

// 定義兩個陣列,一個陣列儲存牌的花色,另一個陣列儲存牌的序號

String[] colors = {"?", "?", "?", "?"};

String[] numbers = {"2", "A", "K", "Q", "J", "10", "9", "8", "7", "6", "5", "4", "3"};

// 先把大王、小王儲存到poker集合中

poker.add("大王");

poker.add("小王");

// 迴圈巢狀遍歷兩個陣列,組裝52張牌

for (String number : numbers) {

for (String color : colors) {

// System.out.println(color + number);

// 把組裝好的牌儲存到poker當中

poker.add(color + number);

}

}

// System.out.println(poker);

/*

2.洗牌

使用集合的工具類Collections中的方法

static void shuffle(List> list) 使用預設隨機源對指定串列進行置換

*/

Collections.shuffle(poker);

// System.out.println(poker);

/*

3.發牌

*/

// 定義四個集合,儲存玩家的牌和底牌

ArrayList player1 = new ArrayList();

ArrayList player2 = new ArrayList();

ArrayList player3 = new ArrayList();

ArrayList diPai = new ArrayList();

/*

遍歷poker集合,取得每一張牌

使用poker集合的索引%3給3個玩家輪流發牌

剩餘3張牌給底牌

注意:

先判斷底牌(i >= 51)

*/

for (int i = 0; i < poker.size(); i++) {

// 取得每一張牌

String p = poker.get(i);

// 輪流發牌

if (i >=51) {

// 給底牌發牌

diPai.add(p);

} else if (i%3 == 0) {

// 給玩家1發牌

player1.add(p);

} else if (i%3 == 1) {

// 給玩家2發牌

player2.add(p);

} else if (i%3 == 2) {

// 給玩家3發牌

player3.add(p);

}

}

/*

4.看牌

*/

System.out.println("周星馳:" + player1);

System.out.println("周潤發:" + player2);

System.out.println("劉德華:" + player3);

System.out.println("底牌:" + diPai);

}

}