今日目標,定義卡片相關的類別和方法。
撲克牌遊戲最麻煩的地方就是要定義花色跟數字,還有牌型的大小比較...
package com.example.card;
public enum Suit {
SPADE,
HEART,
DIAMOND,
CLUB;
}
package com.example.card;
public enum Suit {
SPADE(4),
HEART(3),
DIAMOND(2),
CLUB(1);
private final int level;
Suit(int level) {
this.level = level;
}
// 大於
public boolean greaterThan(Suit other) {
return this.level > other.level;
}
// 小於
public boolean lessThan(Suit other) {
return this.level < other.level;
}
// 相等
public boolean equals(Suit other) {
return this.level == other.level;
}
}
level
代表該 Suit 的階級,其中黑桃(spade) 最大,所以設成 4,其他花色的值往下遞減greaterThan()
、lessThan()
、equals()
,則是根據他們的 level 做比較Suit spade = Suit.SPADE;
Suit heart = Suit.HEART;
spade.greaterThan(heart); // true
heart.lessThan(spade); // true
spade.equals(heart); // false
package com.example.card;
public enum Number {
ACE(12),
TWO(13),
THREE(1),
FOUR(2),
FIVE(3),
SIX(4),
SEVEN(5),
EIGHT(6),
NINE(7),
TEN(8),
JACK(9),
QUEEN(10),
KING(11);
private final int level;
Number(int level) {
this.level = level;
}
public boolean greaterThan(Number other) {
return this.level > other.level;
}
public boolean lessThan(Number other) {
return this.level < other.level;
}
public boolean equals(Number other) {
return this.level == other.level;
}
}
package com.example.card;
import lombok.Getter;
import lombok.Setter;
@Getter @Setter
public class Card {
private Suit suit;
private Number number;
public Card(Suit suit, Number number) {
this.suit = suit;
this.number = number;
}
@Override
public String toString() {
return this.suit + "-" + this.number;
}
}
package com.example.card;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class Deck {
private final ArrayList<Card> deck = new ArrayList<>();
public Deck() {
for (Suit suit : Suit.values()) {
for (Number number : Number.values()) {
this.deck.add(new Card(suit, number));
}
}
}
// 洗牌
public void shuffle() {
Collections.shuffle(this.deck);
}
// 發牌(分成 4 份)
public ArrayList<ArrayList<Card>> deal() {
ArrayList<ArrayList<Card>> result = new ArrayList<>();
int deckSize = this.deck.size();
int numberPerPerson = deckSize / 4;
int start = 0;
for (int i=0; i<4; i++) {
List<Card> tmp = this.deck.subList(start, start + numberPerPerson);
result.add(new ArrayList<>(tmp));
start += numberPerPerson;
}
while (start < deckSize) {
result.get(deckSize - start - 1).add(this.deck.get(start++));
}
return result;
}
}
今天稍微放鬆一下,定義一下之後的撲克牌(Card)、牌堆(Deck)和其洗牌(shuffle)和發牌(deal)的方法~~