You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python3文字冒险游戏坐标触发事件未正常显示问题求助

问题解决方法

你需要按优先级调整以下两处核心问题即可让事件正常触发:

1. 修正坐标判断的语法逻辑错误

你当前写的if xpos == 2 and ypos == 2 or 4:不符合Python的判断规则,这个表达式实际等价于(xpos == 2 and ypos ==2) or 4,而整数4的布尔值恒为True,会导致整个判断条件逻辑完全错误,达不到你想要的「x坐标为2且y坐标为2或4时触发事件」的效果。
修改为正确的判断写法即可:

# 写法1:符合原逻辑的规范写法
if xpos == 2 and (ypos == 2 or ypos ==4):
# 写法2:更简洁的等价写法
if xpos ==2 and ypos in (2,4):

2. 修正事件函数的调用时机

你现在是在定义完event_1之后直接调用了一次,仅会在程序启动时执行一次事件检测。而文字冒险游戏的事件触发逻辑应该是每次玩家移动、坐标更新之后,再执行事件检测,你需要把event_1()的调用放到坐标更新的逻辑后面,比如控制玩家移动的代码块末尾,每次移动完成都执行一遍事件检测。

可选优化:替换递归处理非法输入的逻辑

你当前用return event_1()处理用户输入错误的写法,用户多次输入错误时会触发递归深度超限报错,替换为while循环更稳妥:

def event_1():
    global xpos, ypos
    if xpos ==2 and ypos in (2,4):
        typingPrint("""You've come across a bush of berries! They look safe enough..
       Would you like to:
       A- Eat one right now
       B- Store it in your inventory for later
       C- leave it as it is""")
        while True:
            event_1_choice = typingInput("<<< ")
            if event_1_choice in answer_A:
                typingPrint("You've eaten a berry and gained 20 HP!!")
                break
            elif event_1_choice in answer_B:
                typingPrint("You've stored the berry for later use")
                inventory.append("Berry")
                break
            elif event_1_choice in answer_C:
                typingPrint("You decide to leave the berry as it is, better to be safe then sorry!!")
                break
            else:
                print("Sorry? do you want the berries or not?")

内容的提问来源于stack exchange,提问作者shaji Fai

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 01:45:04