Tuesday, July 14, 2009

C++ text game problem?

i need to know how to make my text game so that if the player gets the action word wrong, the program doesn't just quit out, heres a section of my code





cout%26lt;%26lt;"\nHow about you do some exploring around the ship? maybe you'll find\nsomething of intrest! try using simple words to move around the ship\nsuch as 'climb', 'walk', 'go back', 'open', or 'pickup'. There is a crows nest high above you, with a ladder that leads all the way up.";


getline (cin, str_action);


if (str_action=="climb"||str_action=="climb up"||str_action=="go up ladder"||str_action=="climb up ladder"||str_action=="go to crows nest"){


cout%26lt;%26lt;"\nYou climb up the 132 foot ladder to finally reach the top!.....bla bla bla.";





if the player doesn't type 'climb' or any of the other valid action words the program shuts down. how can i fix this?

C++ text game problem?
put it in a loop that why it will continue to ask the question untill a correct answer is enter try using do -while statement then a series of if else statements example:





do


{


cout%26lt;%26lt;"\n Please enter a selection";


while(str_action != "climb" || "go up ladder" .....bla bla





if(str_action == "climb)


{


statement


}


else if (str_action == "go up ladder")


{


statement


}


.


.


.


.


.


.


etc
Reply:Ooh, a text adventure. The 1st game that I made over 20 years ago was a text adventure.





Well, I suppose you keep track of the player's location as a number right? So, you just need to create a conditional statement.


In your code, you would have something like this:


if (location==1 %26amp;%26amp; str_action != "climb")


{


// player was at room location 1 and chose a different verb


// exit program or whatever


}


if (str_action=="climb" %26amp;%26amp; location==1)


{


// climb up whatever if the verb is 'climb' and you are in the correct room where you can climb something (I omitted the extra processing for the proper noun)


}


(if you're not keeping track of the player's location in your program, then omit the 'location==1 %26amp;%26amp;' part in the IF statement above.)





P.S.


There's actually a better way to design your program.


Keep an array of verbs and a separate array of nouns. You also use a variable to keep track of which room the player is in. (The rooms are actually in an array.)


When a user types in something, you first process the verb and if it is a movement command, then check to see if the player can move in that direction (depending on location #). If the verb is something else, then check the noun. Each room has it's own set of IF statements to determine if the user can do something special that pertains to that room, such as 'look trees.' If there are trees there, then you would do something, otherwise you write out something like, 'I can't do that here', or 'I don't see any %26lt;noun user typed%26gt;.'


No comments:

Post a Comment