斗地主案例

有序排列斗地主案例:
public static void main(String[] args) {
//准备牌
//创建一个map集合,存储牌的索引和组装好的牌
HashMap<Integer,String> pocker = new HashMap<>();
//创建一个list集合,存储牌的索引
ArrayList<Integer> pockerIndex = new ArrayList<>();
//定义两个集合,存储花色和牌的序号
List<String> colors = List.of("♥","♣","♦","♠");
List<String> numbers = List.of("2","A","K","Q","J","10","9","8","7","6","5","4","3");
//把大王小王存储在集合中
//定义一个牌的索引
int index = 0;
pocker.put(index,"大王");
pockerIndex.add(index);
index++;
pocker.put(index,"小王");
pockerIndex.add(index);
index++;
for(String number : numbers){
for(String color : colors){
// 把组装好的牌存储到pocker集合中。
pocker.put(index,color + number);
pockerIndex.add(index);
}
}
System.out.println(pocker);
System.out.println(pockerIndex);
//洗牌
Collections.shuffle(pockerIndex);
//发牌
//定义4个集合,存储玩家牌的索引和底牌的索引
ArrayList<Integer> play01 = new ArrayList<>();
ArrayList<Integer> play02 = new ArrayList<>();
ArrayList<Integer> play03 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
//遍历存储牌索引的list集合,获取每一个牌的索引
for(int i = 0 ;i < pockerIndex.size() ; i++){
Integer in = pockerIndex.get(i);
//先判断底牌
if(i>=51){
//给底牌发牌
dipai.add(in);
}else if(i%3 == 0){
//给玩家1发牌
play01.add(in);
}else if(i%3 == 1){
//给玩家2发牌
play02.add(in);
}else if(i%3 == 2){
//给玩家3发牌
play03.add(in);
}
}
//排序,使用collections中的方法sort(list)(默认为升序排序)
Collections.sort(play01);
Collections.sort(play02);
Collections.sort(play03);
Collections.sort(dipai);
//看牌
lookPocker("贾玲",pocker,play01);
lookPocker("宋小宝",pocker,play02);
lookPocker("海燕",pocker,play03);
lookPocker("底牌",pocker,dipai);
}
//定义一个看牌的方法,提高代码的复用性;
//参数:String name:玩家名称。HashMap<Integer,String> pocker:存储牌。ArrayList<Integer> list:存储玩家和底牌。
//查表法:遍历玩家或底牌集合,获取牌的索引。使用牌的索引,去map集合找到对应的牌。
public static void lookPocker(String name,HashMap<Integer,String> pocker,ArrayList<Integer> list){
//输出玩家名称,不换行
System.out.println(name + ": ");
//遍历玩家或底牌集合,获取牌的索引
for(Integer key : list){
//使用牌的索引,去map集合中,找到对应的牌
String value = pocker.get(key);
System.out.println(value+" ");
}
System.out.println();//打印每一个玩家的牌,换行
}
本文详细介绍了一种基于Java的斗地主游戏实现方案,包括牌的生成、洗牌、发牌及展示过程。通过使用HashMap存储牌面,ArrayList记录牌的索引,实现了游戏的有序排列与随机发牌功能。
774

被折叠的 条评论
为什么被折叠?



