java基础--集合案例斗地主发牌排序

package com.henu;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Demo04_斗地主_制牌_洗牌_发牌_有序 {

	public static void main(String[] args) {
		
		String[] nums = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
		String[] color = {"♥","♦","♠","♣"};
		//定义map存储所有牌,采用它的key为后期的每个人的手牌排序做准备
		Map hMap = new HashMap<>();
		//list存取序号,相当于map的key值。
		List cardId = new ArrayList();
		int count = 1;
		//双重循环将牌存入到map中,注意外内循环的不同数组,为了后续的排序
		for (String str1 : nums) {
			for (String str2 : color) {
				cardId.add(count);
				hMap.put(count++, str2+str1);
			}
		}
		hMap.put(53, "小♋");
		hMap.put(54, "大♋");
		cardId.add(53);
		cardId.add(54);
		
		//将牌的序号进行打乱
		Collections.shuffle(cardId);
		
		//定义三个玩家
		List xiaoTeng = new ArrayList<>();
		List xiaoYun = new ArrayList<>();
		List xiaoHong = new ArrayList<>();
		List diPai = new ArrayList<>();
		
		//发牌
		for (int i = 0; i < cardId.size(); i += 3) {
			
			if (i < cardId.size()-3) {
				xiaoTeng.add(cardId.get(i));
				xiaoYun.add(cardId.get(i+1));
				xiaoHong.add(cardId.get(i+2));
			}else {
				diPai.add(cardId.get(i-1));
				diPai.add(cardId.get(i));
				diPai.add(cardId.get(i+1));
			}
		}
		
		//输出结果
		System.out.println("小腾的牌是:"+toCard(xiaoTeng, hMap));
		System.out.println("小云的牌是:"+toCard(xiaoYun, hMap));
		System.out.println("小宏的牌是:"+toCard(xiaoHong, hMap));
		System.out.println("底牌的牌是:"+toCard(diPai, hMap));
		
		
	}
	//根据list的序号取map的value;即根据序号对map的 牌进行取,得到的即是排序好的纸牌。
	public static List toCard(List user,Map hMap){
		//现将抽到的牌进行排序
		Collections.sort(user);
		//根据序号取到牌
		List userCard = new ArrayList<>();
		for (Integer in : user) {
			userCard.add(hMap.get(in));
		}
		
		return userCard;
		
	}
	
}

结果输出: 

java基础--集合案例斗地主发牌排序_第1张图片

 

 

你可能感兴趣的:(【JAVA】JAVA基础)