Python 属性错误:';int';对象没有属性';方向'; 我已经更新了代码,使其与我的机器上的代码完全相同。

Python 属性错误:';int';对象没有属性';方向'; 我已经更新了代码,使其与我的机器上的代码完全相同。,python,Python,我一直在开发一个简单的Python文本冒险引擎,但遇到了一个问题。如果你能解决我的问题,或者有更有效的方法来编码/构造一个方法或类,请告诉我!我对这类事情还不熟悉,任何建议都很好!此外,格式化可能不会达到标准,但嘿,我试过了! 好的,我的项目有两个模块,分别是Game和Map。第一个模块,Game,“解析”用户输入并更改玩家所在的房间。第二个模块,Map,概述了一个Room类,该类包含一个构造函数和一些与方向、出口等相关的函数。我还没有解决搬进一个不存在的房间的问题,我确信我的代码相当糟糕,但这

我一直在开发一个简单的Python文本冒险引擎,但遇到了一个问题。如果你能解决我的问题,或者有更有效的方法来编码/构造一个方法或类,请告诉我!我对这类事情还不熟悉,任何建议都很好!此外,格式化可能不会达到标准,但嘿,我试过了! 好的,我的项目有两个模块,分别是
Game
Map
。第一个模块,
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:\Users\Spencer\Documents\Python\Game.py", line 25, in <module>
    currentRoom = currentRoom.directions[0]
AttributeError: 'int' object has no attribute 'directions'
>>> 

Map
模块

# 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.")

        
# 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])


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

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

问题1:
不是那样工作的。这不会使用四个可能的参数尝试
命令.partition
。相反

"Go" or "go" or "Take" or "take"
计算结果为“Go”,调用变为

partition = command.partition("Go")
此问题在您使用
的每个地方都会出现。最大的影响是当它发生在
if
条件下时,它会导致始终采用
if

问题2: 共有四行文字说明了这一点。每个选择相同的
方向
元素。他们不应该这样做;他们应该朝着不同的方向走。

问题就在这里

if(item == " North" or " north"):
这是一种不正确的测试条件的方法

你需要做的是

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

在其他地方,你也可以使用“或”检查条件

我修改了
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"]
然后


在某种程度上,您已经为currentRoom分配了一个
int
值。@HughBothwell我也计算了这么多,但我不知道在哪里分配了
int
值!我认为主模块中的命令
currentRoom=Map.currentRoom
不正确。也更改它
currentRoom=Map.Room(name,description)
@Remolten更改了它并得到了
TypeError:\uuu init\uuuuuuu()缺少2个必需的位置参数:“name”和“description”
,而不是在
Map
模块中设置
currentRoom=storageclock
。您还需要通过执行
currentRoom=Map.room(名称、描述)
并填写所需的参数来创建房间。输入您的
storageclock
参数,然后再试一次。@user3387584:确实如此。这实际上应该是
Map
模块中的
namererror
,因此实际代码可能与我们显示的代码不同。我已经更新了代码。您建议我以不同的方式使用
分区
吗?@user3188407:Just
split
字符串
command.split()
将提供一个列表,其中第一个元素是
'Go'
或用户使用的任何第一个单词,第二个元素是
'North'
'East'
,或用户输入的任何方向。使用
是否可以接受?现在,在我的修改版本中,我有一个
分区1
和一个
分区2
,每个分区都有自己的
操作
:P@user3188407当前位置我不知道你想说的是什么,你的修改版本看起来像什么。通常,
x或y
仅用于测试
x
y
中是否至少有一个为真。这是一个布尔逻辑运算符;如果你像英语连词一样阅读它,它不会做你可能认为它会做的大部分事情。哇。那有点高级了,哈哈。然而,我可以很好地理解它。非常感谢。
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