冒险故事图元组错误

问题描述 投票:0回答:1

我正在开展一个处理图表的实践项目。这是一款互动冒险游戏,用户输入选择并试图逃离荒野,然而,现在,当用户选择第一个提示的答案时,它会结束游戏,而不提示其他选择,从而使游戏持续更长时间,并且对用户来说更有意义。我使用元组来表示分支叙述,但我认为我使用错误。如果有人有时间查看此内容或有任何提示,我将不胜感激!!

这是创建故事树的根节点并启动游戏的 main.py 文件:

# Import TreeNode class and story_data from respective files
from story_data import story_data
from tree_node import TreeNode

def main():
    # Create the root node with the initial story piece
    story_root = TreeNode(story_data.story_piece, story_data.choices)

    # Print the initial story piece
    print("Once upon a time...")
    print(story_root.story_piece)

    # Begin the story traversal
    story_root.traverse()

# Check if this file is being run directly
if __name__ == "__main__":
    main()

这是代表故事树中节点的tree_node.py 文件:

class TreeNode:
    def __init__(self, story_piece, choices=None):
        self.story_piece = story_piece
        self.choices = choices or []

    def add_child(self, node):
        self.choices.append(node)

    def traverse(self):
        story_node = self
        while story_node.choices:
            choice = input("Enter 1 or 2 to continue the story: ")
            if choice not in ["1", "2"]:
                print("Invalid choice. Try again.")
            else:
                chosen_index = int(choice) - 1
                chosen_child = story_node.choices[chosen_index]
                print(chosen_child.story_piece)
                story_node = chosen_child

最后,这是定义故事结构的story_data.py 文件,创建树节点的实例来表示故事的不同部分:

from tree_node import TreeNode

story_data = 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_1 = TreeNode("""
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 = TreeNode("""
The bear returns and tells you that bullying is not okay before 
leaving you alone
in the wilderness.

YOU REMAIN LOST.
""")

choice_b_1 = TreeNode("""
The bear is unamused. After smelling the flowers, it turns 
around and leaves you alone.

YOU REMAIN LOST.
"""
)
choice_b_2 = TreeNode("""
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_data.add_child(choice_a_1)
story_data.add_child(choice_a_2)
story_data.add_child(choice_b_1)
story_data.add_child(choice_b_2)
python tuples graph-theory
1个回答
0
投票

正如评论中所说,

您仅向

story_data
添加了子节点。其他节点都不包含子节点,因此
while
循环退出。

为了提供更多细节,在执行

story_data.py

中的代码后

TreeNode
看起来像这样:

story_data.story_piece = "You are in a forest [..]"
story_data.choices = [choice_a_1, choice_a_2, choice_b_1, choice_b_2]

choice_a_1.story_piece = "The bear [..] tells you it's been a rough week [..]"
choice_a_1.choices = []

choice_a_2.story_piece = "The bear [..] tells you bully is not okay [..]"
choice_a_2.choices = []

choice_b_1.story_piece = "The bear is unamused [..]"
choice_b_1.choices = []

choice_b_2.story_piece = "The bear understands [..]"
choice_b_2.choices = []

while
循环的第一次迭代有效,因为条件
story_node.choices
找到了一个非空
list
,其计算结果为
True

当用户从

["1","2"]
中选择一个值时,他们实际上是在
choice_a_1
choice_a_2
之间进行选择。对于这两者,
story_node.choices
将是一个空的
list
,其计算结果为
False
,结束循环而不进行第二次迭代。

如果您不确定 python 程序的行为,您可以随时使用 VS Code/PyCharm/等 IDE 进行调试,或者在您怀疑问题所在的位置之前和/或之后使用

print
语句。

因此,在这种情况下,尝试运行具有以下更改的程序:

class TreeNode:
    # .. (unchanged)

    def traverse(self):
        story_node = self
        while story_node.choices:
            print("story_node.choices before choice " + story_node.choices) #  <-- added
            choice = input("Enter 1 or 2 to continue the story: ")
            if choice not in ["1", "2"]:
                print("Invalid choice. Try again.")
            else:
                chosen_index = int(choice) - 1
                chosen_child = story_node.choices[chosen_index]
                print(chosen_child.story_piece)
                story_node = chosen_child
                print("story_node.choices after choice " + story_node.choices) #  <-- added

    def __repr__(self):          # <-- added
        return self.story_piece  # <-- added

这样你会得到类似以下的输出:

Once upon a time...
1) [..]
2) [..]

story_node.choices before choice  [
The bear returns and tells you it's been a rough week. [..]
, 
The bear returns and tells you that bullying is not okay [..]
, 
The bear is unamused. [..]
, 
The bear understands and apologizes [..]
]
Enter 1 or 2 to continue the story: 1

The bear returns and tells you it's been a rough week. [..]

story_node.choices after choice  []

注意输出的最后一行是空的

list
,这可能会导致您提到的行为。


顺便说一句,

["1", "2"]
在语义上是
list
tuple
看起来像
("1", "2")
,但在这种情况下行为是相同的,因为没有赋值或散列,您可以阅读一些有关差异的内容

您可能还想查看

visitor
设计模式,因为它可以让您将每个
TreeNode
的处理移到对象本身之外,因为在第一次迭代之后,
traverse
方法没有理由在里面
TreeNode
。示例此处

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.