21点游戏 java
时间: 2023-08-23 17:03:33 浏览: 40
以下是一个简单的21点游戏的Java代码示例:
```
import java.util.Scanner;
public class TwentyOneGame {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
int playerTotal = 0;
int dealerTotal = 0;
boolean gameOver = false;
while(!gameOver){
System.out.println("Dealer shows: " + dealerTotal);
System.out.println("Player total: " + playerTotal);
System.out.println("Enter 'hit' or 'stay': ");
String choice = input.nextLine();
if(choice.equalsIgnoreCase("hit")){
int card = drawCard();
playerTotal += card;
System.out.println("You drew a " + card);
if(playerTotal > 21){
System.out.println("Bust! You lose!");
gameOver = true;
}
} else if (choice.equalsIgnoreCase("stay")){
System.out.println("Dealer's turn.");
while(dealerTotal < 17){
int card = drawCard();
dealerTotal += card;
System.out.println("Dealer drew a " + card);
}
if(dealerTotal > 21){
System.out.println("Dealer busts! You win!");
} else if(dealerTotal > playerTotal){
System.out.println("Dealer wins!");
} else if(dealerTotal < playerTotal){
System.out.println("You win!");
} else {
System.out.println("It's a tie!");
}
gameOver = true;
} else {
System.out.println("Invalid input!");
}
}
input.close();
}
public static int drawCard(){
//generates a random number between 1 and 10 (inclusive)
return (int)(Math.random() * 10) + 1;
}
}
```
这个程序使用了一个while循环来控制游戏的进行。每次循环,程序会提示玩家选择“hit”或“stay”,然后根据玩家的选择来继续游戏。如果玩家选择“hit”,程序会随机生成一张牌并将其加到玩家的牌总数中。如果玩家总分数超过21,那么游戏结束,玩家输了。如果玩家选择“stay”,那么程序将进入到庄家的回合,庄家会一直抽牌(直到手牌总数大于等于17),然后比较庄家和玩家的牌总数,决定谁赢了。
这只是一个简单的示例,可以根据需要进行修改和扩展。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)