因此,我正在通过创建Pokemon战斗模拟器(使用JOption窗格)来练习基本Java。

我使用以下方法将Pokemon的攻击值设为最大值,为简单起见,将min设置为0。

public static int randomDamage(int min, int max) {
    int range = (max - min) + 1;
    int randomDamage =  (int)(Math.random() * range) + min;
    return randomDamage;


这就是我一直在调用该方法的地方。

public static void battle(Pokemon pokemon1, Pokemon pokemon2) {
    showMessageDialog(null, pokemon2.name + "'s stats are: \n Health: "
            + pokemon2.health + "\n Attack: " + pokemon2.attack + "\n Speed: " + pokemon2.speed);
    showMessageDialog(null, pokemon1.name + " begins the fight against " + pokemon2.name);
    do {

        if (pokemon1.health > 0 && pokemon2.health > 0) {
            showMessageDialog(null, pokemon1.name + " attacks " + pokemon2.name);
            pokemon2.health = pokemon2.health - randomDamage(0,pokemon1.attack);
            showMessageDialog(null, pokemon1.name + " does " + pokemon1.randomDamage + " damage to " +
                    pokemon2.name + " and " + pokemon2.name + " has " + pokemon2.health + " left.");
        }

        if (pokemon1.health > 0 && pokemon2.health > 0) {
            showMessageDialog(null, pokemon2.name + " attacks " + pokemon1.name);
            pokemon1.health = pokemon1.health - pokemon2.attack;
            showMessageDialog(null, pokemon2.name + " does " + pokemon2.attack + " damage to " +
                    pokemon1.name + " and " + pokemon1.name + " has " + pokemon1.health + " left.");
        }


    } while (pokemon1.health > 0 && pokemon2.health > 0);
    if (pokemon1.health < 1) showMessageDialog(null, pokemon1.name + " has been reduced to 0 health. "
            + pokemon1.name + " has lost the fight.");
    else showMessageDialog(null, pokemon2.name + " has been reduced to 0 health. "
            + pokemon2.name + " has lost the fight.");

}


损坏似乎是随机的,但总是会说“ Charmander对Rattata造成0点伤害,Rattata还剩x点生命值”。

是否可以从运行状况中减去randomDamage值,然后在我的JOption窗口中显示该值?

谢谢!

最佳答案

如果要多次使用它,则需要先存储randomDamage的返回值(即在pokemonX.randomDamage中)。

示例(假设Pokemon具有一个int randomDamage成员):

pokemon1.randomDamage = randomDamage(0,pokemon1.attack);
pokemon2.health = pokemon2.health - pokemon1.randomDamage;
showMessageDialog(null, pokemon1.name + " does " + pokemon1.randomDamage + " damage to " + pokemon2.name + " and " + pokemon2.name + " has " + pokemon2.health + " left.");

关于java - 将随机数的返回值存储为局部变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43546560/

10-11 18:44