java实现21点小游戏
时间: 2023-08-28 13:06:28 浏览: 85
Java 实现小游戏21点
下面是一个简单的 Java 代码实现 21 点小游戏:
```java
import java.util.Scanner;
public class Blackjack {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int total = 0;
int card1 = (int)(Math.random() * 11) + 1;
int card2 = (int)(Math.random() * 11) + 1;
total += card1 + card2;
System.out.println("Your cards: " + card1 + ", " + card2);
System.out.println("Total: " + total);
while (total < 21) {
System.out.print("Do you want another card? (y/n): ");
String answer = input.next();
if (answer.equals("y")) {
int card = (int)(Math.random() * 11) + 1;
total += card;
System.out.println("Your card: " + card);
System.out.println("Total: " + total);
} else {
break;
}
}
if (total == 21) {
System.out.println("You win!");
} else if (total > 21) {
System.out.println("You lose!");
} else {
System.out.println("Dealer's turn.");
int dealerTotal = (int)(Math.random() * 6) + 16;
System.out.println("Dealer's total: " + dealerTotal);
if (dealerTotal > 21 || total > dealerTotal) {
System.out.println("You win!");
} else {
System.out.println("You lose!");
}
}
}
}
```
运行上述代码后,程序会随机发两张牌给玩家,并询问玩家是否需要再要一张牌,直到玩家决定不要牌或者牌的总点数超过了 21 点。然后程序会模拟庄家的回合,庄家的点数是 16 到 21 之间的随机数,然后与玩家的点数进行比较,判断谁获胜。
注意:这只是一个简单的实现,没有考虑到拆牌、保险等复杂规则。
阅读全文