package com.xyf.demo.斗地主发牌案例用Map有序版;
这里排序的实现用到了Map集合的key,通过对key的数字int进行排序,实现对应的牌的排序
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
public class MapDemo {
public static void main(String[] args) {
//1.创建一个map集合放索引和牌,一个list集合放索引,对map集合的操作通过对list集合的操作来实现
HashMap<Integer,String> poker= new HashMap<>();
ArrayList<Integer> index=new ArrayList<>();
//2.创建两个数组中分别放花色和数字,结合起来放入map集合中去
String[] colors={"黑桃","红桃","梅花","方块"};
String[] numbers={"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
poker.put(0,"大王");
poker.put(1,"小王");
index.add(0);
index.add(1);
int number=2;
for (int i=0;i<colors.length;i++){
for (int j=0;j<numbers.length;j++){
poker.put(number,colors[i]+numbers[j]);
index.add(number);
number++;
}
}
//3.通过操作index集合对map集合进行打乱(逻辑意义上),分成4份,3个玩家和一个牌堆
ArrayList<Integer> player1=new ArrayList<>();
ArrayList<Integer> player2=new ArrayList<>();
ArrayList<Integer> player3=new ArrayList<>();
ArrayList<Integer> last=new ArrayList<>();
Collections.shuffle(index);
for (int i=0;i<index.size();i++){
Integer p=index.get(i);
if (i>=51){
last.add(p);
}
else if (i%3==2){
player1.add(p);
} else if (i%3==1){
player2.add(p);
} else if (i%3==0){
player3.add(p);
}
}
//4.对索引排序
Collections.sort(player1);
Collections.sort(player2);
Collections.sort(player3);
Collections.sort(last);
//6调用卡牌输出方法
look(poker,player1,"cake");
}
//5.建立一个方法对牌通过索引进行输出
public static void look(HashMap<Integer,String> poker,ArrayList<Integer> player1,String name){
System.out.println("玩家"+name);
for ( Integer key :
player1) {
String s = poker.get(key);
System.out.print(s+" ");
}
}
}