我第一次使用 Python 时遇到了一些问题。我正在开发一个小游戏,比如迷宫。我创建了一个类 Map
,当我实例化它时,它就可以工作。当我尝试实例化同一个类两次时,我遇到了一些问题。
这是代码:
from random import randint
class Map:
"""Class that generates map"""
width = 0
height = 0
map = list()
dictLine = dict()
def __init__(self, width, height):
"""Constructor takes width and height in input"""
self.width = width
self.height = height
for i in range(0, self.width * self.height):
self.map.append('.')
self.__defineMap()
self.__defineEntrance()
def __defineMap(self):
"""Defines Map in a dict"""
index = 0
for i in range(0,self.height):
self.dictLine[index] = self.map[index:index + self.width]
index = index + self.width
def printMap(self):
"""Function that prints Wumpus World Map"""
for i in range(0, self.width * self.height):
if(i % self.width == 0):
print()
print(self.map[i], end=' ')
print()
def __defineEntrance(self):
"""Random entrance defined at game start"""
state = False
while state is False:
randomEntrance = randint(0,(self.width * self.height)-1)
self.map[-self.width:]
if randomEntrance in range(0,self.width):
#if entrance is at the first line
self.map[randomEntrance] = 'E'
return True
elif randomEntrance % self.width == 0:
#if entrance is on the left side
self.map[randomEntrance] = 'E'
return True
for key in self.dictLine.keys():
#da vedere
if key + self.width - 1 == randomEntrance:
self.map[randomEntrance] = 'E'
return True
l = list()
for key in self.dictLine.keys():
l.append(key)
l.sort()
l.reverse()
if randomEntrance in range(l[0], l[0] + self.width):
self.map[randomEntrance] = 'E'
return True
return False
def reset(self):
self.__init__(self.width, self.height)
这是结果:
>>> map = Map(6,6)
>>> map.printMap()
. . . E . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
>>> map2 = Map(7,7)
>>> map2.printMap()
. . . E . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . E . . .
我该如何解决这个问题?谢谢大家!
最佳答案
map
是一个类属性(在该类的所有实例之间共享),而不是实例属性。
如果这不是您想要的行为,请将其更改为实例属性 - 即,将 map = list()
部分移动到 __init__
内部。您可能希望对 width
、height
和 dictLine
执行相同的操作。
关于python - python 对象实例化失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26995639/