vendredi 21 avril 2017

Storing the return value of a random number as a local variable?

So I'm practicing basic Java by creating a Pokemon battle simulator (using JOption Panes).

I'm using the following method to take the Pokemon's attack value as the max, and set a min of 0 for simplicity.

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

Here's where I've been calling the method.

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.");

}

The damage appears to be randomized as I expected, but it will always say "Charmander does 0 damage to Rattata and Rattata has x health left".

Is it possible to subtract the randomDamage value from the health and then display that value in my JOption window?

Thank you!




Aucun commentaire:

Enregistrer un commentaire