Java中Map集合模拟斗地主发牌(发完洗牌)

代码

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.TreeSet;

public class Test3 {
/*
 * 案例演示:
 * 	模拟斗地主洗牌和发牌并对牌进行排序的代码实现
 * 分析:
 * 	1.买一副扑克牌,其实就是创建一个集合对象,将扑克牌存储进去
 * 	2.洗牌
 * 	3.发牌
 * 	4.看牌
 */
	public static void main(String[] args) {
		//1.创建一副扑克牌,其实就是创建一个集合对象,把扑克牌存储进去
		String[] num = {"3","4","5","6","7","8","9","10","J","Q","K","A","2"};
		String[] color = {"♥","♠","♦","♣"};
		HashMap<Integer, String> hm = new HashMap<>();				//存储索引和扑克牌
		ArrayList<Integer> list = new ArrayList<>();					//存储索引
		int index = 0;
		//拼接扑克牌并且将扑克牌和索引存储在hm中
		for (String s1 : num) {									//获取颜色
			for (String s2 : color) {									//获取数字
				hm.put(index,s2.concat(s1));
				list.add(index);								//将索引0-51添加到集合中
				index++;
				
			}
		}
		//将小王和大王添加到双列集合中
		hm.put(index, "小王");
		list.add(index);										//将索引52添加到集合中
		index++;
		hm.put(index, "大王");
		list.add(index);										//将索引53添加到集合中
		//System.out.println(index);
		//System.out.println(list);
		//2.洗牌
		Collections.shuffle(list);
		//3.发牌
		TreeSet<Integer> zhangsan = new TreeSet<>();
		TreeSet<Integer> lisi = new TreeSet<>();
		TreeSet<Integer> wangwu = new TreeSet<>();
		TreeSet<Integer> dipai = new TreeSet<>();
		for (int i = 0; i < list.size(); i++) {
			if (i >= list.size() - 3) {
				dipai.add(list.get(i));
			}else if (i % 3 == 0) {
				zhangsan.add(list.get(i));
			}else if (i % 3 == 1) {
				lisi.add(list.get(i));
			}else {
				wangwu.add(list.get(i));
			}
		}
		//看牌
		lookPoker(hm, zhangsan, "张三");
		lookPoker(hm, lisi, "李四");
		lookPoker(hm, wangwu, "王五");
		lookPoker(hm, dipai, "底牌");
		
	}
	/**
	 * 看牌
	 * 1.返回值类型 :void
	 * 2.参数列表:HashMap,TreeSet,String name 
	 */
	public static void lookPoker(HashMap<Integer,String> hm,TreeSet<Integer> ts,String name ) {
		System.out.print(name+ "的牌为:");
		
		for (Integer i : ts) {				//i代表双列集合中的每一个键
			String pai = hm.get(i);
			System.out.print(pai+" ");
		}
		System.out.println();
	}

}

你可能感兴趣的:(Java)