用java实现扑克牌小游戏,要包含以下要求: 首先,扑克牌有俩个参数:花色和点数 编写一个程序,创建一牌类(包括花色和点 数)。 扑克牌的初始化,扑克牌除了大小王一共是5 2张,用集合类初始化扑克牌 洗牌 发牌 游戏玩法:三个人每人发一张比大小 要给出完整代码以及运行结果
时间: 2024-11-12 15:40:51 浏览: 37
Java语言编写扑克牌小游戏
为了实现这个简单的扑克牌小游戏,我们将使用Java语言,并利用`ArrayList`作为集合类来存储扑克牌。首先,我们定义一个`Card`类表示扑克牌,它有两个属性:`suit`(花色)和`rank`(点数)。然后我们会创建一个`Deck`类来处理牌堆的操作,包括洗牌和发牌。
```java
import java.util.ArrayList;
import java.util.Collections;
class Card {
enum Suit { SPADES, HEARTS, DIAMONDS, CLUBS }
enum Rank { ACE(1), TWO(2), THREE(3), FOUR(4),
FIVE(5), SIX(6), SEVEN(7), EIGHT(8),
NINE(9), TEN(10), JACK(11), QUEEN(12),
KING(13);
private final int value;
private Suit suit;
Card(Suit suit, int rank) {
this.suit = suit;
this.value = rank.getValue();
}
public Suit getSuit() {
return suit;
}
public int getValue() {
return value;
}
@Override
public String toString() {
return suit.name().charAt(0) + rank.name();
}
}
class Deck {
private ArrayList<Card> cards;
public Deck() {
cards = new ArrayList<>();
for (Suit suit : Card.Suit.values()) {
for (Rank rank : Card.Rank.values()) {
if (rank != Card.Rank.ACE_OF_SPADS && rank != Card.Rank.KING_OF_HEARTS) {
cards.add(new Card(suit, rank));
}
}
}
}
// 洗牌
public void shuffle() {
Collections.shuffle(cards);
}
// 发牌给玩家
public void dealToPlayer(Player player) {
if (!cards.isEmpty()) {
player.receiveCard(cards.remove(0));
} else {
System.out.println("牌已发完");
}
}
}
class Player {
private ArrayList<Card> hand;
public Player() {
hand = new ArrayList<>();
}
public void receiveCard(Card card) {
hand.add(card);
System.out.println("给玩家 " + card + "(" + card.getSuit().name() + " " + card.getRank().value + ")");
}
// 比大小(这里简化为比较点数)
public boolean compareHands(Player other) {
int thisScore = getHandValue();
int otherScore = other.getHandValue();
return thisScore > otherScore;
}
private int getHandValue() {
int score = 0;
for (Card card : hand) {
score += card.getValue();
}
return score;
}
public String getHand() {
StringBuilder sb = new StringBuilder();
for (Card card : hand) {
sb.append(card).append(", ");
}
return sb.toString();
}
}
public class PokerGame {
public static void main(String[] args) {
Deck deck = new Deck();
deck.shuffle();
Player player1 = new Player();
Player player2 = new Player();
Player player3 = new Player();
deck.dealToPlayer(player1);
deck.dealToPlayer(player2);
deck.dealToPlayer(player3);
System.out.println("玩家1的手牌:" + player1.getHand());
System.out.println("玩家2的手牌:" + player2.getHand());
System.out.println("玩家3的手牌:" + player3.getHand());
if (player1.compareHands(player2)) {
System.out.println("玩家1胜过玩家2");
} else if (player2.compareHands(player1)) {
System.out.println("玩家2胜过玩家1");
} else {
System.out.println("平局");
}
}
}
```
运行上述代码后,会随机生成三张牌并分配给三个玩家,然后比较他们的手牌大小。注意这只是一个基础版本,实际游戏中可能会更复杂,比如考虑大小王、同花顺等规则。此外,这里只展示了核心功能,你可以根据需要添加更多游戏玩法。
阅读全文