斗地主综合案例:有序版本
1.准备牌
特殊牌:大王、小王
52张牌:循环嵌套遍历两个集合/数组,组装52张牌
List colors = List.of(“♠”,”♥“,“♣”,“♦”);
List numbers = List.of(“2”,“A”,“K”,“Q”,“J”,“10”,“9”,“8”,“7”,“6”,“5”,“4”,“3”);
2.洗牌
使用Collections中的方法shuffle(List)
3.发牌
一人一张轮流发牌,每人17张
集合索引%3
剩余3张留给底牌
4.排序
使用Collections中的方法:soft(List)
5.看牌,可以使用查表方法
遍历一个集合,获取到另外一个集合的key,通过遍历key查找到value
遍历玩家和底牌的List集合,获取到Map集合的key,通过key找到value
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
public class DouDiZhu{
public static void main(String[] args){
//1.准备牌
//创建一个Map集合,存储牌的索引和组装好的牌
HashMap<Integer,String> poker =new HashMap<>();
//创建一个List集合,存储牌的索引
ArrayList<Integer> pokerIndex = 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;
poker.put(index,"大王");
pokerIndex.add(index);
index++;
poker.put(index,"小王");
pokerIndex.add(index);
index++;
//循环嵌套遍历两个集合,组装52张牌,存储到集合中
for(String c : colors){
for(String n : numbers){
poker.put(index,c+n);
pokerIndex.add(index);
index++;
}
}
/*
2.洗牌
使用Collections中的方法shuffle(List)
*/
Collections.shuffle(pokerIndex);
//3.发牌
//定义4个集合,存储玩家的索引,和底牌的索引
ArrayList<Integer> player01 = new ArrayList<>();
ArrayList<Integer> player02 = new ArrayList<>();
ArrayList<Integer> player03 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
//遍历存储牌的索引的List集合,获取每一个牌的索引
for(Integer n :pokerIndex){
if(n>=51){
dipai.add(n);
}else if(n%3==0){
player01.add(n);
}else if(n%3==1){
player02.add(n);
}else if(n%3==2){
player03.add(n);
}
}
//4.排序
// 使用Collections中的方法sort(List)
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(dipai);
//5.看牌
//调用看牌的方法
lookPoker("刘德华",poker,player01);
lookPoker("周星驰",poker,player01);
lookPoker("周润发",poker,player01);
lookPoker("底牌",poker,player01);
}
/*
定义一个看牌的方法,提高代码的复用性
参数:
String name:玩家名称
HashMap<Integer,String> poker :存储牌的poker集合
ArrayList<Integer> list :存储玩家和底牌的List集合
查表法:
遍历玩家或者底牌集合,获取牌的索引
使用牌额索引,去Map集合中,找对应的牌
*/
public static void lookPoker(String name,HashMap<Integer,String> poker, ArrayList<Integer> list){
//输出玩家名称,不换行
System.out.print(name+": ");
//遍历玩家或者底牌集合,获取牌的索引
for(Intrger key : list){
//使用牌的索引,去Map集合中,找对应的牌
String value = poker.get(key);
System.out.print(value+" ");
}
System.out.println();//打印完每一个玩家的牌,换行
}
}