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

Python Turtle游戏中键存在却触发KeyError的问题排查

解决Turtle地牢逃脱游戏的KeyError问题

问题描述

开发Python Turtle地牢逃脱游戏时,海龟坐标用于匹配房间描述,但触发KeyError:错误显示键(13.00,87.00)不存在,但字典中已定义(13,87)。

相关代码

import turtle
from inspect import getframeinfo, stack


class Story:

    def __init__(self, location, qdescription):
        self.location = location
        self.qdescription = qdescription

        self.wn = turtle.Screen()  # Get a reference to the window
        self.turt = turtle.Turtle()  # Create our favorite turtle
        self.turtwrite = turtle.Turtle()  # Creates another turtle specifically for writing

        # These lines "wire up" keypresses to the handlers we've defined.
        self.wn.onkey(self.h1, "Up")
        self.wn.onkey(self.h2, "Left")
        self.wn.onkey(self.h3, "Right")
        self.wn.onkey(self.h4, "Down")
        self.wn.onkey(self.h5, "q")

        # Now we need to tell the window to start listening for events,
        # If any of the keys that we're monitoring is pressed, its
        # handler will be called.
        self.wn.listen()
        self.wn.mainloop()

    def h1(self):
        up = [(-37, 62), (-62, 62), (-37, 87), (-37, 112), (-37, 137), (-37, 162), (-37, 187), (-37, 212), (-37, 237), (-12, 62), (13, 62), (-12, 37), (13, 87), (38, 62), (13, 112), (38, 37), (88, 62), (63, 37)]

        roomdict = {(13, 87): 'maze5'}

        roomdesc = {'maze5': 'You see a tunnel that is lit with a single torch burning a green flame. There are 2 ways to go: [North and South].'}

        if self.turt.pos() in up:
            self.turt.setheading(90)
            self.turt.forward(25)

            self.location = roomdict[self.turt.pos()]
            self.qdescription = roomdesc[self.location]

错误信息

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
    return self.func(*args)
  File "C:\Users\M\AppData\Local\Programs\Python\Python310\lib\turtle.py", line 685, in eventfun
    fun()
  h1
    self.location = roomdict[self.turt.pos()]
KeyError: (13.00,87.00)

问题原因与解决方法

原因

turtle.pos()方法返回的是浮点数类型的元组(比如(13.00, 87.00)),而你在字典roomdict中定义的键是整数类型的元组((13, 87))。Python中整数和浮点数属于不同数据类型,因此这两个元组无法匹配,触发KeyError。

解决方法

有三种实用方案可以解决这个问题:

  1. 将海龟坐标转换为整数元组
    使用self.turt.pos()时,把每个坐标值转为整数,确保和字典键类型一致:

    current_pos = tuple(int(coord) for coord in self.turt.pos())
    self.location = roomdict[current_pos]
    
  2. 修改字典键为浮点数元组
    直接将roomdict中的键改为浮点数格式,和turtle.pos()返回的类型匹配:

    roomdict = {(13.0, 87.0): 'maze5'}
    
  3. 使用round函数处理坐标
    如果担心移动时出现浮点精度误差(比如坐标变成13.0000001),可以用round函数保留固定小数位:

    current_pos = tuple(round(coord, 2) for coord in self.turt.pos())
    # 同时确保字典键也是保留两位小数的浮点数元组
    roomdict = {(13.00, 87.00): 'maze5'}
    

推荐第一种方案,因为你的关卡坐标都是整数,转成整数元组最直接,也能避免潜在的浮点精度问题。


内容的提问来源于stack exchange,提问作者Easton Mason

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 03:25:18