please help me finish this code

I'm sorry because I don't konw how to make my in code in an box like others, it's my first to log in this forum.
here's my problem:
I wrote a RPG CMD program, the attack function can let the player run or attack.
but i want to change this to multiple enemy(player can meet several enemy), I don't know how, I just konw to change the parameter as an array, anyone can help me ? (Player and Monster are classes)

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
bool Player::attack(Monster & monster) {
	int selection;
	cout << "1) Attack, 2) Run: ";
	cin >> selection;
	cout << endl;
	switch(selection) {
	case 1 :
		cout << "You attack an " << monster.getName()
			<< " with a " << mWeapon.mName << endl;
		if(Random(0, 20) < mAccuracy) {
			int damage = Random(mWeapon.mDamageRange);
			int totalDamage = damage - monster.getArmor();
			if(totalDamage <= 0) {
				cout << "Your attack failed to penetrate "
						<< "the armor." << endl;
			} else {
				cout << "You attack for " << totalDamage
						<< " damage!" << endl;
				//substract from monster's hitpoints
				monster.takeDamage(totalDamage);		// player verus monster
			}
		} else {
			cout << "You miss!" << endl;
		}
		cout << endl;
		break;
	case 2 :
		// 25% chance of being able to run
		int roll = Random(1, 4);
		if(roll == 1) {
			cout << "You run away!" << endl;
			return true;	// <-- Return out the funcion
		} else {
			cout << "You could not escape!" << endl;
			break;
		}
	}
	return false;
}
Last edited on
For the code tags:

[code]Put your code between these things[/code]

As for your problem, you can pass an array to a function in the form of a pointer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

void func( Monster* monsters, int nummonsters )
{
  // can treat 'monsters' as an array:
  monsters[0].whatever = whatever;
  player.whatever += monsters[1].whatever;
}

int main()
{
  Monster anarrayofmonsters[10];

  func( anarrayofmonsters, 10 );  // give it the array, and tell it how many elements it as
}
thanks a lot for .....
if i want to declare like bool Player::attack(Monster monster[]), what should I do?
I don't know how to treat several monsters.
bool Player::attack(Monster monster[]), what should I do?


You should do exactly that. In a parameter list Monster* monster and Monster monster[] are identical:

1
2
3
4
5
6
7
8
9
10
bool Player::attack(Monster monster[], int numberofmonsters)
{
  // ...
}

// then when you call it:

Monster my_array_of_monsters[10];  // 10 monsters

player.attack( my_array_of_monsters, 10 ); // give it the array, and tell it how many monsters are in the array 
Topic archived. No new replies allowed.