用Java语言设计一个21点游戏,要求玩家与Al对抗,双方都能看到对方明牌,不考虑庄家和闲家,加倍等情况
时间: 2023-10-10 19:05:13 浏览: 68
以下是一个简单的21点游戏的Java代码实现,双方玩家和AI都能看到对方明牌:
```java
import java.util.ArrayList;
import java.util.Collections;
import java.util.Scanner;
public class BlackjackGame {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("欢迎来玩21点游戏!");
// 创建一副52张的扑克牌
ArrayList<String> deck = new ArrayList<>();
String[] suits = {"♠️", "♥️", "♣️", "♦️"};
String[] ranks = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
for (String suit : suits) {
for (String rank : ranks) {
deck.add(rank + suit);
}
}
// 洗牌
Collections.shuffle(deck);
// 初始化玩家和AI的手牌
ArrayList<String> playerHand = new ArrayList<>();
ArrayList<String> aiHand = new ArrayList<>();
// 发牌
for (int i = 0; i < 2; i++) {
playerHand.add(deck.remove(0));
aiHand.add(deck.remove(0));
}
// 显示玩家和AI的手牌
System.out.println("你的手牌:" + playerHand);
System.out.println("AI的手牌:" + aiHand.get(0) + " 和一张暗牌");
// 玩家回合
while (true) {
System.out.println("请选择:1.要牌 2.停牌");
int choice = scanner.nextInt();
if (choice == 1) {
playerHand.add(deck.remove(0));
System.out.println("你的手牌:" + playerHand);
int playerTotal = getTotal(playerHand);
if (playerTotal > 21) {
System.out.println("你爆了!");
break;
}
} else {
break;
}
}
// AI回合
while (getTotal(aiHand) < 17) {
aiHand.add(deck.remove(0));
System.out.println("AI的手牌:" + aiHand);
}
// 判断胜负
int playerTotal = getTotal(playerHand);
int aiTotal = getTotal(aiHand);
if (playerTotal > 21) {
System.out.println("AI赢了!");
} else if (aiTotal > 21) {
System.out.println("你赢了!");
} else if (playerTotal > aiTotal) {
System.out.println("你赢了!");
} else if (aiTotal > playerTotal) {
System.out.println("AI赢了!");
} else {
System.out.println("平局!");
}
}
// 计算手牌点数
public static int getTotal(ArrayList<String> hand) {
int total = 0;
int aceCount = 0;
for (String card : hand) {
String rank = card.substring(0, card.length() - 1);
if (rank.equals("A")) {
aceCount++;
} else if (rank.equals("J") || rank.equals("Q") || rank.equals("K")) {
total += 10;
} else {
total += Integer.parseInt(rank);
}
}
for (int i = 0; i < aceCount; i++) {
if (total + 11 > 21) {
total += 1;
} else {
total += 11;
}
}
return total;
}
}
```
上面的代码使用了ArrayList来表示扑克牌和手牌,使用了Collections的shuffle方法来洗牌,使用了Scanner来获取玩家的选择。在计算手牌点数时,特别处理了A牌的情况。
阅读全文