属性错误:"int"对象没有属性"方向"



我已经更新了代码,使它看起来和我的机器上完全一样。

我一直在开发一个简单的Python文本冒险引擎,我遇到了一个问题。如果你能解决我的问题或有一个更有效的方式来编码/结构一个方法或类,请告诉我!我对这类事情很陌生,任何建议都会很好!此外,格式可能达不到标准,但嘿,我试过了!

好的,所以我的项目有两个模块,标题为GameMap。第一个模块Game"解析";用户输入并改变玩家所处的房间。第二个模块Map概述了一个Room类,它包含一个构造函数和一些与方向、出口等相关的函数。我还没有解决搬到一个不存在的房间的问题,我确信我的代码相当糟糕,但这里是:


错误消息

>>> ================================ RESTART ================================
>>> 
You are in a small, cramped space.
It is cold and dark. There is a door to your North.
 > Go North
Traceback (most recent call last):
  File "C:UsersSpencerDocumentsPythonGame.py", line 25, in <module>
    currentRoom = currentRoom.directions[0]
AttributeError: 'int' object has no attribute 'directions'
>>> 

Game module

# It is the main engine for PyrPG
import Map
currentRoom = Map.currentRoom
def updateGame():
    currentRoom.displayName()
def invalidCommand():
    print("Invalid command. Try again.")
while(True):
    updateGame()
    command = input(" > ")
    print()
    
    partition = command.partition("Go" or "go" or "Take" or "take")
    action = partition[1]
    item = partition[2]
    if(action == "Go" or "go"):
        if(item == " North" or " north"):
            currentRoom = currentRoom.directions[0]
        if(item == " East" or " east"):
            currentRoom = currentRoom.directions[0]
        if(item == " South" or " south"):
            currentRoom = currentRoom.directions[0]
        if(item == " West" or " west"):
            currentRoom = currentRoom.directions[0]
    else:
        print("Invalid command.")
        

Map module

# It handles rooms.
class Room:
    rmCount = 0
    directions = [0, 0, 0, 0]
    
    def __init__(self, name, description):
        # Name and description
        self.name = name
        self.description = description
        # Directions
        self.directions = None
        self.canNorth = False
        self.canWest = False
        self.canSouth = False
        self.canEast = False
        # Increase room count
        Room.rmCount += 1
        
    def displayName(self):
        print(self.name)
        print(self.description)
        print()
    def displayDirections(self, directions):
        # Check directions, modify booleans
        if(self.directions[0] != 0):
            self.canNorth = True
            gNorth = "North"
        else:
            gNorth = ""
        if(self.directions[1] != 0):
            self.canEast = True
            gEast = "East"
        else:
            gEast = ""
        if(self.directions[2] != 0):
            self.canSouth = True
            gSouth = "South"
        else:
            gSouth = ""
        if(self.directions[3] != 0):
            self.canWest = True
            gWest = "West"
        else:
            gWest = ""
        print("Directions:", gNorth, gEast, gSouth, gWest)
    def setDirections(self, directions):
        self.directions = directions
    def displayInfo():
        displayName()
        displayDirections()
introRoom = Room("Welcome to the Cave.", "To start the game, type "Go North"")
storageCloset = Room("You are in a small, cramped space.", "It is cold and dark. There is a door to your North.")
mainOffice = Room("the main office.", "It is cold and empty.")
currentRoom = storageCloset
introRoom.setDirections([storageCloset, 0, 0, 0])
storageCloset.setDirections([mainOffice, 0, 0, 0])
mainOffice.setDirections([0, 0, storageCloset, 0])

再说一次,如果你看到什么可怕的东西,请告诉我!这是我自己写的第一个项目,没有任何指示。谢谢!

问题就在这里…

if(item == " North" or " north"):

这是一个不正确的测试条件的方法。

你需要做的是

if (item == " North") or (item == " north"):

看看你在其他地方使用"或"来检查条件。

我可以看到两个主要的错误,一堆没有错误但仍然很糟糕的部分,可能还有更多我没有注意到的问题。以下是主要的bug。

问题1:

partition = command.partition("Go" or "go" or "Take" or "take")

or不是这样工作的。这不会用四个可能的参数尝试command.partition。相反,

"Go" or "go" or "Take" or "take"

求值为"Go",调用变为

partition = command.partition("Go")

每次使用or时都会出现这个问题。最大的影响是当它发生在if条件下时,它会导致if总是被占用。

问题2:

currentRoom = currentRoom.directions[0]

有4行都是这么说的。每个都选择相同的directions元素。他们不应该这么做;

我已经修改了Map.py,使其更灵活:

class CaseInsensitiveDict(dict):
    def __getitem__(self, key):
        return dict.__getitem__(self, key.lower())
    def __setitem__(self, key, value):
        return dict.__setitem__(self, key.lower(), value)
# room index
all_rooms = CaseInsensitiveDict()
class Room:
    def __init__(self, name, description):
        all_rooms[name] = self   # add to index
        self.name = name
        self.description = description
        self.dirs = CaseInsensitiveDict()
    def add_dir(self, dir, room_name):
        self.dirs[dir] = all_rooms[room_name]
    @property
    def directions(self):
        return "From here you can go: " + ", ".join(sorted(self.dirs.keys())) + "n"
    def go(self, dir):
        try:
            next_room = self.dirs[dir]
            print(next_room)
            return next_room
        except KeyError:
            print("You can't go {} from here.n".format(dir))
            return self
    def __str__(self):
        return (
            self.name + "n" +
            self.description + "n"
        )
def make_link(dir_a, room_a, dir_b, room_b):
    if dir_b:
        all_rooms[room_a].add_dir(dir_b, room_b)
    if dir_a:
        all_rooms[room_b].add_dir(dir_a, room_a)

可以像

一样使用
Room("Small closet", "You are in a small, cramped space. It is cold and dark. There is a door to your North.")
Room("Dusty office", "This must be the main office. It is still cold and dark. There is a door marked 'Supplies' to the South, and a set of double doors to the East.")
Room("Foyer", "Blah blah")
make_link("North", "Dusty office", "South", "Small closet")
make_link("East", "Foyer", "West", "Dusty office")
here = all_rooms["small closet"]
然后

>>> print(here)
Small closet
You are in a small, cramped space. It is cold and dark. There is a door to your North.
>>> here = here.go("north")
Dusty office
This must be the main office. It is still cold and dark. There is a door marked 'Supplies' to the South, and a set of double doors to the East.
>>> here = here.go("north")
You can't go north from here.
>>> print(here.directions)
From here you can go: east, south
>>> here = here.go("east")
Foyer
Blah blah

最新更新