gurgy11
gurgy11

Reputation: 37

How To Get A Random Item From A Class In Java?

I've just started to learn Java, and I'm pretty new.

I am trying to create a very simple text based RPG game in Java.

I have created a class called "enemy". This class contains certain variables, such as a string for the enemy's name, integers for the enemy's health, damage, and so on. With this "enemy" class, I create specific enemies. For example, using the "enemy" class, I'll make a zombie enemy and assign certain values to the above mentioned variables.

What I would like to be able to do is to have a random enemy encounter. For example, lets say I have a zombie enemy, giant spider enemy, and an assassin enemy, each with values assigned to variables within the "enemy" class, I would like to have a random battle encounter. The zombie appear maybe 45% of the time, the spider 25% of the time, and the assassin, 30% of the time.

How can I do this or something similar? Any tutorials maybe?

Sorry if I'm not making much sense...

Upvotes: 1

Views: 412

Answers (2)

Michael
Michael

Reputation: 2773

This would be the general format for acheiving that (as in a uniform probability of selecting an Enemy):

Enemy[] enemies = new Enemies[10];
//fill in your array with a bunch of enemies
//...
//ahh, time for a battle encounter!
int randIndex = new Random().nextInt(enemies.length);
Enemy encounterEnemy = enemies[randIndex];
//now you can use encounterEnemy for the simulated battle

Note: the random element selection was taken from here

For different probabilities of Enemy selection

The idea is to create a random double in the range of 0-1, then based on different ranges within that, select/create an Enemy. In this case, an array would not make sense.

double randVal = Math.random();
Enemy encounterEnemy;
if (randVal < 0.25){
    encounterEnemy = createZombie();
}else{
    encounterEnemy = createGiantSpider();
}

In this case, there's a 25% probability of running into a zombie, and a 75% chance of running into a giant spider.

Upvotes: 5

Dici
Dici

Reputation: 25950

If you put your Enemy instances in a list, and have a separate sorted list to store the probabilies, you can do the following to pick one randomly:

// in real code you would have to build this list and check it is sorted in reverse order
// and that the total sum is 100
List<Double> probabilities = Arrays.asList(45, 30, 25);
List<Enemy> enemies = Arrays.asList(new Zombie(), new Spider(), new Assassin());

public static Enemy randomEnemy(List<Enemy> enemies, List<Double> probabilities) {
    double d = Math.random();
    double threshold = 0;

    for (int i = 0; i < probabilities.size(); i++) {
        threshold += probabilities.get(i) / 100;
        if (d < threshold) return enemies.get(i);
    }
    throw new IllegalArgumentException("Probabilities don't add up to 1. Total: " + threshold);
}

Upvotes: 0

Related Questions