rand() and srand() ques.

For my text game, my battle function looks like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int Battle(){
	int userDamage;
	int monsterDamage;
	int userHealth;
	int monsterHealth;
	srand ( time(NULL) );
	userHealth = 15;
	userDamage = rand() % 9;
	monsterDamage = rand() % 7;
	monsterHealth = 10;
	while(monsterHealth > 0 == true){
		cout << "You are attacked by a monster, will you attack or run?" << endl;
	getline(cin, userAnswer);
	cin.clear();
	if(userAnswer == "attack"){
		monsterHealth = monsterHealth - userDamage;
		cout << "You hit for " << " " << monsterHealth << endl;
		cout << "The monsters health is now " << monsterHealth << "." << endl;

	}
	}
return 0;
}


I only have the user's attack coded for now.
The problem is that the monsterHealth int wont properly become the monsterHealth - userDamage. It's just replaced by whatever userDamage was.
I need it to do the damage, then monsterHealth will be replace by the new monsterHealth, where it will properly repeat the battle fuction with the diminishing monster health until monsterHealth > 0 becomes false, where it will return to where the game left off.
Also, is there a way for the damage to be only positive, because I even had it become a negative once.
Your code is working how you expect.

The problem is you're printing monsterHealth when you meant to print userDamage. This is why it looks like they're the same.

Right here:

 
cout << "You hit for " << " " << monsterHealth << endl;  // <- should be userDamage, not monsterHealth 



Also:

-) The way you're generating random numbers, they will always be positive. Don't worry about that.

-) Don't call srand() here. Only call it once at the very start of your program (like the first thing you do in main). Don't put it anywhere else in your program.

-) If you want the user to deal different amounts of damage each time they attack, you'll have to put the userDamage assignment inside your loop.
Oh, I see now, thank you! I'll pop those in and see how it works.
Topic archived. No new replies allowed.