rand() and srand() text adventure combat system

May 28, 2016 at 2:45am
I learned about rand() and srand() today and was excited because I was trying to figure out a way to do a combat rolling system for a text adventure that I've been working on.

Everything is working mostly the way I want it to but there's this extra number that the code is outputting that I do not want the user to see. I'm 100% positive it has to do with my for statement in the attack function, I'm just not sure how to keep the attacks between 0 and 10 if I use a '0' at

for(i = 1; i <= 1: i++)
^^

Also, I've been messing around with adding an output for if an attack = 9+,
then a critical strike message is printed. Same if the attack = 0, a "miss" message is printed. If nobody gets to this part it is fine I really just want the extra integer to go away

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
 #include "stdafx.h"
#include <iostream>
#include <string>
#include <iomanip>
#include <cstdlib>
#include <ctime>
#include <stdlib.h>
#include <stdio.h> 



using namespace std;

int attack(int i) {
	srand( time( NULL ));
	for (i = 1; i <= 1; ++i) {
		cout << 1 + (rand() % 10) << endl;
		return (rand() % 10);
	}
	
}


int main()
{
	int k = 0;
	cout << "Bash<1> Cleave<2> Gash<3> Stomp<4>" << endl;
	cin >> k;
	
	if (k == 1) {
		cout << "The warrior bashes the enemy with his weapon!" << endl;
	}

	if (k == 2) {
		cout << "Cleave attack!" << endl;
	}

	if (k == 3) {
		cout << "Gash attack!" << endl;
	}

	if (k == 4) {
		cout << "Stomp attack!" << endl;
	}

	while (k > 4) {
		cout << "That is not an attack!" << endl;
		cin >> k;
	}
	cout << "The warrior attacks for " << attack(k) << " HP" << endl;
	system("pause");
    
    return 0;
}

May 28, 2016 at 3:13am
Hi,

Some questions:

What is the purpose of a for loop? How is that related to the start and end conditions?
What is the relationship between the function parameter (variable i), and it's use in the for loop?
What happens when the return statement is encountered?

Hope this helps :+)
May 28, 2016 at 10:17pm
Thank you!

After messing around with it then pondering your questions, I realized that I don't even need the for loop to generate the random number... Or the cout line.
Last edited on May 28, 2016 at 10:17pm
Topic archived. No new replies allowed.