2015-06-19 45 views
2

我想做一個非常簡單的遊戲(即使沒有界面)。你應該輸入你想要做什麼動作(攻擊或阻止)。但爲什麼我的(enemy_hp > 0 || hp > 0)聲明不起作用?循環永遠。不明白爲什麼我的||不工作

public class Game { 
    public static void main(String[] args){ 
     int hp = 10, enemy_hp = 10; 
     String attack = "attack"; 
     String block = "block"; 
     Scanner userInput = new Scanner (System.in); 
     while (enemy_hp > 0 || hp > 0) { 
      System.out.println("It is your turn, attack or try to block"); 
      int your_block_chance1 = (int) (Math.random() * 4); //Chance to block an attack 
      int enemy_block_chance1 = (int) (Math.random() * 4); 
      String action = userInput.next(); 
      if (action.equals(attack)){ 
       System.out.print("You attacked your enemy and "); 
       if (enemy_block_chance1 == 0) { 
        System.out.println("he blocked it"); 
       } 
       else if (enemy_block_chance1 != 0){ 
        enemy_hp = enemy_hp - 2; 
        System.out.println("managed to hit, now his hp is " +enemy_hp); 
       } 
      }  
      else if (action.equals(block)){ 
       System.out.println("You dicided to block"); 
       your_block_chance1 = 0; 
      } 
      System.out.print("It is your enemy turn, he decided to "); 
      int enemy_action = (int) (Math.random() * 2); 
      if (enemy_action == 1){ 
       System.out.print("attack you,"); 
       if (your_block_chance1 == 0){ 
        System.out.println(" but you blocked it"); 
       } 
       else if (your_block_chance1 != 0){ 
        hp = hp - 2; 
        System.out.println(" and you didn't block it, now your hp is " +hp); 

       } 
      } 
      else if (enemy_action != 1){ 
       System.out.print("do a heavy attack"); 
       int heavy_attack_chance = (int) (Math.random() * 2); 
       if (heavy_attack_chance == 1){ 
        System.out.println(" but failed"); 
       } 
       else if (heavy_attack_chance != 1){ 
        if (your_block_chance1 == 0){ 
         System.out.println(" but you blocked it"); 
        } 
        else if (your_block_chance1 != 0){ 
         hp = hp - 4; 
         System.out.println(" and he managed to hit you really hard, now your hp is " +hp); 

        } 
       } 
      } 
     } 
     if (hp <= 0){ 
      System.out.println("You failed"); 
     } 
     else if (enemy_hp <= 0){ 
      System.out.println("You won!"); 
     } 
    } 
} 

回答

8

你想讓一個玩家死的時候停止嗎?那麼你應該把一個& &。因爲||除非兩名玩家的HP值低於0,否則不會是假的。

2

如果你想在或者敵人或者玩家的生命值降至零或者低於零時停止,那麼你希望你的循環條件爲使用邏輯運算符,而不是OR:

while (enemy_hp > 0 && hp > 0) { 

繼續雖然兩者都是大於零。因此,當(或兩者)都爲零或低於0時,停止

2

您的病情使用||或OR。這意味着你的循環將繼續,而敵方HP是積極的,或HP的玩家是積極的(這意味着它會在敵方HP達到0後繼續)。改爲改爲&&

相關問題