[英]Dice game in C for Fifty
我必須編寫一個 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”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.