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