菜单选项导致程序失败。 (C)

时间:2012-07-13 14:00:48

标签: c debugging callstack

我正在制作一个基于文字的小游戏。

当用户按下“1”或点击程序时,用户有一些攻击选项:

  while(1)
    {
    if (round > 1) //First time no pause
        Sleep(500); //Cleans up timing... i like it

    score_round = 0;
    //This is so ugly fix it!
    printf("Round %d: \nChoose Your Attack:(1/2/.../D)\n\n1.Jab\t\tOr D to defend\n2.Cross\n3.Hook\n",round);
    action = getch();

    //Create the damage for each player
        if(action == '1')
        {
            UserAttack = rand() % (UserStats[0]-2);
            EnemyAttack = rand() % (EnemyStats[0]-3);
            break;
        }

        else if(action == '2')
        {
            UserAttack = rand()  %UserStats[0];
            EnemyAttack = rand() %EnemyStats[0];
            break;
        }

        else if(action == '3')
        {
            UserAttack = rand()  %(UserStats[0]+4);
            EnemyAttack = rand() %(EnemyStats[0]+2);
            break;
        }

        else if(action == 'D' || action == 'd')
        {
            UserAttack= 0;
            EnemyAttack = defense(); //Defense randomizes a number upto 3 if it is 1 the enemy attack is 1 point
            break;
        }

        else //Ensures the key pressed is a valid choice
        {
            system("cls");
            printf("INVALID ACTION PRESS ANY KEY TO RECHOOSE:"); getch(); //TODO: Pressing this clears the health screen!
            system("cls"); //Clears screen just in case
            continue;
        }
    }

我运行调试器并且所有变量都没问题,但调用堆栈(我不知道返回此内容)

Call Stack

如果您需要更多信息,请告诉我们!谢谢!

3 个答案:

答案 0 :(得分:1)

您可以为userstats或enemystats设置较低的值,从而导致表达式

EnemyStats[0]-3

为零。这导致采取mod 0,这是不好的。

您可能会使用类似

的内容
x ? y%x : x

获得您想要的行为。

答案 1 :(得分:0)

我认为switch case是一个更好的选择,如果违反了代码可读性,那就太多了。

答案 2 :(得分:0)

我通过用

替换if(action =='1'){}中的内容来修复它
                if(UserStats[0]  <= 2) UserAttack  = rand() %2; //Ensure users strength is above 2
                else UserAttack = rand() % (UserStats[0]-2);

                if(EnemyStats[0] <= 3) EnemyAttack = rand() %2; //Ensures enemies strength is above 3
                else EnemyAttack = rand() % (EnemyStats[0]-3);
                break;

感谢大家的帮助和支持!我确信有一种更简单的方法可以做到这一点,但我喜欢这种方式,因为它可以帮助我更好地理解未来使用的代码! :)

相关问题