我正在尝试制作一个非常简单的游戏(即使没有界面)。您应该键入想要执行的操作(攻击或阻止)。但是为什么我的(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!");
        }
    }
}

最佳答案

您想在其中一名玩家死亡时停止片刻吗?然后,您应该放一个&&。因为||除非两个玩家的hp都低于0,否则永远不会为假。

关于java - 不明白为什么我的||不管用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30947849/

10-12 02:10