Alice Alice - 2 months ago 6
C++ Question

In a text based adventure game, how do I prevent long confusing conditional code?

I am creating a text-based, choose your own adventure game in C++.

In this game, there will be lots of possibilities on where you choose to go, what you choose to do etc.

My question is, how do I prevent this from becoming extremely confusing.

Example:

Lets say at one point in the game you can be asked whether to go to the forest or the desert. If you choose desert, thats a COMPLETELY different story line from the forest.

So how would I prevent from my code looking like this.

if (player goes to the desert)advice? {
/*Whole story line of the desert*/
else if (player goes to the forest) {
/*Whole story line of the forest */


Inside of these story lines there would be more conditionals like that, and more elaborate story lines, so is there any way that I can write the code for one story line in a separate file, then just run that file for that conditional? Anyways I can do that separately instead of writing everything out inside of the conditionals? If I did that the code would quickly become long and confusing to look at/edit.

I was thinking about doing headers and making functions inside of the headers that write out the story line, so I would just have to type out the function, but if I did that, then I couldnt access the global variables in the game such as
playerName
or
playerRace
etc.

Any and all suggestions are appreciated. I'm new to C++ so please forgive me if I've missed something painstakingly obvious.

Answer

Probably a class based solution. The question is quote broad, so not quite sure which design patterns would fit. However, a sample class may be CrossroadsDesicision that'll export options ["Go to desert", "Go to city", ...] and have a method apply that should receive an options from the array and return the relevant decision class for the next step

Edit: The base class should contain:

  • possibleDecisions - an array of possible decisions (You could use an option class here, composed of a name (string or enum - you should use templating here) and a description)

  • apply - a function receiving a decision, acting on it, and returning the next decision