c - C 中的骰子游戏 50
问题描述
我必须编写一个 C 程序来为两个人掷骰子。确定获胜者后,我需要它循环并要求再次播放。如果输入 q,程序将结束。如果用户按下进入,程序将继续并询问谁先玩,然后再次确定获胜者。程序运行一次后,我输入 1 或 2 它只是一直显示祝贺 player1or2 你赢了。它永远不会回到我的 while 循环中(playerTotal1 < WinScore)。我已经在 while(end!= q) 的 while 循环中再次初始化了 playerTotal 和 Winscore = 0 但它没有改变任何东西。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int dice1, dice2;
srand((unsigned)time(NULL));
int player1Total = 0, player2Total = 0, playerTurn;
int currentSum;
int WinScore = 50;
char end = ' ';
printf("Welcome to Dice Game Fifty. The first player who reaches %d wins!\n", WinScore);
while (end != 'q' && end != 'Q')
{
player1Total = 0; player2Total = 0;
printf("Choose who rolls first, player1 or player2 (1 or 2): ");
scanf_s("%d", &playerTurn);
while (playerTurn != 1 && playerTurn != 2 )
{
printf("Only 2 players play this game...\n");
printf("Choose the first player to roll (1 or 2): ");
scanf_s("%d", &playerTurn);
}
while (player1Total < WinScore && player2Total < WinScore)
{
dice1 = rand() % 6 + 1;
dice2 = rand() % 6 + 1;
currentSum = 0;
if (dice1 == dice2)
{
if (dice1 == 6)
currentSum = 25;
else if (dice1 == 3)
{
currentSum = 0;
if (playerTurn == 1)
player1Total = 0;
else
player2Total = 0;
}
else
currentSum = 5;
}
if (playerTurn == 1)
player1Total += currentSum;
else
player2Total += currentSum;
printf("Player %d: You rolled (%d, %d), and so your round score is: %d, and your final score as of now is: ", playerTurn, dice1, dice2, currentSum);
if (playerTurn == 1)
printf("%d\n", player1Total);
else
printf("%d\n", player2Total);
if (playerTurn == 1)
playerTurn = 2;
else
playerTurn = 1;
}
if (playerTurn == 1)
printf("Congratulations to Player2. You WON.\n");
else
printf("Congratulations to Player1. You WON.\n");
printf("Enter q to quit or enter to continue: ");
scanf_s("%s", &end);
}
}
解决方案
scanf_s 方法不适用于空输入,因此如果您只是按 Enter 键,它将尝试读取另一行(不是循环不再执行,而是您的代码永远不会从 scanf_s 返回)。您应该尝试其他方法,例如 fgets 或 getch。对于 char 变量,我认为 getch 更适合您(getch 是特定于 Windows 的,但是当您使用 scanf_s 时,我认为这不会成为问题)。
printf("Enter q to quit or any other key to continue\n");
end = getch();
由于 getch 的工作方式,您必须在 printf 中添加一个新行。我还将消息更改为“任何其他键”,因为在您的循环中您只检查“q”或“Q”。
推荐阅读
- php - 从查询的查询中引用一个变量
- python - 没有名为“openpyxl.styles”的模块
- python - LSTM模型的准确率很低
- python - 当状态值相互重叠时,在 python 中处理状态机中的转换
- python - 如何获取字符串中每个字符的ord(unicode)?
- jhipster - 更新 Jhipster 用户实体
- android - 如何在运行时使用基于 android sdk 版本的库的可变版本?
- tfs - 如何在部署组注册脚本中显示“用户身份验证令牌”复选框
- image - 在 Azure 中创建自定义 Linux 32 位映像
- pm2 - 未找到 npm 命令 pm2:未找到命令