我试图让用户输入 y 或 n,游戏将退出或继续。我还想显示总输赢和用户退出。也许我没有真正掌握 boolean 值并返回函数中的东西?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdbool.h>
int rollDice(void);
bool playGame(void);
int main(void)
{
srand((unsigned)(time(NULL)));
char userInput;
while (true)
{
playGame();
printf("Would you like to play again?");
scanf("%c", &userInput);
if (userInput == 'n' || userInput == 'N')
{
return false;
}
else
{
return true;
}
}
return 0;
}
int rollDice(void)
{
int dice1 = rand()%6+1;
int dice2 = rand()%6+1;
int totaldice = dice1 + dice2;
return totaldice;
}
bool playGame(void)
{
int point, total;
int winCounter, looseCounter;
printf("The game is starting!\n");
total = rollDice();
printf("You rolled: %d\n", total);
if (total == 7 || total == 11)
{
printf("Wow it's your lucky day! You Win!\n");
winCounter++;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("Unlucky! You Loose!\n");
looseCounter++;
}
else {
point = total;
printf("Your Point is: %d\n", point);
while (true)
{
total = rollDice();
printf("You rolled: %d\n", total);
if (total == point)
{
printf("You made your point! You Win!\n");
winCounter++;
break;
}
else if (total == 7)
{
printf("Thats a %d. You Loose!\n", total);
looseCounter++;
break;
}
}
}return true;
}
最佳答案
您的主要问题是,如果用户输入的内容与 'n'
或 'N'
不同,您会使用 return
终止 main指令。删除它,循环可以继续。
如果使用 boolean 变量退出 while 循环会更好:
int main(void)
{
srand((unsigned)(time(NULL)));
char userInput;
bool paygame = true;
while (paygame)
{
playGame();
printf("Would you like to play again?");
scanf(" %c", &userInput);
printf ("Test: %c\n", userInput);
if (userInput == 'n' || userInput == 'N')
{
paygame = false;
}
}
return 0;
}
第二个大问题是 playgame 函数的计数器:它们必须初始化为 0。
int winCounter = 0, looseCounter = 0;
否则从随机数开始计数。
如果你想计算所有玩过的游戏的所有输赢,你可以简单地使用静态变量:
bool playGame(void)
{
int point, total;
static int winCounter = 0, looseCounter = 0;
printf("The game is starting!\n");
total = rollDice();
printf("You rolled: %d\n", total);
if (total == 7 || total == 11)
{
printf("Wow it's your lucky day! You Win!\n");
winCounter++;
}
else if (total == 2 || total == 3 || total == 12)
{
printf("Unlucky! You Loose!\n");
looseCounter++;
}
else {
point = total;
printf("Your Point is: %d\n", point);
while (true)
{
total = rollDice();
printf("You rolled: %d\n", total);
if (total == point)
{
printf("You made your point! You Win!\n");
winCounter++;
break;
}
else if (total == 7)
{
printf("Thats a %d. You Loose!\n", total);
looseCounter++;
break;
}
}
}
printf ("Won: %d - Lose: %d\n", winCounter, looseCounter);
return true;
}
最后一件事是将 scanf
格式说明符更改为 "%c"
以允许 scanf
“刷新”换行符 '\n '
字符在用户每次输入后留在 stdin
中。
关于c - 掷骰子游戏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39974904/