斗地主有序案例(Map集合)
案例分析如下图所示:
package com.scdn.DouDiZhu;
import java.util.*;
/*
斗地主综合案例:有序版本
1.准备牌
2.洗牌
3.发牌
4.排序
5.看牌
*/
public class Demodoudizhu {
public static void main(String[] args) {
//1.创造牌盒子,创建一个Map集合,存储牌的索引和组装好的牌
HashMap<Integer,String> poker = new HashMap<>();
//准备牌的索引盒子
ArrayList<Integer> pokerindex = new ArrayList<>();
//花色集合
ArrayList<String> colors = new ArrayList<>();
//数字集合
ArrayList<String> numbers = new ArrayList<>();
Collections.addAll(colors,"♠","♥","♣","♦");
Collections.addAll(numbers,"3","4","5","6","7","8","9","10","J","Q","K","A","2");
int index = 0;
//循环遍历两个字符串数组,将一整副牌准备好
for(String number:numbers){
for(String color:colors){
poker.put(index,color+number);
pokerindex.add(index);
index++;
}
}
//手动添加大王
poker.put(index,"大王");
pokerindex.add(index);
index++;
//手动添加小王
poker.put(index,"小王");
pokerindex.add(index);
index++;
// System.out.println(index);
//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 (Integer i = 0;i<pokerindex.size();i++){
Integer in = pokerindex.get(i);
if(i>=51){
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.排序,使用Collections中的方法sort(List<T> list,comparator<? super T>)
//因为斗地主真实游戏中是降序排序,所以使用Comparator自定义方法来降序排序
// Collections.sort(dipai);
// Collections.sort(player01);
// Collections.sort(player02);
// Collections.sort(player03);
Collections.sort(dipai, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
Collections.sort(player01, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
Collections.sort(player02, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
Collections.sort(player03, new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return o2-o1;
}
});
//5.看牌,写一个看牌的方法,在此方法中,利用每个玩家牌盒中存储的key,去poker中获取对应的value值
Lookpoker("底牌",poker,dipai);
Lookpoker("地主",poker,player01);
Lookpoker("农民1",poker,player02);
Lookpoker("农民2",poker,player03);
}
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();
}
}
代码运行结果:
底牌:♦2 ♦K ♥6
地主:♣A ♥A ♠K ♥J ♣10 ♥10 ♣9 ♠8 ♥7 ♦6 ♣6 ♠6 ♦5 ♣4 ♠4 ♣3 ♥3
农民1:小王 ♥2 ♠2 ♦A ♠A ♣K ♥K ♦Q ♥Q ♠Q ♦J ♠10 ♥9 ♣8 ♠7 ♦4 ♥4
农民2:大王 ♣2 ♣Q ♣J ♠J ♦10 ♦9 ♠9 ♦8 ♥8 ♦7 ♣7 ♣5 ♥5 ♠5 ♦3 ♠3