java学习笔记 - 集合类综合案例 斗地主

集合类方法

最近学到java的各个集合类,常用的有List,Set,Map,这三个都是接口,其中List和Set继承了Collections。

为了锻炼实际掌握各种常用方法的案例,自己写了个斗地主案例

要求

  1. 组装54张扑克牌将
  2. 54张牌顺序打乱
  3. 三个玩家参与游戏,三人交替摸牌,每人17张牌,最后三张留作底牌。
  4. 查看三人各自手中的牌(按照牌的大小排序)、底牌

需求分析

  1. 准备牌: 完成数字与纸牌的映射关系: 使用双列Map(HashMap)集合,完成一个数字与字符串纸牌的对应关系(相当于一个字典)。
  2. 洗牌: 通过数字完成洗牌发牌
  3. 发牌: 将每个人以及底牌设计为ArrayList,将最后3张牌直接存放于底牌,剩余牌通过对3取模依次发牌。 存放的过程中要求数字大小与斗地主规则的大小对应。 将代表不同纸牌的数字分配给不同的玩家与底牌。
  4. 看牌: 通过Map集合找到对应字符展示。 通过查询纸牌与数字的对应关系,由数字转成纸牌字符串再进行展示。

代码实现

package advancedgrammer.collection;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;

public class FightLoad {
    public static void main(String[] args) {
        List<String> colors = List.of("红桃", "黑桃", "方块", "梅花"); 
        List<String> numbers = List.of( "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A","2");
        ArrayList<Integer> index = new ArrayList<>();  //存放牌的索引,shuffle后发给三个人
        HashMap<Integer, String> poker = new HashMap<>();  //表示牌的hashmap,把54张牌按大小索引存放。
        int in = 0;
        for (String number : numbers) {
            for (String color : colors) {
                index.add(in);
                poker.put(in++, color + number);
            }
        }
        poker.put(52, "大王");index.add(52);
        poker.put(53, "小王");index.add(53);
//        System.out.println(poker);
        Collections.shuffle(index);
        System.out.println(index);
        ArrayList<Integer> index1 = new ArrayList<>();  //放每个玩家拿到的牌
        ArrayList<Integer> index2 = new ArrayList<>();
        ArrayList<Integer> index3 = new ArrayList<>();
        ArrayList<Integer> dipaiindex = new ArrayList<>();
        for (int i = 0; i < 54; i++) {
        	//发牌给三个玩家和底牌
            if (i > 50) {
                dipaiindex.add(index.get(i));
            }else if (i % 3 == 0) {
                index1.add(index.get(i));
            }else if (i % 3 == 1) {
                index2.add(index.get(i));
            }else if (i % 3 == 2) {
                index3.add(index.get(i));
            }
        }
        check("诸葛大力",index1,poker);
        check("陈美嘉",index2,poker);
        check("诺澜",index3,poker);
        check("婉瑜",dipaiindex,poker);
    }

	//提高复用性,每个玩家的看牌的方法
    public static void check(String name,ArrayList<Integer> index,HashMap<Integer, String> poker) {
        Collections.sort(index);
        System.out.print(name + ":");
        for (Integer integer : index) {
            System.out.print(poker.get(integer) + " ");
        }
        System.out.println();
    };
}

一次看牌的结果

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值