请写一个21点游戏的c++代码
时间: 2023-12-19 15:05:25 浏览: 186
以下是一个简单的21点游戏的C代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int player_total = 0;
int dealer_total = 0;
int player_card1, player_card2, dealer_card1, dealer_card2;
char choice;
srand(time(NULL)); // 用当前时间作为随机数生成器的种子
// 发牌
player_card1 = rand() % 10 + 1;
player_card2 = rand() % 10 + 1;
dealer_card1 = rand() % 10 + 1;
dealer_card2 = rand() % 10 + 1;
printf("你的牌是:%d 和 %d\n", player_card1, player_card2);
printf("庄家的牌是:%d 和 ?\n", dealer_card1);
// 计算点数
player_total = player_card1 + player_card2;
dealer_total = dealer_card1;
// 玩家回合
do {
printf("你的总点数是:%d\n", player_total);
printf("是否要继续要牌?(y/n)\n");
scanf(" %c", &choice);
if (choice == 'y') {
int new_card = rand() % 10 + 1;
printf("你抽到的牌是:%d\n", new_card);
player_total += new_card;
}
} while (choice == 'y' && player_total <= 21);
// 庄家回合
while (dealer_total < 17) {
int new_card = rand() % 10 + 1;
printf("庄家抽到的牌是:%d\n", new_card);
dealer_total += new_card;
}
// 结果判断
printf("你的总点数是:%d,庄家的总点数是:%d\n", player_total, dealer_total);
if (player_total > 21) {
printf("你输了!\n");
} else if (dealer_total > 21) {
printf("你赢了!\n");
} else if (player_total > dealer_total) {
printf("你赢了!\n");
} else if (player_total < dealer_total) {
printf("你输了!\n");
} else {
printf("平局!\n");
}
return 0;
}
```
该代码使用了随机数生成器来模拟发牌过程,并且使用了循环语句来让玩家和庄家分别进行回合。最后通过比较点数来判断胜负。
阅读全文