How to make my program read previous lines of code?

Long version: Hello to anyone who reads this. First off just let me say that this is my first time making a topic on these forums so sorry if I do something wrong while asking you this. Now back to the topic. I am a beginner at c++ and I am trying to make a text based story-type game. The problem is I have done quite a good amount so far but I really need to know how I can get my program to go back to a different line of code, or anything that is similar like that. For example I give the player 2 options. He can either follow the road to the truck stop, or go down the road that leads to nothing (you can see this in lines 10 and 11.) Now I have it so if he goes down the truck stop road he finds the truck stop and if he goes down the other road then he dies (shown in lines 12-25.) I have come to realize that this is a really bad way to code the game since I will have to create multiple outcomes within each if/else statements. This can work in some cases but what I was hoping to do is to have the program say "You will die if you go down that path" or something like that, and then it would bring up the 2 choices again so you can pick again. I now hope you can see why I said "Make the program read a previous line of code" in my title because that's what it seems like I would have to do for it to work. So now hopefully one of you guys can help me with this, thanks.

Short version: I need to know how to get the program go back to lines of codes when you make a decision.

Backround: I am using codeblocks and the function First() which is the code I have given to you is where you go from a decision you make in the main() function.

P.S. This is a semi-related question. Is there a way to make a certain key like 1 or 2 go back to the top of the main(). Like restarting a game you can put in the number 1 and it would go to the top of main() and restart the game.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  int First()
{
    cout << "You start walking and you finally make it out of the woods." << endl;
    cout << "You are now on a road. To the right you see a sign that says \n'Bubba's Truck Stop.' To the left you see nothing but road. " << endl;
    cout << "What do you do?" << endl;
    cout << "\n1. Follow the road that leads to the truck stop" << endl;
    cout << "2. Follow the road that leads to nothing" << endl;
    cin >> Choice;
    if ( Choice == 1)
    {
        cout << "\nAfter a little walking you find the truck stop. It is a very run down place with an autoshop, diner, burning barrels, and a broken down car." << endl;
        
    }
    else
    {
        cout << "The road you took is too big for you to reach civilization, you die of hunger \nand dehydration," << endl;

        return 0;
    }

}.
First, you are absolutely corrected about how this won't scale very well. At all.

The best way I can think of to do this is to prefer thinking of code in terms of data. So, you might have an array of data, containing messages for what to do and a number saying what way allows you to survive. For example:
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
57
58
59
60
61
62
63
64
#include <iostream>
#include <string>

// A data type for a single 'page' in your story.
struct StoryPage {
    // the flavour text at the start of your choices.
    std::string message;

    // list of options - this can be as many as you like. I'll assume that
    // there are always only two options to choose from.
    std::string option1;
    std::string option2;

    // message for when you lose.
    std::string loss;

    // flag to determine which one is correct.
    int choice;
};

int main() {
    const int numPages = 2; // change this when you add more pages
    StoryPage story[2] = {
        {
            "You start walking and you finally make it out of the woods.\n"
            "You are now on a road. To the right you see a sign that says\n"
            "'Bubba's Truck Stop.' To the left you see nothing but road.",

            "Follow the road that leads to the truck stop.",
            "Follow the road that leads to nothing.",

            "The road you took is too big for you to reach civilisation, you die of\n"
            "hunger and dehydration.",

            1
        },
        {
            "(Second Page story background)",
            "(Second page option 1)",
            "(Second page option 2)",
            "(Second page death message)",
            2 // lets just say option 2 is correct
        }
    };

    for (int i = 0; i < numPages; ++i) {
        std::cout << story[i].message << std::endl;
        std::cout << "What do you do?\n" << std::endl;
        std::cout << "1. " << story[i].option1 << std::endl;
        std::cout << "2. " << story[i].option2 << std::endl;

        int choice;
        std::cin >> choice;

        // if you choose wrong
        if (choice != story[i].choice) {
            std::cout << story[i].loss << std::endl;
            i -= 1; // go back one step and repeat this
        } 
        // otherwise go on to the next difficulty.
    }
    std::cout << "You won!" << std::endl;
    return 0;
}


As you can see, you can just keep on adding to that massive array at the start of your program, and everything should fit in neatly. If you like, you can even add more choices, without much difficulty (maybe see if a certain choice message exists and don't print it if it doesn't). You could even store all of this in a file and load it when you run your program (what I'd do, personally), though that would be a bit harder. Using std::vector instead of a C-style array would make that a lot easier, though.

It also gets a bit more complicated if your story stops being linear - rather than storing which option doesn't kill you, you should store what choice will go to what 'page', and change 'i' to based on that. Hope you enjoy looking through this, and that it gives you an idea of what to do - I spent far too much time typing of all of this up...

EDIT:
Like this, its also really easy to restart the game. Say, check if they enter -1 or 0 or something, and then just set i to -1. That way it will loop back to 0 and you get to start the game from the beginning again!

Also, if you are wondering what I did with the strings, "Hello" "World" becomes just "HelloWorld". Its a useful trick for breaking up long strings onto multiple lines. Make sure that you have the comma at the end of each entry, though.
Last edited on
@OP, If you ever will consider creating a branching story, such adventures are easy to represent as directed graph: nodes are places, outgoing edges are choices. For example this is the text quest editor from Space Rangers: http://puu.sh/fboKH/5e8abe5458.png
Thanks for the help you just said, although there are some things I didn't understand. Like the story[i] commands and the lines 46,56, and 58. Sorry but I just don't truly understand what your trying to tell me so if you can try to dumb it down then that would be great.
Sure. I'll just assume you know very little, and go from there.

On line 23, we defined that we are storing our pages for the story as an array, basically a list of values. We defined on line 22 how big that array would be, as in how many story pages it would have. For our example, we have 2 story pages, so its an array with size 2 (2 elements).

However, we don't just want an array with those elements, we want to be able to actually access them. In a 10 element array, the indices of the list go 0,1,2...9. Note that they start from 0. This means, to access the first page in the story we would type in story[0], and for the second page in the story we would type story[1].

On line 46 we have a for loop. In this, we declare a variable i, a condition for looping (i < numPages) and a rule for modifying the value (++i, or add one to i). What this does is it repeats the code inside the braces, while i fulfils the condition that we have set. At the end of the loop, it follows the rule for modifying the value (in this case, add one to i). This means that, unless you modify i, the loop will run 2 times, once with i=0 and once with i=1 - then it will go on to line 62.

On line 56 we have an if statement, which I'm sure you are familiar with. The condition we have is if choice != story[i].choice, then lose. In other words, if the player of your story-game thing make a choice that ISN'T the one you said was right, then you run the 'you were wrong' part of the code (lines 57-78).

Line 57, as I'm sure you worked out, just prints the message for when you lose. Line 58 is a bit more complicated. Remember what I said about the for loop simply being repeating based on i, and i is incremented at the end of each loop? What we do on line 58 is subtract 1 from i, which means that after i is incremented again we are back to the same number page we were on before.

Having read all this, I'm sure you can now work out what story[i] means, but I'll say anyway. Basically, it is a way to access the 'ith' page of our story.

Hope this helps!
Thank you for explaining this. I now understand most of it and i'm getting started to write my program again, thanks again.
Topic archived. No new replies allowed.