用数组和集合实现斗地主案例

一、准备54张牌,存储到一个集合中

2张特殊牌:大王,小王
其他52张牌,定义两个数组
数组一:储存5个花色♠,♥,♣,♦
数组二:储存13个序号(由大到小)2,A,K,Q…5,4,3

import java.util.ArrayList;

public class Doudizhu {
    public static void main(String[] args) {
//         一、准备牌
        String [] colors = {"♠","♥","♣","♦"};          //定义两个数组,一个储存花色,一个储存序号
        String [] numbers = {"2 ","A ","K ","Q ","J ","10 "," 9"," 8","7 "," 6"," 5"," 4","3 ",};
        ArrayList<String> poker = new ArrayList();          // 定义一个能存储54张牌的ArrarList集合,泛型使用String
        poker.add("大王");            // 先把两张特殊牌(大王,小王)存进集合。
        poker.add("小王");
//            用加强for循环遍历两个数组,组装52张牌
        for (String number:numbers){
            for (String color:colors){
                poker.add(number+color);      //把组装好的牌存进集合
            }
        }
        System.out.println(poker);          //打印出54张牌
    }
}

二、洗牌

使用集合的工具类collections中的shuffle方法将组装好的54张牌打乱顺序
1,先导入Collections工具类

import java.util.Collections;

2,使用shuffle方法

 Collections.shuffle(poker);         //使用shuffle()打乱集合中的元素顺序

三、发牌

定义四个集合,存储发给三个玩家的牌和三张底牌


        ArrayList<String> Play1 = new ArrayList<>();            //存储玩家一的牌
        ArrayList<String> Play2 = new ArrayList<>();            //存储玩家二的牌
        ArrayList<String> Play3 = new ArrayList<>();            //存储玩家三的牌
        ArrayList<String> dipai = new ArrayList<>();            //存储3张底牌 

遍历poker集合,获取每一张牌,使用poker集合的索引%3给三个玩家轮流发牌
剩余三张牌给底牌
注意:先判断底牌索引值(i>=51),否则牌发没了

 for (int i = 0; i <= 53; i++) {
            String p = poker.get(i);            //获取每一张牌
            if (i >= 51){
                dipai.add(p);           //发底牌
            }else if (i%3 == 0){
                Play1.add(p);           //给玩家一发牌
            }else if(i%3 == 1){
                Play2.add(p);           //给玩家二发牌
            }else if (i%3 == 2){
                Play3.add(p);           //给玩家三发牌
            }
        }

四、看牌

打印出三个玩家的牌和底牌

  		System.out.println(Play1);
        System.out.println(Play2);
        System.out.println(Play3);
        System.out.println(dipai);

五、运行结果

周润发:[ 5, 3, A ♥, 7, 3, J ♣,  8, 10, 7,  6, 10,  9, J ♦,  6,  4, 2, 3]
刘德华:[Q ♥, 7, 大王,  8, 2,  5,  9, J ♠,  8, K ♣, J ♥,  9, K ♠, 10, Q ♣,  6,  4]
周星驰:[小王, A ♦, 7,  4, K ♦,  4, 3,  8,  5, A ♠, 10, Q ♠, Q ♦, 2,  6,  5, K ♥]
底牌:[ 9, A ♣, 2]

 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值