파이썬에서 저의 첫 경험에 약간의 문제가 있습니다. 나는 미로 같은 작은 게임을하고있다. Map
클래스를 만들면 인스턴스화 할 때 작동합니다. 같은 클래스에서 두 번 인스턴스를 만들려고 할 때 몇 가지 문제가있었습니다.파이썬 객체에서 인스턴스화가 실패합니다.
>>> map = Map(6,6)
>>> map.printMap()
. . . E . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
>>> map2 = Map(7,7)
>>> map2.printMap()
. . . E . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . . . . .
. . . E . . .
가 어떻게이 문제를 해결할 수 :
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()''이 덮어 쓸 것입니다. 함수 – wnnmaw