Let's create a function to begin telling our story. Remember we have to define functions before we can use them.
We need code that allows us to always access the node (part of the story) we are on and not lose our place in the adventure.
story_node = self
Print will create a message for this part of the story on the screen for the player to read.
Printsends text, variables, and other objects to the screen for the user to see. The syntax for print is print().
The while loop will keep checking the story for choices as long as the game is running. If there are no more choices because we reached a dead end then the loop will end. How do we check for choices? The len function stands for length and will check to see how long our choices list is. If you can go left or right, then your list has 2 items. If you reached a dead end and the story ends, the list has 0 items indicating you've reached a dead end and the loop should stop. !=0 is the syntax that means the length of the story_node.choices list does not equal 0 (yes, there are there items in your list so the loop can continue and the story can go on).
The variable answer will gives the player an option to type 0 or 1 to move the story along. Since we will use numbers as the means for advancing the story, we have to translate our responses into those. int stands for integer and turns our story options into numbers. Instead of "Do you go left or right?" it becomes "Do you pick 0 or 1?" where 0 is left and 1 is right.
If the answer is choice 0 or choice 1 then we can go to the next tree node scenario.
answer =int(input("Enter 0 or 1 to continue the story:"))if answer ==0or answer ==1:
choice = story_node.choices[answer]
We have to now update and add our new options to the story_node.choices list. Remember how Python lists are ordered? The placement in the list is called an index and the first item actually has a starting position of 0, not 1. Weird, right? Let's take a look at that shopping list again.
An indexis the position of an item in a list. The first item in a list has an index = 0, the second = 1 and so on.
self.shopping = [apple, banana, milk, bread]
Apple is the first item in the list so it has an index of 0. Banana is the second item. What comes after 0? 1! That's the index for banana. Any idea what the index is for bread? ...It's 3! Our newest story choices will be added to the end of our list.
Now we need to update the story based on our choice and turn the page. Think of it like moving a bookmark.
story_node = choice
Let's create a message that tells the player what the next part of the story says once we make a choice.
If the player makes a choice you didn't provide, like typing 382 or kitty then our program should create an in-game message saying that's not an option. This is where the else comes in since 0 or 1 wasn't entered.
else:print("Invalid answer! Try again!")
Accessing this project requires a login, please enter your credentials below!