Java斗地主小游戏有序版

4次阅读

共计 2102 个字符,预计需要花费 6 分钟才能阅读完成。

斗地主综合案例:有序版

1. 准备牌:大王小王

52 张牌:循环嵌套遍历两个集合,组装 52 张牌

可以使用 Map 集合储存牌的索引 + 组装好的牌。创建一个 List 集合存储牌的索引

2. 洗牌:使用 Collections 中的方法 shuffle(List)

3. 发牌:一人一张轮流发牌,每人 17 张,集合索引 %3,剩余 3 张给底牌.(注意:要先判断底牌 i > 50,即在第 51 张牌开始给底牌发)

4. 排序:使用 Collections 中的方法 sort(List)

5. 看牌:可以用查表的方法

遍历一个集合,获取到另外一个集合的 key,通过 key 查找到 value

遍历玩家和底牌的 List 集合,获取到 Map 集合的 key,通过 key 找到 value 值

***【注意】***:使用了 JDK9 及以上版本才可以使用的 List.of()。

List colors = List.of(“♠”,”♥”,”♣”,”♦”);

List numbers = List.of(“2″,”A”,”K”,”Q”,”J”,”10″,”9″,”8″,”7″,”6″,”5″,”4″,”3″);

1

2

如果是 JDK9 以下的版本,可以建立两个数组:

String[] colors = {“♠”,”♥”,”♣”,”♦”};

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

1

2

程序

package Demo06;

import java.util.*;

/*

斗地主有序版本

1. 准备牌

2. 洗牌

3. 发牌

4. 排序

5. 看牌

*/

public class DouDiZhu2 {

public static void main(String[] args) {

//1. 准备牌

// 创建集合 poker,存储 54 张牌的索引和组装好的牌

HashMap poker = new HashMap<>();

// 创建一个 list 集合,存储牌的索引

ArrayList pokerIndex = new ArrayList<>();

// 定义两个集合,分别存储花色和数字

List colors = List.of(“♠”,”♥”,”♣”,”♦”);

List numbers = List.of(“2″,”A”,”K”,”Q”,”J”,”10″,”9″,”8″,”7″,”6″,”5″,”4″,”3″);

// 存储大小王

// 定义一个牌的索引

int index = 0;

poker.put(index,” 大王 ”);

pokerIndex.add(index);

index++;

poker.put(index,” 小王 ”);

pokerIndex.add(index);

index++;

// 循环嵌套遍历两个集合,组装 52 张牌,存储到集合中

for (String number : numbers) {

for (String color : colors) {

poker.put(index,color+number);

pokerIndex.add(index);

index++;

}

}

//2. 洗牌

Collections.shuffle(pokerIndex);

// 3. 发牌

// 定义四个集合分别存储玩家和底牌的牌索引

ArrayList player01 = new ArrayList<>();

ArrayList player02 = new ArrayList<>();

ArrayList player03 = new ArrayList<>();

ArrayList dipai = new ArrayList<>();

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

int in = pokerIndex.get(i);

if(i > 50) {

dipai.add(in);

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

player01.add(in);

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

player02.add(in);

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

player03.add(in);

}

}

// 4. 排序
XM 返佣 http://www.kaifx.cn/broker/xm…

Collections.sort(player01);

Collections.sort(player02);

Collections.sort(player03);

Collections.sort(dipai);

//5. 看牌

pokerShow(“ 刘亦菲 ”,poker,player01);

pokerShow(“ 单薇子 ”,poker,player02);

pokerShow(“ 周星驰 ”,poker,player03);

pokerShow(“ 底牌 ”,poker,dipai);

}

/*

定义一个方法,看牌,使用查表方法

*/

public static void pokerShow(String name,HashMap poker,ArrayList list) {

// 输出玩家的名称

System.out.print(name+ “:”);

for (Integer key : list) {

String value = poker.get(key);

System.out.print(value+ ” “);

}

System.out.println();

}

}

正文完
 0