java 写一个可以给斗地主玩家随机发牌的程序。

需求:写一个可以给斗地主玩家随机发牌的程序。a:牌可以随机发给三个玩家b:在控制台打印每个玩家的牌。c:对每个玩家手中的牌按照大小排序。

 
牌的花色:"♠", "♥", "♣", "♦"

思路:创建一个容器存储所有的牌,再创建三个容器分别表示三个用户的牌,三个用户轮流从第一个容器中取牌,剩下三张为底牌。把大王和小王也算进去。可以封装一个类表示牌
代码:Main.java

package hcq.hw;

import java.util.List;
import java.util.TreeSet;

public class Main {

	public static void main(String[] args) {
		Poker poker = new Poker();
		
		poker.getPoker();// 得到牌
		// 每个玩家存储牌的容器
		TreeSet p1 = new TreeSet<>();
		TreeSet p2 = new TreeSet<>();
		TreeSet p3 = new TreeSet<>();
		// 洗牌和发牌操作 返回的是底牌
		List dealPoker = poker.dealPoker(p1, p2, p3);

		// 删除牌
		System.err.println("玩家一:" + p1);
		System.err.println("玩家二:" + p2);
		System.err.println("玩家三:" + p3);
		System.out.println("底牌    :" + dealPoker);
	}

}

Poker.java
package hcq.hw;

import java.util.Collection;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;

public class Poker {

	private LinkedList pokers = new LinkedList<>();
	private char[] flowers = { '♦', '♣', '♥', '♠' };
	private char[] numbers = { '3', '4', '5', '6', '7', '8', '9', '0', 'J', 'Q', 'K', 'A', '2' };

	public Poker() {
		for (int i = 0; i < numbers.length; i++) {
			for (int j = 0; j < flowers.length; j++) {
				pokers.add(new Card(numbers[i], flowers[j], j + i * flowers.length));
			}
		}

		pokers.add(new Card('王', '小', 99));
		pokers.add(new Card('王', '大', 100));

	}

	// 初始化牌
	public static Poker getPoker() {
		return new Poker();
	}

	// 打印牌
	public void showPoker() {
		for (Card c : pokers) {
			System.out.println(c.toString());
		}
	}

	// 洗牌和发牌方法
	public List dealPoker(Collection play1, Collection play2, Collection play3) {
		Collections.shuffle(pokers);// 洗牌
		while (pokers.size() > 3) {
			play1.add(pokers.removeFirst());
			play2.add(pokers.removeFirst());
			play3.add(pokers.removeFirst());
		}
		return pokers;// 返回3张底牌
	}

}

Card.java
package hcq.hw;

public class Card implements Comparable {
	private char number;// 号码
	private char flower;// 花色
	private int grade;// 等级

	public Card(char number, char flower, int grade) {
		super();
		this.number = number;
		this.flower = flower;
		this.grade = grade;
	}

	@Override
	public String toString() {
		return "[" + flower + number + "]";
	}

	public char getNumber() {
		return number;
	}

	public void setNumber(char number) {
		this.number = number;
	}

	public char getFlower() {
		return flower;
	}

	public void setFlower(char flower) {
		this.flower = flower;
	}

	public int getGrade() {
		return grade;
	}

	public void setGrade(int grade) {
		this.grade = grade;
	}

	@Override
	public int compareTo(Card o) {
		return o.grade - this.grade;
	}

}

结果:

你可能感兴趣的:(javaSE)