|
| 1 | +###### |
| 2 | +# TREENODE CLASS |
| 3 | +###### |
| 4 | +class TreeNode: |
| 5 | + def __init__(self, story_piece): |
| 6 | + self.story_piece = story_piece |
| 7 | + self.choices = [] |
| 8 | + |
| 9 | + def add_child(self, node): |
| 10 | + self.choices.append(node) |
| 11 | + |
| 12 | + def traverse(self): |
| 13 | + story_node = self |
| 14 | + print(story_node.story_piece) |
| 15 | + while len(story_node.choices) > 0: |
| 16 | + choice = input("Enter 1 or 2 to continue the story: ") |
| 17 | + if choice not in ["1","2"]: |
| 18 | + print("Invalid, please enter a valid choice: 1 or 2: ") |
| 19 | + else: |
| 20 | + chosen_index = int(choice) |
| 21 | + chosen_index -= 1 |
| 22 | + chosen_child = story_node.choices[chosen_index] |
| 23 | + print(chosen_child.story_piece) |
| 24 | + story_node = chosen_child |
| 25 | +###### |
| 26 | +# VARIABLES FOR TREE |
| 27 | +###### |
| 28 | +story_root = TreeNode(""" |
| 29 | +You are in a forest clearing. There is a path to the left. |
| 30 | +A bear emerges from the trees and roars! |
| 31 | +Do you: |
| 32 | +1 ) Roar back! |
| 33 | +2 ) Run to the left... |
| 34 | +""") |
| 35 | +choice_a = TreeNode(""" |
| 36 | +The bear is startled and runs away. |
| 37 | +Do you: |
| 38 | +1 ) Shout 'Sorry bear!' |
| 39 | +2 ) Yell 'Hooray!' |
| 40 | +""") |
| 41 | +choice_b = TreeNode(""" |
| 42 | +You come across a clearing full of flowers. |
| 43 | +The bear follows you and asks 'what gives?' |
| 44 | +Do you: |
| 45 | +1 ) Gasp 'A talking bear!' |
| 46 | +2 ) Explain that the bear scared you. |
| 47 | +""") |
| 48 | +story_root.add_child(choice_a) |
| 49 | +story_root.add_child(choice_b) |
| 50 | +choice_a_1 = TreeNode(""" |
| 51 | +The bear returns and tells you it's been a rough week. After making peace with |
| 52 | +a talking bear, he shows you the way out of the forest. |
| 53 | + |
| 54 | +YOU HAVE ESCAPED THE WILDERNESS. |
| 55 | +""") |
| 56 | +choice_a_2 = TreeNode(""" |
| 57 | +The bear returns and tells you that bullying is not okay before leaving you alone |
| 58 | +in the wilderness. |
| 59 | + |
| 60 | +YOU REMAIN LOST. |
| 61 | +""") |
| 62 | +choice_a.add_child(choice_a_1) |
| 63 | +choice_a.add_child(choice_a_2) |
| 64 | +choice_b_1 = TreeNode(""" |
| 65 | +The bear is unamused. After smelling the flowers, it turns around and leaves you alone. |
| 66 | + |
| 67 | +YOU REMAIN LOST. |
| 68 | +""") |
| 69 | +choice_b_2 = TreeNode(""" |
| 70 | +The bear understands and apologizes for startling you. Your new friend shows you a |
| 71 | +path leading out of the forest. |
| 72 | + |
| 73 | +YOU HAVE ESCAPED THE WILDERNESS. |
| 74 | +""") |
| 75 | +choice_b.add_child(choice_b_1) |
| 76 | +choice_b.add_child(choice_b_2) |
| 77 | +###### |
| 78 | +# TESTING AREA |
| 79 | +###### |
| 80 | +print("Once upon a time...") |
| 81 | +story_root.traverse() |
0 commit comments