题目:
参考斗地主的游戏规则,完成一个发牌的功能(54张牌,考虑点数,花色;三名玩家,其中地主比其他玩家多3张牌) * (1) 牌类(花色,点数,序号) * (2) 玩家类(id,名字,是否地主,牌集合)
package cn.java.work;
import java.util.*;
/**
* 斗地主
*/
public class Game {
//需要有一个属性.或者说是一个变量来存储54张牌
private HashMap<Integer,String> map = new HashMap<Integer, String>();
//花色
private String[] hs = {"♠","♥","♣","♦"};
//数字
private String[] nums = {"2","A","K","Q","J","10","9","8","7","6","5","4","3"};
//存储打乱顺序的元素
private List<Integer> keys = new ArrayList<Integer>();
//准备牌
public void init(){
//也表示Map集合中的键值
int count = 0;//计数器
map.put(++count,"大王");
map.put(++count,"小王");
for(int i = 0; i < nums.length; i++){
for(int j = 0; j < hs.length; j++){
map.put(++count,hs[j] + nums[i]);
}
}
keys.addAll(map.keySet());
}
//洗牌
public void xiPai(){
Collections.shuffle(keys);
}
//发牌
//key 玩家1 玩家2 玩家3 底牌
//可以根据打乱的key找到对应的value
public Map<String, Map<Integer, String>> faPai(){
Map<String,Map<Integer,String>> tempMap = new LinkedHashMap<>();
//玩家1
Map<Integer,String> l1 = new HashMap<Integer, String>();
//玩家2
Map<Integer,String> l2 = new HashMap<Integer, String>();
//玩家3
Map<Integer,String> l3 = new HashMap<Integer, String>();
//底牌
Map<Integer,String> dp = new HashMap<Integer, String>();
//map.size() - 3 留三张底牌
for(int i = 0; i < map.size() - 3; i++){
if(i % 3 == 0){
l1.put(keys.get(i),map.get(keys.get(i)));//key value
}else if(i % 3 == 1){
l2.put(keys.get(i),map.get(keys.get(i)));
}else if(i % 3 == 2){
l3.put(keys.get(i),map.get(keys.get(i)));
}
}
for(int i = map.size() - 3; i < map.size(); i++){
dp.put(keys.get(i),map.get(keys.get(i)));
}
tempMap.put("玩家1",l1);
tempMap.put("玩家2",l2);
tempMap.put("玩家3",l3);
tempMap.put("底牌",dp);
return tempMap;
}
//排序
public Map<Integer,String> paiXu(Map<Integer,String> pai){
//map集合是无序的,但是LinkedHashMap有序的
Map<Integer,String> map = new LinkedHashMap<Integer, String>();
List<Integer> tempList = new ArrayList<Integer>();
//将牌的键集拿出来
tempList.addAll(pai.keySet());
//对list集合进行排序
Collections.sort(tempList);
//遍历这些键然后将这些键和值存储到LinkedHashMap
for(Integer x : tempList){
map.put(x,pai.get(x));
}
return map;
}
public static void main(String[] args) {
Game game = new Game();
//准备牌
game.init();
//洗牌
game.xiPai();
//发牌
Map<String,Map<Integer,String>> m = game.faPai();
Set<String> set = m.keySet();//遍历输出每个玩家的牌
for(String s : set){//s代表:玩家1,玩家2,玩家3,底牌
Map<Integer,String> pai = m.get(s);
pai = game.paiXu(pai);
System.out.println(s + pai.values());
}
}
}
运行结果: