集合综合练习(斗地主随机洗牌)
package com.zs.Demo; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.Map; public class DouDiZhu { private static Map<Integer,String> Pooker; private static ArrayList<Integer> Pookervalue; private static ArrayList<Integer> play1,play2,play3,dipai; DouDiZhu() { createPooker(); ShufflePooker(); faPooker(); lookPooker("玩家1",play1); lookPooker("玩家2",play2); lookPooker("玩家3",play3); lookPooker("底牌",dipai); } private void lookPooker(String s,ArrayList<Integer> play1) { System.out.print(s+":"); for (Integer pookernum : play1) { for (Integer index : Pooker.keySet()) { if(pookernum==index) { String color = Pooker.get(index); System.out.print(color+"\t"); } } } System.out.println(); } private void faPooker() { //创建三个数组分别代表三位玩家 play1=new ArrayList<>(); play2=new ArrayList<>(); play3=new ArrayList<>(); dipai=new ArrayList<>(); int index=54; for (Integer pooker : Pookervalue) { if (index<=3) dipai.add(pooker); if(index%3==0) play1.add(pooker); if (index%3==1) play2.add(pooker); if (index%3==2) play3.add(pooker); index--; } // 排序 Collections.sort(play1); Collections.sort(play2); Collections.sort(play3); Collections.sort(dipai); } private void ShufflePooker() { //定义一个ArrayList集合接收Map集合的值,方便调用shuffle方法,因为只有List集合才能调用shuffle方法 Pookervalue=new ArrayList<>(); //遍历Map集合,并将Map集合的值传递给ArrayList集合 for (Integer it : Pooker.keySet()) { Pookervalue.add(it); } //将ArrayList集合的顺序打乱,也就是洗牌 Collections.shuffle(Pookervalue); } private void createPooker() { //创造保存扑克的Map集合,键-扑克;54张扑克牌,键为扑克牌号,值为扑克加花色 Pooker= new HashMap<>(); //定义扑克牌数字的数组, String[] pookerNum={"2","3","4","5","6","7","8","9","10","J","Q","K","A"}; //定义扑克牌花色的数组 String[] colors={"♥","♠","♣","♦"}; //给Map集合添加元素大王小王 Pooker.put(0,"大王"); Pooker.put(1,"小王"); //定义普通类牌的序号,从2开始,到53结束,52张普通拍,0,1为大小王; int index=2; for (String num : pookerNum) { for (String color : colors) { Pooker.put(index,color+num); index++; } } //System.out.println(Pooker);//{2=♥2, 3=♠2, 4=♣2, 5=♦2, 6=♥3, 7=♠3,。。。。50=♥A, 51=♠A, 52=♣A, 53=♦A}} } public static void main(String[] args) { new DouDiZhu();// } /* 玩家1:♥2 ♣3 ♦3 ♥4 ♣4 ♦4 ♥5 ♠5 ♦7 ♥9 ♠10 ♣10 ♥J ♠J ♣J ♠Q ♥K ♥A 玩家2:大王 小王 ♣2 ♦2 ♥3 ♣5 ♦5 ♥6 ♦6 ♥7 ♠7 ♥8 ♣9 ♣Q ♦Q ♠K ♣K ♦A 玩家3:♠2 ♠3 ♠4 ♠6 ♣6 ♣7 ♠8 ♣8 ♦8 ♠9 ♦9 ♥10 ♦10 ♦J ♥Q ♦K ♠A ♣A 底牌:♦7 ♣Q ♠A
结果是随机的每次都不一样
*/ }