鬥地主有序案例(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