Keyboard Guide
class TreeNode: def __init__(self, story_piece): self.story_piece = story_piece self.choices = [] def add_choices(self, choice_a, choice_b): self.choices.append(choice_a) self.choices.append(choice_b) def tell_story(self): story_node = self print(story_node.story_piece) while len(story_node.choices) !=0: answer = int(input("Enter 0 or 1 to continue the story: ")) if answer == 0 or answer == 1: choice = story_node.choices[answer] story_node = choice print(story_node.story_piece) else: print("Invalid answer! Try again!") story_root = TreeNode("You awake in an empty room. There is a phone booth in the middle. \nDo you: \n 0 ) Investigate the phone booth. \n 1 ) Leave it alone.\n") current_node = story_root choice_a = TreeNode("You enter the phone booth and look around. You see a button that says 1980 and a button that says 3000. \nDo you: \n 0 ) Press 1980. \n 1 ) Press 3000.\n") choice_b = TreeNode("You decide to leave the phone booth alone. You live out the rest of your life in boredom.\n") current_node.add_choices(choice_a, choice_b) play_again = "y" while play_again == "y": story_root.tell_story() play_again = input("Would you like to play again [y]/[n]?: ").lower()
Let’s add the choices we just typed out into our choices list by using the add_choices() function.
current_node.add_choices(choice_a, choice_b)
Before we continue adding to our story, let’s create a means for sending the player back to the beginning of the story if they come across a dead end.
We’ll do this by using a while loop. Our game will consistently check for if the player reaches a dead end and will then ask the player if they want to continue from the beginning.
While loops continue to endlessly run until it doesn’t meet a certain condition. In this case, it will run as long as the player types y for yes.
play_again = "y" while play_again == "y": story_root.tell_story() play_again = input("Would you like to play again [y]/[n]?: ").lower()
To make sure the player input is consistent with the code you’ve written, we need to make sure they both match. If you coded y for yes but the player types Y an error will occur because the computer thinks y and Y are different answers. Fix this by adding .lower() to this function.
Adding .lower() to the input() function will convert whatever the player types into lowercase. This would turn YES, YeS, yES into yes. We will just use y for this project.
Notice how we used == instead of = to see if the play_again variable matches y.
Use == as a comparison tool to see if two things are similar. Using = is typically used to define things such as variables and are not used for comparisons.