如何为游戏生成随机伤害点? -Java

问题描述 投票:0回答:2

我正在建立一个迷你游戏,其中两个怪物(对手和玩家)相互战斗。当回合开始时,怪兽应该战斗,它们的生命值降低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
        }
    }
}

谢谢您的帮助!

java random
2个回答
1
投票

首先,关于您的伤害公式:

int randomDamagePoints = (int)(Math.random() * 1 + 5);

这将始终导致5。您想要

int randomDamagePoints = (int)(Math.random() * 5 + 1);

如果要使损害不断变化,应将其置于其自身的功能或攻击功能中。另外,我建议您仅使用一个带有损坏参数的attack函数,将其命名为attackMe。然后只需从生命值中减去伤害,例如

public boolean attackMe(int damage) {
  health -= damage;
  return hitPoints > 0;
}

0
投票

[您似乎正在尝试确定谁会在两种情况下彼此造成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!");
    }
  } 

}

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.