案例:
定义一个类:
package JiHe.MapJiHe;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/*
斗地主综合案例:有序版本。
实现步骤:
1. 准备牌。
2. 洗牌。
3. 发牌。
4. 排序。
5. 看牌。
*/
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 number : numbers) {
for (String color : colors) {
poker.put(index,color+number);
pokerIndex.add(index);
index++;
}
}
//System.out.println(poker);
//System.out.println(pokerIndex);
//2. 洗牌。
//使用Collections中的方法shuffle(List)
Collections.shuffle(pokerIndex);
//System.out.println(pokerIndex);
//3. 发牌
//定义四个集合,储存玩家牌的索引,和底牌的索引
ArrayList<Integer> player01 = new ArrayList<>();
ArrayList<Integer> player02 = new ArrayList<>();
ArrayList<Integer> player03 = new ArrayList<>();
ArrayList<Integer> diPai = new ArrayList<>();
//遍历存储牌索引的List集合,获取每一个牌的索引
for (int i = 0; i < pokerIndex.size(); i++) {
Integer in = pokerIndex.get(i);
//先判断底牌
if(i >= 51){
//给底牌发牌
diPai.add(i);
}else if(i % 3 == 0){
player01.add(i);
}else if(i % 3 == 1){
player02.add(i);
}else if(i % 3 == 2){
player03.add(i);
}
}
//4. 排序
//使用Collections中的方法sort(List):默认是升序排序
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(diPai);
//5. 看牌
//调用看牌的方法
lookPoker("AAA",poker,player01);
lookPoker("BBB",poker,player02);
lookPoker("CCC",poker,player03);
lookPoker("底牌",poker,diPai);
}
/*
定义一个看牌的方法,提高代码的重复性
参数:
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 (Integer key : list) {
//使用牌的索引,去Map集合中,找到对应的牌
String value = poker.get(key);
System.out.print(value + " ");
}
System.out.println( ); //打印完每个玩家的牌,换行
}
}
运行结果:
AAA: 大王 ♥2 ♠A ♦A ♣K ♥Q ♠J ♦J ♣10 ♥9 ♠8 ♦8 ♣7 ♥6 ♠5 ♦5 ♣4
BBB: 小王 ♣2 ♥A ♠K ♦K ♣Q ♥J ♠10 ♦10 ♣9 ♥8 ♠7 ♦7 ♣6 ♥5 ♠4 ♦4
CCC: ♠2 ♦2 ♣A ♥K ♠Q ♦Q ♣J ♥10 ♠9 ♦9 ♣8 ♥7 ♠6 ♦6 ♣5 ♥4 ♠3
底牌: ♥3 ♣3 ♦3
另一种实现方法(无序排序版本):https://blog.youkuaiyun.com/qq_36050720/article/details/98210849