Click to view: java collections (List, Set, Map) blog directory
Section X: a collection of integrated case - Landlords 2 (cards ordered)
Ideas Analysis:
code implementation:
// 斗地主综合案例:有序版本
1.准备牌
2.洗牌
3.发牌
4.排序
5.看牌
import java.util.*;
public class DouDiZhu2{
public static void main(String args []){
// 1.准备牌
// HashMap 要存储的是 <索引,牌>,例如:<6 , ♠A> ,<13 , ♦K>
HashMap<Integer,String> puke = new HashMap<>();
// 创建一个List集合,存储牌的索引
ArrayList<Integer> pukeindex = new ArrayList<>();
// 定义两个集合存储花色
String [] colors = {"♠","♥","♣","♦"};
String [] numbers = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
// 定义一个牌的索引,把大王和小王存储到集合中
int index= 0;
puke.put(index,"大王");
pukeindex.add(index);
index++;
puke.put(index,"小王");
pukeindex.add(index);
index++;
// 循环嵌套遍历两个集合,组装52张牌,存储到集合中
for(String number : numbers) {
for(String color : colors) {
puke.put(index, color+number);
pukeindex.add(index);
index++;
}
}
// 2. 洗牌 使用Collections里的shuffle方法,传递牌的索引集合
Collections.shuffle(pukeindex);
// 3. 发牌 定义四个集合,底牌+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<pukeindex.size();i++){
// 获取每一张牌
Integer in1 = pukeindex.get(i);
// 轮流发牌
if(i>=51){
dipai.add(in1);
}else if(i%3==0){ // 给玩家1发牌
player01.add(in1);
}else if(i%3==1){ // 给玩家2发牌
player02.add(in1);
}else if(i%3==2){ // 给玩家3发牌
player03.add(in1);
}
}
// 4.排序
// 使用Collection.sort()
Collections.sort(player01);
Collections.sort(player02);
Collections.sort(player03);
Collections.sort(dipai);
// 5.看牌
lookpuke("袁睿昕",puke,player01);
lookpuke("闫津铭",puke,player02);
lookpuke("李天一",puke,player03);
lookpuke("底牌 ",puke,dipai);
}
/* 定义一个看牌的方法
* Stirng player : 玩家名称
* HashMap<Integer,String> map : 存储牌的puke集合
* ArrayList<Integer> list : 存储玩家和底牌的list集合
* 查表法:
* 遍历玩家或底牌的集合,获取牌的索引
* 使用牌的索引,在Map集合中,找到对应的值
*/
public static void lookpuke(String player , HashMap<Integer,String> puke , ArrayList<Integer> list) {
// 输出玩家名称
System.out.print(player+": ");
// 遍历玩家或底牌集合,获取牌的索引
for(Integer key : list) {
// 使用牌的索引,去map集合中,找到对应的牌
String value = puke.get(key);
System.out.print(value+" ");
}
System.out.println();
}
}
Result of the program: