Ask coding questions

← Back to all posts
Using a random variable in C++
LoveFromSkyy

I'm working on the first level of my game and I want to know how I can make the monster use a random attack on the player AND use the correct number of damage. Here is the data that I wrote for this part (I'm not including the whole code because the rest is useless):

Tell me if you need more of the code to answer this. Please help me with this.

Answered by 19wintersp [earned 5 cycles]
View Answer
Voters
LoveFromSkyy
Comments
hotnewtop
19wintersp

Do you want to pick a random attack? You can generate a random number using rand from cstdlib, and use that to choose. Here's a function which generates a random integer from min to max inclusive:

LoveFromSkyy

Thank you! How can I implement this into my code? I looked stuff like this up but I don't want a random number, I'm looking for a random variable like

@19wintersp

19wintersp

@LoveFromSkyy You could store those as an array rather than giving them names, or if you prefer to use these predefined names:

Strongly recommend the array though.

LoveFromSkyy

Okay, I'll try, I suck at arrays

@19wintersp

19wintersp

@LoveFromSkyy Here's how I might implement it:

Baconman321

@19wintersp Doesn't the random integer have to be seeded?
I ran into a problem seeding an integer inside a loop due to it most of the time being seeded with time (which doesn't change fast enough for loops).

19wintersp

@Baconman321 Not too sure, I think srand does, but using rand seems fine.

Baconman321

@19wintersp Ah, yes. I remember now...
Yeah, I was thinking "hmmm, that command doesn't seem like the ones I used".

LoveFromSkyy

I made the Arrays for attacks and attack damage. How do I pick a random attack to be used?
@19wintersp

19wintersp

@LoveFromSkyy Assuming you've added the code from my first comment, you can select a random element from the array:

so for the attacks array, with a length of 3: