AttributeError:' int'对象没有属性'指示'

时间:2014-03-14 00:41:02

标签: python

我已经更新了代码,使其与我的机器完全一样。

我一直在开发一个简单的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:\Users\Spencer\Documents\Python\Game.py", line 25, in <module>
    currentRoom = currentRoom.directions[0]
AttributeError: 'int' object has no attribute 'directions'
>>> 

Game模块

# 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模块

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

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

3 个答案:

答案 0 :(得分:1)

问题出在这里......

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

这是测试条件的错误方法。

您需要做的是

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

使用&#34;或&#34;查看您正在检查条件的其他地方。

答案 1 :(得分:0)

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

问题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元素。他们不应该这样做;他们应该走向不同的方向。

答案 2 :(得分:0)

我已将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