写一个21点扑克牌的游戏
时间: 2023-07-06 22:34:24 浏览: 94
以下是一个简单的21点扑克牌游戏的示例代码,供您参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// 定义扑克牌面值和花色
char *card_values[] = {"A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"};
char *card_suits[] = {"♠︎", "♣︎", "♥︎", "♦︎"};
// 定义函数:发牌
int deal_card()
{
int value = rand() % 13 + 1; // 随机生成牌面值
int suit = rand() % 4; // 随机生成花色
if (value > 10)
{
value = 10; // J/Q/K 的点数均为10
}
else if (value == 1)
{
value = 11; // A 的点数为 11
}
return value;
}
// 定义函数:计算点数
int calculate_points(int *cards, int num_cards)
{
int i, points = 0, num_aces = 0;
for (i = 0; i < num_cards; i++)
{
if (cards[i] == 11)
{
num_aces++; // 统计 A 的数量
}
points += cards[i]; // 累加点数
}
while (points > 21 && num_aces > 0)
{
points -= 10; // 将 A 视为 1 点
num_aces--;
}
return points;
}
// 主函数
int main()
{
int player_cards[10], dealer_cards[10]; // 定义两个数组,用于存放玩家和庄家的牌
int player_points, dealer_points, num_player_cards = 0, num_dealer_cards = 0;
char choice;
srand(time(NULL)); // 初始化随机数种子
// 发两张牌给玩家和庄家
player_cards[num_player_cards++] = deal_card();
dealer_cards[num_dealer_cards++] = deal_card();
player_cards[num_player_cards++] = deal_card();
dealer_cards[num_dealer_cards++] = deal_card();
// 显示玩家的牌和庄家的一张牌
printf("你的牌:");
for (int i = 0; i < num_player_cards; i++)
{
printf("%s%s ", card_suits[rand() % 4], card_values[player_cards[i] - 1]);
}
printf("\n庄家的牌:%s%s\n", card_suits[rand() % 4], card_values[dealer_cards[0] - 1]);
// 玩家的回合
while (1)
{
player_points = calculate_points(player_cards, num_player_cards);
printf("你的点数:%d\n", player_points);
if (player_points > 21)
{
printf("你爆了!\n");
break;
}
printf("是否要继续要牌?(y/n)\n");
scanf(" %c", &choice);
if (choice == 'y')
{
player_cards[num_player_cards++] = deal_card();
}
else
{
break;
}
}
// 庄家的回合
dealer_points = calculate_points(dealer_cards, num_dealer_cards);
while (dealer_points < 17)
{
dealer_cards[num_dealer_cards++] = deal_card();
dealer_points = calculate_points(dealer_cards, num_dealer_cards);
}
printf("庄家的牌:");
for (int i = 0; i < num_dealer_cards; i++)
{
printf("%s%s ", card_suits[rand() % 4], card_values[dealer_cards[i] - 1]);
}
printf("\n庄家的点数:%d\n", dealer_points);
// 判断胜负
if (player_points > 21)
{
printf("你输了!\n");
}
else if (dealer_points > 21)
{
printf("你赢了!\n");
}
else if (player_points > dealer_points)
{
printf("你赢了!\n");
}
else if (player_points < dealer_points)
{
printf("你输了!\n");
}
else
{
printf("平局!\n");
}
return 0;
}
```
在这个程序中,我们使用了随机数生成牌面值和花色,并通过 `deal_card()` 函数来发牌。我们还定义了 `calculate_points()` 函数来计算玩家和庄家的点数,并使用一个循环来进行玩家和庄家的回合。最后,根据点数的比较来判断胜负。
需要注意的是,这只是一个简单的示例程序,实际的21点游戏可能需要更多的规则和玩法。
阅读全文