本程序为使用Java编写的简易发牌系统,能够模拟扑克游戏中的发牌过程,适用于学习和练习基础编程技能。
下面是一个简单的Java发牌小程序代码示例,该程序使用枚举类来表示扑克牌:
```java
import java.util.ArrayList;
import java.util.Collections;
// 定义花色的枚举类型
enum Suit {
SPADE, HEART, CLUB, DIAMOND
}
// 定义数值的枚举类型
enum Rank {
ACE(1), TWO(2), THREE(3), FOUR(4),
FIVE(5), SIX(6), SEVEN(7), EIGHT,
NINE(9), TEN(10), JACK(11), QUEEN(12),
KING(13);
private int value;
Rank(int v) {
this.value = v;
}
public int getValue() {
return this.value;
}
}
// 定义扑克牌类
class Card implements Comparable {
Suit suit; // 花色枚举实例引用
Rank rank; // 数值枚举实例引用
public Card(Suit s, Rank r) { // 构造方法,初始化花色和数值
this.suit = s;
this.rank = r;
}
@Override
public int compareTo(Card that) {
if (this.rank.getValue() < that.rank.getValue()) return -1;
else if (this.rank.getValue() > that.rank.getValue()) return 1;
else { // 排序时,同数值的牌按花色大小排序
switch(this.suit){
case SPADE: return -3;
case HEART: return -2;
case CLUB: return -1;
default : // DIAMOND
return 0;
}
}
}
}
// 定义发牌器类,用于生成一副随机洗好的扑克
class Deck {
private ArrayList cards;
public Deck() { // 构造方法
this.cards = new ArrayList<>();
for (Suit s : Suit.values()) { // 遍历花色枚举类型的所有实例
for(Rank r : Rank.values()){ // 内嵌循环,遍历数值枚举类型的所有实例
cards.add(new Card(s, r));
}
}
}
public void shuffle() {
Collections.shuffle(cards);
}
}
// 测试代码
public class ShuffleDeck {
public static void main(String[] args) {
Deck deck = new Deck(); // 生成一副牌并洗好
System.out.println(原始顺序:);
for (Card c : deck.cards)
System.out.print(c.rank + of + c.suit + , );
deck.shuffle();
System.out.println(\n\n发牌后随机的顺序:);
for (Card c : deck.cards)
System.out.print(c.rank + of + c.suit + , );
}
}
```
这段代码实现了一个简单的扑克牌游戏程序,其中包含创建一副完整的52张纸牌、洗牌功能以及打印输出的功能。通过使用枚举类来表示花色和数值,使得代码更加清晰且易于维护。