该程序模拟掷骰子的游戏,该游戏有两个骰子。在第一个掷骰中,如果骰子的总和是7或11,则玩家获胜。如果掷骰子的总和是2、3或12,则玩家将输。其他掷骰被称为“点”,然后游戏继续。在随后的每次掷骰中,如果玩家再次掷出“点”,则获胜。玩家通过掷骰7输了。任何其他掷骰将被忽略,游戏继续进行。
我使用函数roll_dice(void)
生成了1到6之间的两个随机数,然后将它们加在一起。我知道问题在于,似乎无法在while
循环中生成另一个数字。
#include <stdio.h>
#include <stdbool.h>
#include <time.h>
#include <stdlib.h>
int roll_dice(void);
int main(void)
{
int a, pointer;
int win = 0, lose = 0;
a = roll_dice(); /*Assigns the sum of the 2 generated random numbers to a*/
printf("%d\n", a);
printf("You rolled: %d\n", a);
if (a == 2 || a == 3 || a == 12) { /*First roll's loss condition*/
printf("You lose!");
lose = 1;
}
else if (a == 7 || a == 11) { /*First roll's win condition*/
printf("You win!\n");
win = 1;
}
else { /*Otherwise the first roll is assigned to a 'pointer' */
pointer = a;
printf("Your point is: %d\n", pointer);
}
while (!win || !lose) { /*While the game is still on */
a = roll_dice(); /*The problem is here, the roll_dice got called for the second time, yet still produces the same sum */
printf("You rolled: %d\n", a);
if (a == 7) {
printf("You lose!\n");
lose = 1;
break;
}
if (a == pointer) {
printf("You win!\n");
win = 1;
break;
}
}
return 0;
}
int roll_dice(void) /*Generates 2 random number from 1 to 6 and add them*/
{
int a, b;
srand((unsigned) time(NULL));
a = rand() % 5 + 1;
b = rand() % 5 + 1;
return a + b;
}
由于每次都会返回两个相同的数字,因此游戏大部分时间都是赢了:(