java集合框架的练习之斗地主洗牌发牌的模拟(初级版)

要点:

  Collections是java.util下的类,它包含有各种有关集合操作的静态方法。集中,Collections.shuffle()可使集合所存内容随机置换.



要求:

   模拟斗地主洗牌和发牌,牌没有排序



分析:

 1.创建一副扑克
 2.洗牌
 3.发牌
 4.看牌
          


代码:

import java.util.ArrayList;
import java.util.Collections;

public class Poker_Collections_shuffle_1 {

    public static void main(String[] args) {
        
        /*创建一副扑克*/
        String[] num = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
        String[] color = {"黑桃", "红桃", "梅花", "方块"};

        ArrayList<String> poker = new ArrayList<>();
        for (String s1 : num) {    
            for (String s2 : color) {
                poker.add(s2.concat(s1));    // concat() ==> 连接两个字符串
            }
        }
        poker.add("小王");
        poker.add("大王");
        
        /*洗牌*/
        Collections.shuffle(poker);       // Collections.shuffle() ==> 随机置换

        /*发牌*/
        ArrayList<String> player1 = new ArrayList<>();
        ArrayList<String> player2 = new ArrayList<>();
        ArrayList<String> myself = new ArrayList<>();
        ArrayList<String> dipai = new ArrayList<>();
        
        for (int i = 0; i < poker.size(); i++) {
            if (i >= poker.size() - 3) {
                dipai.add(poker.get(i));
            } else if (i%3 == 0) {
                player1.add(poker.get(i));
            } else if (i%3 == 1) {
                player2.add(poker.get(i));
            } else {
                myself.add(poker.get(i));
            }
        }
        
        /*看牌*/
        System.out.println("Player1的牌为: " + player1);
        System.out.println("Player2的牌为: " + player2);
        System.out.println("myself 的牌为: " + myself);
        System.out.println("底牌: " + dipai);
    }
}



运行调试:






查阅相关代码请点击: https://github.com/striner/javaCode/blob/master/Fight%20the%20Landlord_1







猜你喜欢

转载自blog.csdn.net/striner/article/details/78489306