[英]"Big Pig" dice game code goes in infinite loop :C
您好,我是 c 新手,目前正在学习我的大学课程,所以我需要遵守以下规则:我们不能使用数组或全局变量。
所以我一直在尝试制作一个名为“大猪”的骰子游戏。 我现在正在创建计算机将用来玩名为“play_computer()”的游戏的函数。 还有一个名为“computer_strategy_decider()”的函数。Computer_strategy_decider() 应该从是或否中进行选择。 我刚刚做了一个 rand 函数,它调用 1 或 2 来完成这项工作。 Play_computer() 让你选择两个骰子,然后它需要计算分数。 如果您只选择一项,那么您的分数不会增加并且您的游戏将终止。 如果您遇到两个,则会增加 25 个。 如果您获得任何其他双精度值,例如 a ,则会添加 (a+a)*2 或 4*a 等。 最后,如果您得到两个随机数,计算机将决定是否继续。 这就是 computer_strategy_decider() 的用武之地。
问题来自 play_computer() 函数。 当计算机滚动两个不同的值并且不继续时,一切似乎都运行良好。 它终止正常。 但是如果它想继续,它就会进入无限循环。 无限循环也具有相同的骰子值。 滚动双打时会发生相同的循环。 我的代码中的某些内容无法正确循环。 我不知道这是否与 rand() 有关。 我不认为它是 rand(),因为我在 computer_strategy_decider() 上使用了 rand()。 我的理论是希望这是我错过的一些小事。
在我添加一些更改之前,我的代码在一个小时前工作,这就是为什么我很沮丧哈哈。
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <time.h>
int computer_strategy_decider(){
int deci;
srand(time(NULL));
deci=1+ (int) rand() % 2;
return deci;}
int play_computer(round_number,strategy){
int roll_1,roll_2,cntrl_var=0,score_comp=0;
char answ;
printf("\nRound %d-- My Turn:",round_number);printf("\n---------------------------------");
while(cntrl_var==0){
srand(time(NULL));
roll_1 = 1 + (int) rand() % 6;
roll_2 = 1 + (int) rand() % 6;
printf("\nI got --> [Dice 1]: %d [Dice 2]: %d",roll_1,roll_2);
if(roll_1==roll_2 && roll_1!=1){
score_comp=score_comp+roll_1*4;
printf("\nScore: %d",score_comp);printf("\nDoubles! Roll again!");}
else if(roll_1==1 && roll_2==1){
score_comp=score_comp+25;
printf("\nScore: %d",score_comp);printf("\nDoubles! Roll again!");}
else if(roll_1==1 || roll_2==1){
cntrl_var=1;
printf("\nYou got a single one! End of your turn!");}
else{
score_comp=score_comp+roll_1+roll_2;
printf("\nScore: %d",score_comp);
while(cntrl_var==0){
printf("\nDo you want to continue (Y/N)?");
if (strategy==1){
printf("Y");
break;}
else if (strategy==2){
printf("N");
break;}}
if (strategy==1)
cntrl_var=0;
else if (strategy==2)
cntrl_var=1;
else
cntrl_var=0;}}
printf("\nMy Score: %d",score_comp);
return score_comp;}
int main(){
int round_no=1,deci;
deci=computer_strategy_decider();
play_computer(round_no,deci);
}
我将 srand 放在 while 循环中,这导致 srand 被多次调用。 所以我把 srand 放在循环上面。 那就修好了!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.