Java实现斗地主发牌系统

package pack_0;

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

public class sendPokers {
	public static void main(String[] args) {
		// 1.买牌
		Map pokers = new HashMap<>();// 创建双列集合
		List list = new ArrayList<>();// 用来存放下标
		String[] colors = { "♠", "♥", "♣", "♦" };
		String[] numbers = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A" };
		int num = 0;// num表示牌的编号
		for (String number : numbers) { // 外循环:获取所有的点数
			for (String color : colors) { // 内循环:获取所有的花色
				String poker = color + number;
				// 将拍的编号,具体的牌放到双列集合中
				pokers.put(num, poker);
				// 将拍的编号放到单列集合中
				list.add(num);
				// 每添加一张牌,编号都要自加1
				num++;
			}
		}
		// 添加大小王
		pokers.put(num, "大王");
		list.add(num++);// --> list.add(num) num++
		pokers.put(num, "小王");
		list.add(num);
		/*
		 * System.out.println(pokers); System.out.println(list);
		 */

		// 2.洗牌和发牌
		Collections.shuffle(list);// 洗牌

		// 定义四个集合,分别表示3个玩家和底牌
		List laozhou = new ArrayList();
		List xiaozhou = new ArrayList();
		List zhongzhou = new ArrayList();
		List dipai = new ArrayList();

		// 发牌 -- 将索引对三取模,决定发给哪个玩家
		for (int i = 0; i < list.size(); i++) {
			Integer pokerNum = list.get(i);// 获取下标,下标越小,牌越小
			if (i >= list.size() - 3) {
				dipai.add(pokerNum);// 将最后三张牌给底牌
			} else if (i % 3 == 0) {
				laozhou.add(pokerNum);// 给老周
			} else if (i % 3 == 1) {
				xiaozhou.add(pokerNum);// 给小周
			} else if (i % 3 == 2) {
				zhongzhou.add(pokerNum);// 给中周
			}
		}
		/*得到的是牌的下标,对照下标可得到具体的牌
		System.out.println("老周的牌:" + laozhou);
		System.out.println("小周的牌:" + xiaozhou);
		System.out.println("中周的牌:" + zhongzhou);
		System.out.println("底牌:" + dipai);*/
		
		System.out.println("**************************************************");
		String str1 = printPoker(laozhou,pokers);
		System.out.println("老周的牌:" + str1);
		String str2 = printPoker(xiaozhou,pokers);
		System.out.println("小周的牌:" + str2);
		String str3 = printPoker(zhongzhou,pokers);
		System.out.println("中周的牌:" + str3);
		String str4 = printPoker(dipai,pokers);
		System.out.println("底牌:" + str4);
		System.out.println("**************************************************");

	}

	// 3.看牌
	public static String printPoker(List nums, Map pokers) {
		//对牌的编号进行升序排列
		Collections.sort(nums);
		StringBuilder sb = new StringBuilder();
		//增强for循环遍历牌的编号集合,获取到每一个编号
		for(Integer num:nums) {
			//根据编号去双列集合中查找该编号对应的具体牌
			String poker = pokers.get(num);
			//每得到一张牌就将其加入sb中
			sb.append(poker + " ");
		}
		//将获取的牌进行拼接
		String str = sb.toString();
		//去掉首尾空格
		return str.trim();
	}
}

 

你可能感兴趣的:(Java自学)