之前使用集合,模拟了斗地主的进程。
今天新学习了Map集合,增加排序功能
package Gamedoudizhu;
import javax.swing.plaf.synth.SynthOptionPaneUI;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
/*斗地主案例:有序版本
* 1.准备牌
* 2.洗牌
* 3.发牌
* 4.排序
* 5.看牌*/
public class Demo02 {
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> num = 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++;
for (String numb : num) {
for (String color : colors) {
poker.put(index, color + numb);
pokerIndex.add(index);
index++;
}
}
// System.out.println(pokerIndex);
// System.out.println(poker);
//2.洗牌
Collections.shuffle(pokerIndex);
//3.发牌
//定义四个集合,存储玩家的牌的索引
ArrayList<Integer> p1 = new ArrayList<>();
ArrayList<Integer> p2 = new ArrayList<>();
ArrayList<Integer> p3 = new ArrayList<>();
ArrayList<Integer> dipai = new ArrayList<>();
for (int i = 0; i <pokerIndex.size() ; i++) {
Integer in = pokerIndex.get(i);
//先判断底牌
if(i>=51){
dipai.add(in);
}else if (i%3==0){
p1.add(in);
}else if (i%3==1){
p2.add(in);
}else if (i%3==2){
p3.add(in);
}
}
//4.排序
//使用Collections中的sort(List)
Collections.sort(dipai);
Collections.sort(p1);
Collections.sort(p2);
Collections.sort(p3);
//5.看牌
/*定义一个看牌的方法,提高代码的复用性
* 参数:
* String name;玩家的名称
* HashMap<Integer,String> poker: 存储牌的poker集合
* ArrayList<Integer> list:存储玩家和底牌的List集合
* 查表法:
* 遍历玩家或者底牌集合,获取牌的索引
* 使用牌的索引,去Map集合中,找到对应的牌*/
lookPoker("刑天",poker,p1);
lookPoker("飞影",poker,p2);
lookPoker("金刚",poker,p3);
lookPoker("底牌",poker,dipai);
}
public static void lookPoker(String name,HashMap<Integer,String> poker,ArrayList<Integer> list){
//先输出玩家的名称,不换行
System.out.print(name+":");
//遍历玩家或者底牌集合,获取牌的索引
for (Integer key : list) {
String value = poker.get(key);
System.out.print(value+" ");
}
System.out.println();//打印完每个玩家换行
}
}