用java程序模拟斗地主,随机发牌。
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;public class PokerDemo {public static void main(String[] args) {//用hashmap存编号,和牌HashMap<Integer,String> hm = new HashMap<>();//创建一个数组来存储编号,每一个编号代表一张牌ArrayList<Integer> num = new ArrayList<>();//创建花色 和 牌 String[] hs = {"♠","♥","♦","♣"};String[] bh = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};//存储牌和数组 从0开始网hashmap里面存储编号,并存储对应的牌,同时往arraylist里面存储编号int index = 0;for (String s : bh) {for (String h : hs) {num.add(index);hm.put(index, h + s);index++;}}num.add(index);hm.put(index,"小王");index++;num.add(index);hm.put(index,"大王");//利用treeset的排序,用其接收TreeSet<Integer> user1 = new TreeSet<>();TreeSet<Integer> user2 = new TreeSet<>();TreeSet<Integer> user3 = new TreeSet<>();TreeSet<Integer> dp = new TreeSet<>();//用collections中的shuffle()方法打乱num中的数字 打乱排序Collections.shuffle(num);//发牌for(int i= 0;i <num.size();i++){int poker = num.get(i);if (i>=num.size()-3){dp.add(poker);}else if (i%3 == 0){user1.add(poker);}else if(i%3==1){user2.add(poker);}else{user3.add(poker);}}//利用自定义方法显示手中的牌LookPoker("用户1",user1,hm);LookPoker("用户2",user2,hm);LookPoker("用户3",user3,hm);LookPoker("底牌",dp,hm);}public static void LookPoker(String name ,TreeSet<Integer> user,HashMap<Integer,String> hashMap){System.out.print(name + "的牌: ");for (Integer ss : user){System.out.print(hashMap.get(ss)+" ");}System.out.println();}
}
运行结果: