LoginSignup
metaton
@metaton (metaton Go)

Are you sure you want to delete the question?

Leaving a resolved question undeleted may help others!

[C言語]RPGを作ろうとしているが無限ループになる原因が分からない

解決したいこと

現在Cで文字だけのRPGを作っていたのですが突然無限ループになってしまいました。誰か原因をお教えください。また、qiitaを使うのはこれが初めてですので読みにくかったらごめんなさい。

該当するソースコード

#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main(void){
  srand(time(NULL));
  int attackp = rand()%200+1;
  int attacke = rand()%300+1;
  int HPP = 500;
  int HPE = 1000;
  int DefenseP = 100;
  int DetenseE = 70;
  int comand;
  char name;
  int damersep = attackp - (attackp*(DetenseE/100));
  printf("\nPlayer: Life-%d. Attack-100. Defense-%d \n",HPP,DefenseP);
  printf("SANSE: Life-%d. Attack-200. Defense-%d", HPE,DetenseE);
  printf("\n(0) Attack\n(1) Skill\n(2) Heal\n");
  while (HPE != 0 && HPP != 0)
  {
    srand(time(NULL));
    attackp = rand()%200+1;
    attacke = rand()%300+1;
    printf("\nCommand:");
    scanf("%d", &comand);
    if (comand == 0){
      printf("Playerは攻撃した!\n");
      HPE -= damersep;
      printf("%dのダメージを与えた!",damersep);
    }else if (comand == 1)
    {
      printf("Playerはスキルを使った!\n");
    }else if (comand == 2)
    {
      printf("Playerは回復した!\n");
    }else{
      printf("Commandが違います");
    }
    if (HPE == 0 || HPP == 0)
    {
      if (HPE == 0)
      {
        printf("YOUR WIN!!");
        break;
      }
      else if (HPP == 0)
      {
        printf("YOUR LOSE...");
        break;
      }


    }

    HPE -= 600;
  }

}

自分で試したこと

自分で試したことコードを片っ端から見直しましたが分からなかったので質問させて頂きました。

0

2Answer

while (HPE != 0 && HPP != 0)

ループ中でHPPからは値が引かれている様子はないので500のままなのと、HPEから値が引かれた際に0を通り越してマイナス値になってしまっても上記条件は成立してしまうからではないでしょうか。

3

Comments

  1. @metaton

    Questioner
    回答ありがとうございます。
    確かに考えてみればそうですね、やっと先に進めましたありがとうございます。
        if (HPE <= 0 || HPP <= 0)
        //if (HPE == 0 || HPP == 0)
        {
            if (HPE <= 0)
            //if (HPE == 0)
            {
                printf("YOUR WIN!!");
                break;
            }
            else if (HPP <= 0)
            //else if (HPP == 0)
            {
                printf("YOUR LOSE...");
                break;
            }
        }

勝敗判定の部分がHPがちょうど0になった場合のみしか処理しないようになっていたのでbreakされなかったことが原因かと思われます

    //while (HPE != 0 && HPP != 0)
    while (1)

また勝利か敗北まで処理はループし続けると思うので上記whileの部分に条件は不要(常にTrue)で良いかと思います

処理が分かりにくい場合は入力コマンドの直前にHPPとHPEの内容を表示するようにするとループ内の処理が分かりやすくなるかと思います

1

Comments

  1. @metaton

    Questioner
    回答ありがとうございます。
    おかげさまで先に進めました本当にありがとうございました

Your answer might help someone💌