The code works fine for the first choice I make, but, no matter what I end up choosing for my second choice, I always get the following error:
Traceback (most recent call last):
File “C:/Users/JAV/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Cyoa.py”, line 111, in
File “C:/Users/JAV/AppData/Roaming/JetBrains/PyCharmCE2020.1/scratches/Cyoa.py”, line 30, in traverse
AttributeError: ‘str’ object has no attribute ‘story_piece’
I think it has something to do with the way I wrote the traverse method, but at this point, I’m pulling my hair out and would be profoundly grateful for any help anyone can provide.
'''Data Structures Project: Using a binary tree to make a choose your own adventure game''' ###### Use a tree data structure to keep track of the different paths a user can choose in their story. class TreeNode: def __init__(self, story_piece): self.story_piece = story_piece # Keep track of player choices self.choices =  #Each child node is a distinct path taken by the user def add_child(self,node): self.choices.append(node) def traverse(self): story_node = self print(story_node.story_piece) while len(story_node.choices) > 0: road_taken = input("Choose 1 or 2 ") if road_taken not in ["1", "2"]: print("Invalid selection, please try again.") else: chosen_index = int(road_taken) # adjusts index so they are 0 and 1 chosen_index -= 1 chosen_child = story_node.choices[chosen_index] print(chosen_child.story_piece) story_node = chosen_child ###### # VARIABLES FOR TREE story_root = TreeNode(""" You are in a forest clearing. There is a path to the left. A bear emerges from the trees and roars! Do you: 1 ) Roar back! 2 ) Run to the left... """) choice_a = TreeNode(""" The bear is startled and runs away. Do you: 1 ) Shout 'Sorry bear!' 2 ) Yell 'Hooray!' """) choice_a_1 = """ The bear returns and tells you it's been a rough week. After making peace with a talking bear, he shows you the way out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """ choice_a_2 = """ The bear returns and tells you that bullying is not okay before leaving you alone in the wilderness. YOU REMAIN LOST. """ choice_b = TreeNode(""" You come across a clearing full of flowers. The bear follows you and asks 'what gives?' Do you: 1 ) Gasp 'A talking bear!' 2 ) Explain that the bear scared you. """) choice_b_1 = """ The bear returns and tells you that bullying is not okay before leaving you alone in the wilderness. YOU REMAIN LOST. """ choice_b_2 = """ The bear understands and apologizes for startling you. Your new friend shows you a path leading out of the forest. YOU HAVE ESCAPED THE WILDERNESS. """ story_root.add_child(choice_a) story_root.add_child(choice_b) choice_a.add_child(choice_a_1) choice_a.add_child(choice_a_2) choice_b.add_child(choice_b_1) choice_b.add_child(choice_b_2) ###### user_choice = input("What is your name? ") # print(user_choice) ###### # TESTING AREA ###### print('Once upon a time...') story_root.traverse()