利用HashMap和ArrayList,模拟斗地主洗牌,发牌,看牌,案例。
package com.gaojixifa;
import java.util.*;
public class Xifaplus {
public static void main(String[] args) {
HashMap<Integer,String> hm = new HashMap<Integer, String>();//利用索引找到对应的牌
ArrayList<Integer> array = new ArrayList<Integer>();//牌的索引
String[] colors = {"♦","♣","♥","♠"};
String[] numbers ={"2","3","4","5","6","7","8","9","10","J","Q","K","A"};
int index = 0;
for(String number : numbers){
for(String color : colors){
hm.put(index,color+number);
array.add(index);
index++;
}
}
hm.put(index,"小王");
array.add(index);
index++;
hm.put(index,"大王");
array.add(index);
Collections.shuffle(array);
TreeSet<Integer> lqxset = new TreeSet<Integer>();
TreeSet<Integer> lyset = new TreeSet<Integer>();
TreeSet<Integer> fqyset = new TreeSet<Integer>();
TreeSet<Integer> dpset = new TreeSet<Integer>();
for(int i=0;i<array.size();i++){
int x = array.get(i);
if(i>=array.size()-3){
dpset.add(x);
}else if(i%3==0){
lqxset.add(x);
}else if(i%3==1){
lyset.add(x);
}else if(i%3==2){
fqyset.add(x);
}
}
Lookpocker("林青霞",lqxset,hm);
Lookpocker("柳岩",lyset,hm);
Lookpocker("风清扬",fqyset,hm);
Lookpocker("底牌",dpset,hm);
}
//下面是看牌的方法
public static void Lookpocker(String name,TreeSet<Integer> ts,HashMap<Integer,String> hm){
System.out.println(name+"的牌是:");
for(Integer key : ts){
String pocker = hm.get(key);
System.out.print(pocker+" ");
}
System.out.println();
}
}
运行的结果:
林青霞的牌是:
♣2 ♣4 ♠6 ♦7 ♥7 ♠7 ♣8 ♠10 ♦J ♣Q ♠Q ♦K ♥K ♠K ♣A ♥A 大王
柳岩的牌是:
♦3 ♥3 ♠3 ♥4 ♠4 ♣5 ♦6 ♣6 ♥8 ♦9 ♣9 ♥9 ♦10 ♦Q ♦A ♠A 小王
风清扬的牌是:
♦2 ♠2 ♣3 ♦4 ♦5 ♠5 ♥6 ♦8 ♠8 ♠9 ♣10 ♥10 ♣J ♥J ♠J ♥Q ♣K
底牌的牌是:
♥2 ♥5 ♣7