java模仿斗地主随机洗牌 发牌,TreeMap、ArrayList、TreeSet练习

/**
 * 模仿斗地主洗牌,随机发牌
 * 	使用TreeMap、ArrayList、TreeSet
 * 		思想:
 * 				使用TreeMap存54张牌,每张牌作为值,key为每张牌整数编号1-54,取出键进行乱序牌,
 * 				之后发给三个人存在TreeSet自动会排序,然后偶循环通过键获得每张牌,斗地主不考虑花色
 */
import java.util.ArrayList;
import java.util.Collections;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;

public class Poker1 {

	public static void main(String[] args) {
		// 定义点数
		String[] point = { "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q",
				"K", "A", "2" };
		// 定义花色
		// String[] fC = { "红心", "方块", "黑桃", "梅花" };
		String[] fC = { "♥", "♦", "♠", "♣" };
		// 定义扑克集合
		TreeMap mapPoker = new TreeMap<>();
		// 生成扑克
		int sum = 0;
		for (String s1 : point) {
			for (String s2 : fC) {
				mapPoker.put(++sum, s2.concat(s1));
			}
		}
		mapPoker.put(++sum, "小王");
		mapPoker.put(++sum, "大王");
		// System.out.println(mapPoker + "\n");

		//获取所有键
		Set keys = mapPoker.keySet();
		//把键个封装到ArrayList集合,便于使用Collections集合工具类洗牌
		ArrayList poker = new ArrayList<>();
		for (Integer integer : keys) {
			poker.add(integer);
		}
		// System.out.println("洗牌前key:" + poker);
		
		// 洗牌
		//使用集合工具类洗牌
		Collections.shuffle(poker);
		// System.out.println("洗牌后key:" + poker + "\n" + poker.size());

		// 派牌、码牌(TreeSet),定义了三个人man1、man2、man3,底牌 diPoker
		TreeSet man1 = new TreeSet<>();
		TreeSet man2 = new TreeSet<>();
		TreeSet man3 = new TreeSet<>();
		ArrayList diPoker = new ArrayList<>(poker.subList(
				poker.size() - 3, poker.size()));
		//每人一张发牌
		for (int i = 0; i < poker.size() - 3; i++) {
			Integer s = poker.get(i);
			if (i % 3 == 1) {
				man1.add(s);
			} else if (i % 3 == 2) {
				man2.add(s);
			} else if (i % 3 == 0) {
				man3.add(s);
			}
		}

		// 看牌
		//三方牌装到ArrayList便于每个man遍历打印
		ArrayList> sets = new ArrayList<>();
		sets.add(man1);
		sets.add(man2);
		sets.add(man3);
		//外层遍历ArrayList的man封装,内层打印牌
		for (int i = 0; i < sets.size(); i++) {
			//三目嵌套打出每个人
			System.out.print(i == 0 ? "man1:" : (i == 1 ? "man2:"
					: (i == 2 ? "man3:" : "")));
			Set set = sets.get(i);
			for (Integer te : set) {
				System.out.print(mapPoker.get(te) + "   ");
			}
			System.out.println();
		}
		//打印底牌
		System.out.print("\ndiPoker:");
		for (Integer te : diPoker) {
			System.out.print(mapPoker.get(te) + "   ");
		}
	}
}

你可能感兴趣的:(java原创,斗地主,Java,TreeMap,ArrayList,TreeSet)