2014-11-18 6 views
1

파이썬에서 저의 첫 경험에 약간의 문제가 있습니다. 나는 미로 같은 작은 게임을하고있다. 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) 

이 결과 :

코드인가? 다들 감사 해요!

+1

클래스 인스턴스'''map''을 호출하면 내장 함수'''map()''이 덮어 쓸 것입니다. 함수 – wnnmaw

답변

0

글쎄, 우선 먼저. Max으로

는 모든 변수 클래스 속성 대신 그래서 당신은 하나 개의 인스턴스에서 변경이 다른 사람에 영향을 미칠 것입니다예 (심지어 당신이 만듭니다)로 만들어진 말했다. 해결 방법은 __init__으로 이동하는 것입니다.

또한 "예약 된"단어를 사용하지 마십시오. map은 내장으로 사용됩니다. 어쩌면 maze으로 변경하십시오.

코드를 빠르게 변경했습니다. 개선의 여지가 있지만 잘 처리 할 수 ​​있습니다.

from random import randint 


class Maze(object): 
    """Class that generates maze""" 

    def __init__(self, columns, rows): 
     """Constructor takes columns and rows in input""" 
     self.columns = columns 
     self.rows = rows 
     self.reset() 

    def reset(self): 
     # Building maze. 
     self.__maze_cell_mapping = [] 
     for i in xrange(self.columns): 
      for j in xrange(self.rows): 
       self.__maze_cell_mapping.append((i, j)) 

     # Defining entrance. 
     self.__entrance = None 
     self.__define_entrance() 

    def __define_entrance(self): 
     """Random entrance defined at game start""" 
     while self.__entrance is None: 
      cell_id = randint(0, len(self.__maze_cell_mapping)) 
      if self.__is_boundary(cell_id): 
       self.__entrance = self.__maze_cell_mapping[cell_id] 

    def __is_boundary(self, cell_id): 
     """ 
     :param int cell_id: 
      ID of the cell to check. 

     :rtype: bool 
     :returns: 
      ``True`` if given ``cell_id`` is at maze boundary. 
     """ 
     column, row = self.__maze_cell_mapping[cell_id] 
     if column == 0 or column == self.columns - 1: 
      return True 
     elif row == 0 or row == self.rows - 1: 
      return True 
     else: 
      return False 

    def print_maze(self): 
     """Function that prints Wumpus World Maze""" 
     result = [ 
      ['.'] * self.columns 
      for _i in xrange(self.rows) 
     ] 

     column, row = self.__entrance 
     result[column][row] = 'E' 

     for row in result: 
      print(' '.join(row)) 

희망이 있습니다.

+0

대단히 고마워 !!!이게 자바 같다고 생각 했어 .... 어쨌든 고맙다 !! – Altair

1

map은 인스턴스 속성이 아닌 클래스 속성 (클래스의 모든 인스턴스간에 공유 됨)입니다.

원하는 동작이 아니라면 인스턴스 속성이되도록 변경하십시오. 즉, map = list() 부분을 __init__으로 이동하십시오. width, heightdictLine과 같은 작업을 수행하는 것이 좋습니다.

+0

답장을 보내 주셔서 감사합니다. 생성자 내에서 map = list()를 이동하려고 시도했지만 새로운 문제가있었습니다. >>> map from import * >>> mappa = Map (5,5) Traceback (최근 호출 마지막) : 파일 파일에서 ""라인 1 "/ 사용자/마르코/데스크탑/wumpus 사 세계/map.py"__init__ self.map.append 라인 (16), ('.') AttributeError : ' Map '객체에는 속성'map '이 없습니다. – Altair

+0

당신의 traceback은 선언하기 전에'self.map'에 것을 추가하려고한다는 것을 나타냅니다 (진지하게, * 오류 메시지를 읽습니다 *). 정의가'__init__' 맨 꼭대기에 있는지 확인하십시오. –

+0

나는 시도했지만 좋은 소식이 없었다. ( – Altair

관련 문제