Sign in to follow this  
zeltrax5

help with a code

Recommended Posts

Hey, I recently made text game but can't get this statement to work properly: void Attack() { cout<<"You have attacked with your sword"<<endl; cout<<"Your sword has been destroyed during the hit, your target had killed you"; || cout<<"Your have slain the enemy with your sword"; }; it's a simple function I located in a class... when the game gets to the point where the function has to run it ALWAYS prints "Your sword has been destroyed...", while I want it to randomly select one of these quotes. Can any1 help please?

Share this post


Link to post
Share on other sites
You can't use the OR operator like that '||'. I am surprised that compiles. Instead you can do something like this.

This will create a random number between 1 - 3, depending on what it is it will output one of your sentences.



#include <time.h>
void Attack() {
srand ( time(NULL) );
int randomNum = rand() % 3 + 1;
if(randomNum == 1){
cout<<"You have attacked with your sword"<<endl;
}else(randomNum == 2){
cout<<"Your sword has been destroyed during the hit, your target had killed you";
}else{
cout<<"Your have slain the enemy with your sword";
}
};



Share this post


Link to post
Share on other sites
How i would go about it...

[source lang = "c++"]'

void Attack() {
int choice = rand() % 3; //include #include <stdlib.h>

switch(choice){
case 0:
cout<<"You have attacked with your sword"<<endl;
break;
case 1:
cout<<"Your sword has been destroyed during the hit, your target had killed you";
break;
case 2:
cout<<"Your have slain the enemy with your sword";
break;
}
};



Share this post


Link to post
Share on other sites
Considering that Attack() will most likely get called several times, it's not a good idea to call srand() in the function to seed the PRNG. Call it once at the start of the application.

You might also think about the probabilities associated with each event, i.e. if it makes much sense to think of every event to be equally probable.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this