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

Python地牢爬行游戏移动系统随机报KeyError: None错误如何解决

报错根因

你的KeyError: None报错是因为玩家移动时读取的目标房间名称为None,无法从world字典中找到对应的房间条目,问题确实出在你怀疑的findExits()和findRoom()关联逻辑上,核心有两个错误点:

  1. 坐标顺序不匹配:你在makeRoomsForLevel()中存储房间坐标时,rooms数组的索引顺序和Room类coords属性的存储顺序相反,导致findExits()判断相邻房间位置时出现错位,部分存在的房间无法被findRoom()匹配到,返回None。
  2. 无返回值校验:findExits()没有校验findRoom()的返回值,直接把None存入了房间的出口字典中,玩家触发对应方向的移动时就会报错。
    因为地牢是随机生成的,只有部分生成结果会触发坐标错位问题,所以报错是随机出现的。
修复方案

1. 修正findExits()的坐标顺序

把findExits()中所有判断rooms数组值的位置,交换x和y的索引顺序,修改后代码如下:

def findExits():
  for i in range(len(world)):
      x, y = world[f"room{i+1}"].coords
      exits = dict()
      
      #east
      if rooms[y, x+1] == 1:
          exits["E"] = findRoom(x+1, y)
      
      #south
      if rooms[y+1, x] == 1:
          exits["S"] = findRoom(x, y+1)
      
      #west
      if rooms[y, x-1] == 1:
          exits["W"] = findRoom(x-1, y)
      
      #north
      if rooms[y-1, x] == 1:
          exits["N"] = findRoom(x, y-1)
          
      world[f"room{i+1}"].exits = exits

2. 增加返回值校验

给每个出口赋值逻辑加非空判断,避免None被存入出口字典:

def findExits():
  for i in range(len(world)):
      x, y = world[f"room{i+1}"].coords
      exits = dict()
      
      #east
      if rooms[y, x+1] == 1:
          room_name = findRoom(x+1, y)
          if room_name:
              exits["E"] = room_name
      
      #south
      if rooms[y+1, x] == 1:
          room_name = findRoom(x, y+1)
          if room_name:
              exits["S"] = room_name
      
      #west
      if rooms[y, x-1] == 1:
          room_name = findRoom(x-1, y)
          if room_name:
              exits["W"] = room_name
      
      #north
      if rooms[y-1, x] == 1:
          room_name = findRoom(x, y-1)
          if room_name:
              exits["N"] = room_name
          
      world[f"room{i+1}"].exits = exits

3. 可选:增加移动兜底校验

可以在Player.Move()方法中再加一层校验,避免漏网的异常值:

def Move(self, direction):
    if direction not in self.room.exits:
      print("Cannot Move In That Direction!")
      return
    newRoomName = self.room.exits[direction]
    if newRoomName not in world:
        print("Cannot Move In That Direction!")
        return
    self.previousRoom = world[self.room.name]
    print("Moving to", newRoomName)
    self.room = world[newRoomName]

内容的提问来源于stack exchange,提问作者Jedidiah Blitz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:54:07