繁体   English   中英

C 中的骰子游戏 50

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM