0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

javascriptのwhile文とif文でゲームっぽい練習

Posted at
<script>
//変数を作る
let enemy = 100;
let command;
let kougeki;

これは最初に変数を用意すべきなのかな?
この場所で宣言しているだけなのかな?

while(true){
//promptは()の中に表示される文字を記載する
//選択肢は更に中に()で記載し【番号】で選択する
command = prompt('敵が現れた!(【1】戦う【2】逃げる)');
kougeki = Math.floor(Math.random()* 40);

このwhile文でこの後のif文が成立している間は繰り返すという処理になっているのかな?

if(command === '1'){
  
  //敵の体力からランダム数値の攻撃ダメージを引く
  enemy = enemy - kougeki;
  
  //ランダムダメージ数を表示
  console.log(kougeki + '攻撃!')
    
  //倒した時の処理
  //下記if文の(enemy <= 0)がtrueになるまで繰り返す
  if(enemy <= 0){
  console.log('敵を倒しました!')
  break;
  }
    //敵の残体力を表示
  console.log('敵の残り体力は' + enemy + 'です!' )
}

【1】を選んだ場合は<enemy(敵の体力)>からランダムで選ばれた<kougeki(攻撃)>の数値を引く
が0より小さくなったら、'敵を倒しました。'
が0よりも大きかったら、'敵の残り体力は・・・'と表示する。

 //ifの{}の外に記載する。【2】を選んだ時の処理
  else if(command === '2') {
  console.log('無事に逃げれました');
  break;
}  

最初の選択肢で【2】を選んだ時の処理。

}//while文の閉じ}です。
 //
console.log('ゲーム終了です!')
</script>

敵を倒すか、無事に逃げるかしたら処理終了

全文

<script>
//変数を作る
let enemy = 100;
let command;
let kougeki;

while(true){

//promptは()の中に表示される文字を記載する
//選択肢は更に中に()で記載し【番号】で選択する
command = prompt('敵が現れた!(【1】戦う【2】逃げる)');
kougeki = Math.floor(Math.random()* 40);

if(command === '1'){
  
  //敵の体力からランダム数値の攻撃ダメージを引く
  enemy = enemy - kougeki;
  
  //ランダムダメージ数を表示
  console.log(kougeki + '攻撃!')
    
  //倒した時の処理
  //下記if文の(enemy <= 0)がtrueになるまで繰り返す
  if(enemy <= 0){
  console.log('敵を倒しました!')
  break;
  }

    //敵の残体力を表示
  console.log('敵の残り体力は' + enemy + 'です!' )

 //ifの{}の外に記載する。【2】を選んだ時の処理
} else if(command === '2') {
  console.log('無事に逃げれました');
  break;
}  
}

console.log('ゲーム終了です!')
</script>
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?