我对python编程相当陌生,我想尝试一个简单的文本冒险游戏,但我立即遇到了一个障碍
class userInterface:
def __init__(self, roomID, roomDesc, dirDesc, itemDesc):
self.roomID = roomID
self.roomDesc = roomDesc
self.dirDesc = dirDesc
self.itemDesc = itemDesc
def displayRoom(self): #Displays the room description
print(self.roomDesc)
def displayDir(self): #Displays available directions
L1 = self.dirDesc.keys()
L2 = ""
for i in L1:
L2 += str(i) + " "
print("You can go: " + L2)
def displayItems(self): #Displays any items of interest
print("Interesting items: " + str(self.itemDesc))
def displayAll(self, num): #Displays all of the above
num.displayRoom()
num.displayDir()
num.displayItems()
def playerMovement(self): #Allows the player to change rooms based on the cardinal directions
if input( "--> " ) in self.dirDesc.keys():
letsago = "ID" + str(self.dirDesc.values())
self.displayAll(letsago)
else:
print("Sorry, you can't go there mate.")
ID1 = userInterface(1, "This is a very small and empty room.", {"N": 2}, "There is nothing here.")
ID2 = userInterface(2, "This is another room.", {"W": 3}, ["knife", "butter"])
ID3 = userInterface(3, "This is the third room. GET OVER HERE", {}, ["rocket launcher"])
ID1.displayAll(ID1)
ID1.playerMovement()
这是我的代码,出于某种原因会抛出该错误:
Traceback (most recent call last):
File "D:/Python34/Text Adventure/framework.py", line 42, in <module>
ID1.playerMovement()
File "D:/Python34/Text Adventure/framework.py", line 30, in playerMovement
self.displayAll(fuckthis)
File "D:/Python34/Text Adventure/framework.py", line 23, in displayAll
num.displayRoom()
AttributeError: 'str' object has no attribute 'displayRoom'
我在互联网上和python文档中搜索过我到底做错了什么,我不知道。如果我用ID2或ID3来代替self.displayAll(letsago),它工作得很好,但这是毫无意义的,因为玩家无法控制他想去哪里,所以我猜尝试将ID与字典中的数字连接是有问题的,但我不知道该怎么做,也不知道如何解决这个问题
问题出在
playerMovement
方法中。您正在创建文件室变量的字符串名称(ID1
,ID2
,ID3
):然而,您创建的只是一个
str
。这不是变量。另外,我不认为它在做你认为它在做的事情:如果确实需要以这种方式查找变量,可以使用
eval
函数:或者
globals
函数:然而,我强烈建议你重新思考你的课程。您的
userInterface
类本质上是一个Room
。它不应该处理玩家的移动。这应该在另一个类中,可能是GameManager
之类的相关问题 更多 >
编程相关推荐