1

我正在开发一个基于文本的小游戏。

有时当用户按下“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;
        }
    }

我运行了调试器,所有变量都很好,但是调用堆栈(我不知道返回了这个)

调用堆栈

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

4

3 回答 3

1

您的 userstats 或enemystats 的值可能较低,从而导致表达式

EnemyStats[0]-3

为零。这导致采用 mod 0 的东西,这很糟糕。

你可能会使用类似的东西

x ? y%x : x

得到你想要的行为。

于 2012-07-13T14:23:25.193 回答
0

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

于 2012-07-13T15:05:05.957 回答
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;

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

于 2012-07-14T00:59:46.207 回答