首页 > 解决方案 > “大猪”骰子游戏代码进入无限循环:C

问题描述

您好,我是 c 新手,我目前正在学习我的大学课程,所以我需要遵守以下规则:我们不能使用数组或全局变量。

所以我一直在尝试制作一个名为“大猪”的骰子游戏。我现在正在创建计算机将用来玩名为“play_computer()”的游戏的函数。还有一个名为“computer_strategy_decider()”的函数。Computer_strategy_decider() 应该选择是或否。我刚刚创建了一个调用 1 或 2 的 rand 函数来完成这项工作。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);
}

标签: crandomdice

解决方案


我将 srand 放在 while 循环中,这导致 srand 被多次调用。所以我把 srand 放在循环之上。那解决了它!


推荐阅读