Qwisatz
Qwisatz

Reputation: 77

How to manipulate and randomise a variable in a while loop condition?

I have a while loop with a condition inside called card1Hp and it is a new instance variable defined at the top of the class called Game.

    public int card1Hp = 100;
    public int card2Hp = 80;
    public int card3Hp = 90;
    public int card4Hp = 70;

and there's a method in the class with a while loop:

 while(card1Hp > 0)

I have a method in the class that generates a specified random number for me where I can go:

someVar= Game.getRandIntBetween(1,5);

and it generates randVar = 1 or 2 or 3 or 4 or 5. Is there any way I can put this into my while loop condition. Basically I want it to be:

while(card1Hp > 0)

replaced with some kind of way like this

 while(card(randVar)Hp > 0)

I know that isn't the way to write it in java but that's the effect I want to try and generate the random number I want in my cardHp. What's a good way to achieve this? I plan for hundreds of cardhp variables in my game as well to randomize.

Upvotes: 1

Views: 85

Answers (2)

Sweeper
Sweeper

Reputation: 274480

First, put your hp values into an array:

int[] hps = {card1Hp, card2Hp, card3Hp, card4Hp};

If you want to use a different hp value each time the while loop condition is checked, you can do this:

while (hps[Game.getRandIntBetween(0, hps.length - 1)] > 0)

Otherwise, do this:

int randIndex = Game.getRandIntBetween(0, hps.length - 1);
while (hps[randIndex] > 0)

Upvotes: 0

Elliott Frisch
Elliott Frisch

Reputation: 201527

I would use an array. Something like static int[] hpValues = { 100, 80, 90, 70 };, then get a random number x between 0 (inclusive) and hpValues.length (exclusive) and your random "cardhp" is int randCardHP = hpValues[x]; - and that might look like

int x = Game.getRandIntBetween(1, hpValues.length) - 1;

Upvotes: 1

Related Questions