AttributeError: 'int'对象没有属性'directions
我更新了代码,让它看起来和我电脑上的一模一样。
我正在开发一个简单的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'
>>>
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
我对 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
1
问题出在这里...
if(item == " North" or " north"):
这种方式来测试条件是不对的。
你需要做的是
if (item == " North") or (item == " north"):
还要看看其他地方,你使用“或”来检查条件的地方。
0
我看到你有两个主要的bug,还有一些不是bug但也不好的地方,可能还有更多我没注意到的问题。下面是主要的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]
有四行代码都是这样写的。每一行都选了同一个directions
元素。它们不应该这样;每一行应该选择不同的方向。