Quantcast
Channel: GameDev.net
Viewing all articles
Browse latest Browse all 17825

Random Number Generator

$
0
0
I'm running to some issues with a random number generator that I am trying to create to test what type of attack an enemy will use (weapon or magic) and whether or not they land a hit with the attack. What I want it to do is generate a random number number for the type of attack, then generate a separate random number for if the hit lands or not. What actually happens is it is generating a different number each iteration, but the same number for each item. So for instance, if the random number is a 6, both attack type and if it hit is a 6, if it's a 7 both are 7, etc. I'm almost certain the issue is within how I'm using time in conjunction with this, but everything else I've found hasn't been helpful. I've tried doing one function, but had the same issue and switched to two functions in the hopes that would help, but it didn't and now I'm not quite sure what to try next. Here is the code I have so far: // Example program #include <iostream> #include <string> #include <stdlib.h> #include <ctime> using namespace std; int getRandAttack(); int getRandHit(); int main() { int randomAttack; int randomHit; randomAttack = getRandAttack(); cout<<randomAttack<<endl; //used to ensure same number isn't given every time //decides what happens based on what number was given if (randomAttack <= 5) { cout<<"Enemy used a weapon!"<<endl; }else if (randomAttack > 5) { cout<<"Enemy used magic!"<<endl; } randomHit = getRandHit(); cout<<randomHit<<endl; //used to ensure same number isn't given every time //decides what happens based on what number was given if (randomHit <= 5) { cout<<"The attack missed!"; }else if (randomHit > 5) { cout<<"The attack hit!"; } } //gets random number to determine enemy attack type int getRandAttack () { int random; srand (time(NULL)); random = rand() % 10 + 1; return random; } //gets random number to determine if enemy attack lands a hit int getRandHit () { int random; srand (time(NULL)); random = rand() % 10 + 1; return random; } I know there is an easier way to do this that involves classes, but the online compiler I'm messing around with right now doesn't seem to support extra files, so I'm making functions work instead. Any help and lead in the right direction would be greatly appreciated.

Viewing all articles
Browse latest Browse all 17825

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>