使用Java写一个完整扑克牌游戏
时间: 2023-07-20 20:44:26 浏览: 88
好的,我可以为您提供一个完整的Java扑克牌游戏的实现。以下是完整的代码:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Scanner;
public class PokerGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来到扑克牌游戏!");
System.out.print("请输入玩家1的姓名:");
String player1Name = scanner.nextLine();
System.out.print("请输入玩家2的姓名:");
String player2Name = scanner.nextLine();
System.out.println("游戏开始!");
List<Card> deck = createDeck();
shuffleDeck(deck);
List<Card> player1Hand = new ArrayList<>();
List<Card> player2Hand = new ArrayList<>();
dealCards(deck, player1Hand, player2Hand);
System.out.println(player1Name + "的手牌:");
displayCards(player1Hand);
System.out.println("\n" + player2Name + "的手牌:");
displayCards(player2Hand);
int player1Score = calculateHandValue(player1Hand);
int player2Score = calculateHandValue(player2Hand);
System.out.println("\n" + player1Name + "的手牌总点数:" + player1Score);
System.out.println(player2Name + "的手牌总点数:" + player2Score);
if (player1Score > player2Score) {
System.out.println("\n" + player1Name + "获胜!");
} else if (player1Score < player2Score) {
System.out.println("\n" + player2Name + "获胜!");
} else {
System.out.println("\n双方平局!");
}
}
public static List<Card> createDeck() {
List<Card> deck = new ArrayList<>();
for (Suit suit : Suit.values()) {
for (Rank rank : Rank.values()) {
deck.add(new Card(suit, rank));
}
}
return deck;
}
public static void shuffleDeck(List<Card> deck) {
Collections.shuffle(deck);
}
public static void dealCards(List<Card> deck, List<Card> player1Hand, List<Card> player2Hand) {
for (int i = 0; i < deck.size(); i++) {
Card card = deck.get(i);
if (i % 2 == 0) {
player1Hand.add(card);
} else {
player2Hand.add(card);
}
}
}
public static void displayCards(List<Card> hand) {
for (Card card : hand) {
System.out.print(card + " ");
}
}
public static int calculateHandValue(List<Card> hand) {
int totalValue = 0;
for (Card card : hand) {
totalValue += card.getRank().getValue();
}
return totalValue;
}
}
enum Suit {
HEARTS, DIAMONDS, CLUBS, SPADES
}
enum Rank {
TWO(2), THREE(3), FOUR(4), FIVE(5), SIX(6), SEVEN(7), EIGHT(8), NINE(9), TEN(10), JACK(10), QUEEN(10), KING(10), ACE(11);
private int value;
Rank(int value) {
this.value = value;
}
public int getValue() {
return value;
}
}
class Card {
private Suit suit;
private Rank rank;
public Card(Suit suit, Rank rank) {
this.suit = suit;
this.rank = rank;
}
public Suit getSuit() {
return suit;
}
public void setSuit(Suit suit) {
this.suit = suit;
}
public Rank getRank() {
return rank;
}
public void setRank(Rank rank) {
this.rank = rank;
}
@Override
public String toString() {
return rank + " of " + suit;
}
}
```
这个程序可以实现一个简单的两个玩家的扑克牌游戏。在游戏开始时,程序会要求输入两个玩家的姓名,然后创建一副扑克牌,洗牌并将牌发给两个玩家。接下来,程序会计算每个玩家手中的牌的大小,并比较它们的大小。最后,程序会展示胜者或平局。
阅读全文