我的教授给了我一个写一个16场比赛尼姆游戏的协议。
任务的一部分是让PC也能做出动作。因此,我试图通过使用SRAND解决问题,但PC选择了相同的行和相同数量的棒。更重要的是,当他拿下零重量时,PC也会占据空中并且撞到墙上。
所以,那就是我已经做过的事情。有什么想法吗?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define row 4
int main()
{
int theChecker = 1, sticks[row] = {1,3,5,7}, stickSum, i, choiceRow, choiceStick, pcRow, pcStick;
char answer;
do
{
printf("\n\n\t ************ \n");
printf("\t *THE NIM GAME* \n");
printf("\t ************ \n\n");
stickSum = sticks[0] + sticks[1] + sticks[2] + sticks[3];
while(stickSum > 0)
{
printf("\nStick log:\n");
for(i = 0; i < row; i++)
printf("Row %d: %d\n", i+1, sticks[i]);
printf("\n");
if(theChecker == 1)
{
printf("Choose a row: ");
scanf("%d", &choiceRow);
printf("Choose a sick: ");
scanf("%d", &choiceStick);
while((choiceRow <= 0) || (choiceRow > 4) || (sticks[choiceRow - 1] < choiceStick) || (choiceStick == 0))
{
printf("\n\t !!!ERROR!!!\n\tInvalid row or stick\n\nCheck stick log above\n\n");
printf("Choose a row: ");
scanf("%d", &choiceRow);
printf("Choose a sick: ");
scanf("%d", &choiceStick);
}
sticks[choiceRow-1] -= choiceStick;
stickSum -= choiceStick;
}
else //pc move starts-------------------------------------------
{
while(((pcRow <= 0) || (pcRow > 4)) && sticks[choiceRow - 1] == 0)
{
time_t seconds;
seconds = 0;
time(&seconds);
srand((unsigned int)seconds);
pcRow = rand() % 4;
}
printf("PC ROW: %d\n", pcRow);
while((sticks[pcRow - 1] < pcStick) || (pcStick == 0))
{
time_t seconds2;
seconds2 = 0;
time(&seconds2);
srand((unsigned int)seconds2);
pcStick = rand() % 16;
}
printf("PC STICK: %d\n\n", pcStick);
sticks[pcRow-1] -= pcStick;
stickSum -= pcStick;
}
if((theChecker == 1) && (stickSum == 0))
printf("\n\n!!!GAME OVER!!! You took the last stick!!!\n\n");
else if((theChecker == 2) && (stickSum == 0))
printf("\n\n!!!CONGRATS!!! You won!!!\n\n");
theChecker++;
if(theChecker == 3)
theChecker -= 2;
}
printf("\nPress r to restart the game or any key to end the game: ");
scanf("%c", &answer);
printf("\n");
}
while(answer == 'r');
return 0;`enter code here`
}
答案 0 :(得分:2)
不要多次调用srand()
,它用于初始化随机种子,您始终将其初始化为相同的值,即内部状态一遍又一遍地重置,总是产生相同的伪随机值。
我说你总是传递相同的种子,因为time()
具有秒分辨率,并且在一秒钟内,整个游戏都被播放和终止。
您只需在程序开头调用srand()
,以防止程序在程序运行期间选择相同的值,而不是在同一运行中。