java枚举enum实现扑克牌

花色(黑、红、梅花、方块)

public enum Suit {
	SPADES,HEARTS,CLUBS,DIAMONDS
}

牌型(扑克中的A,就是ACE的缩写)

public enum Rank {
	ACE, DEUCE, THREE, FOUR, FIVE, SIX, SERVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING
}

牌(有花色和牌型两个属性)

public class Card {
	private Rank rank;

	private Suit suit;

	//集合存储张牌
	private static List deck = new ArrayList();

	public Card(Rank rank, Suit suit) {
		this.rank = rank;
		this.suit = suit;
	}

	static {
		for (Rank rank : Rank.values()) {
			for (Suit suit : Suit.values()) {
				//牌型和花色构成一张牌
				deck.add(new Card(rank, suit));
			}
		}
	}

	public Rank getRank() {
		return rank;
	}

	public void setRank(Rank rank) {
		this.rank = rank;
	}

	public Suit getSuit() {
		return suit;
	}

	public void setSuit(Suit suit) {
		this.suit = suit;
	}

	public static List getDeck() {
		//返回一副牌
		return deck;
	}

	public String toString() {
		return rank + " of " + suit;
	}
}

测试类

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

public class CardTest {

	public static void main(String[] args) {
		//几个玩家
		int hands = 4;
		//每个玩家手里有几张牌
		int perHand = 10;
		//把一副牌全部拿到
		List deck = Card.getDeck();
		System.out.println("****before shuffle deck****");
		System.out.println(deck);
		//打乱,就是洗牌
		Collections.shuffle(deck);
		System.out.println("****after shuffle deck****");
		System.out.println(deck);
		//4*13总共52张牌
		System.out.println("****total cards:" + deck.size() + "****");
		//给每个玩家发牌
		for (int i = 1; i <= hands; i++) {
			List hand = dealHand(deck, perHand);
			System.out.println("hand" + i + ":" + hand);
		}
	}

	private static List dealHand(List deck, int perHand) {
		int size = deck.size();
		System.out.println("****current deck size:" + deck.size() + "****");
		//取子集合,每次取最尾部的10张牌
		//
		List handView = deck.subList(size - perHand, size);
		List hand = new ArrayList(handView);
		//已经分发的牌清空 
                //<-!!! 注意clear同时对handView和deck产生影响 !!!->
		handView.clear();
		return hand;
	}
}

 

你可能感兴趣的:(java,java)