模拟斗地主洗牌,发牌
使用HashMap,TreeSet和List来实现
效果如下图所示:
详细实现代码如下:
package star.july.tags;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;
/**
* 模拟斗地主洗牌,发牌
* 使用HashMap,TreeSet和List来实现
* @author Starjuly
*
*/
public class Poker {
public static void main(String[] args) {
//先把牌设置好
String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
String[] size = {"方块","梅花","红桃","大葵"};
HashMap<Integer, String> hm = new HashMap<Integer,String>();
ArrayList<Integer> list = new ArrayList<Integer>();
int index = 0;
//装牌
for(String s1 : num){
for(String s2 : size){
hm.put(index,s2.concat(s1));
list.add(index);
index++;
}
}
//装大王和小王
hm.put(index, "小王");
list.add(index);
index++;
hm.put(index, "大王");
list.add(index);
//洗牌:将集合中的顺序打乱
Collections.shuffle(list);
//定义玩家和底牌
TreeSet<Integer> GaoJin = new TreeSet<Integer>();
TreeSet<Integer> LongWu = new TreeSet<Integer>();
TreeSet<Integer> Me = new TreeSet<Integer>();
TreeSet<Integer> DiPai = new TreeSet<Integer>();
//将牌发给玩家和留3张底牌
for(int i = 0 ; i < list.size() ; i++){
if(i >= list.size() - 3){
DiPai.add(list.get(i));
}
else if( i % 3 == 0){
GaoJin.add(list.get(i));
}
else if( i % 3 == 1){
LongWu.add(list.get(i));
}
else{
Me.add(list.get(i));
}
}
//遍历每个玩家手中的牌
lookPoker(hm, GaoJin, "高进");
lookPoker(hm, LongWu, "龙五");
lookPoker(hm, Me, "自己");
lookPoker(hm, DiPai, "底牌");
}
public static void lookPoker(HashMap<Integer, String> hm , TreeSet<Integer> ts,String name){
System.out.print(name + " 手中的牌: ");
for(Integer i : ts){ //用增强for循环遍历TreeSet集合
String poker = hm.get(i); //通过key找到HashMap中的值
System.out.print(poker + " ");
}
System.out.println();
}
}