我正在建立一个迷你游戏,其中两个怪物相互战斗(对手和玩家)。当回合开始时,这些怪物应该战斗,并且它们的生命值降低1、2、3、4或5。

我正在使用Math.random随机分配给每个怪物造成的伤害。

运行程序并开始回合时,如何减少每个怪物的健康点?

到目前为止,这是我的代码(Monster.java文件):

import java.util.Random;

public class Monster {
    // Monster properties
    private String name;
    private int health;
    private int damage;

    // Random damage points that vary from 1 to 5
    int randomDamagePoints = (int)(Math.random() * 1 + 5);

    // Constructor
    public Monster(String name, int health, int damage) {
        this.name = "Monster";
        this.health = 50;
        this.damage = 2;
    }

    // Opponent attacks Monster 1 - Player
    public void AttackPlayer(Monster player) {
        while(health > 0) {
            // Part I need help with
        }
    }

    // Player attacks Monster 2 - Opponent
    public void AttackOpponent(Monster opponent) {
        while(health > 0) {
            // Part I need help with
        }
    }
}


谢谢您的帮助!

最佳答案

似乎您正在尝试确定谁会在两种情况下彼此造成1到5的伤害时获胜。

为此,您可以使用以下方法:

import java.util.Random;

public class Monster {
  // Monster properties
  private String name;
  public int health; //public so that Monsters hitting each other can manipulate health.
  private int damage;

  public int getRandomDamage() {
    return (int)(Math.random() * 5 + 1);
  }

  public void Fight(Monster opponent) {
    while (this.health > 0 && opponent.health > 0) {
      opponent.health -= this.getRandomDamage();
      this.health -= opponent.getRandomDamage();
    }
    if (opponent.health>this.health) {
      System.out.println(this.name + " lost!");
    } else {
      System.out.println(opponent.name + " lost!");
    }
  }

}


希望这可以帮助!

09-27 06:56