2012-01-24 2 views
-1

보드에 임의의 테트리스 모양을 그리는 python 프로그램을 작성하려고합니다. 다음은 내 코드입니다 :무작위 테트리스 모양

def __init__(self, win): 
    self.board = Board(win, self.BOARD_WIDTH, self.BOARD_HEIGHT) 
    self.win = win 
    self.delay = 1000 

    self.current_shape = self.create_new_shape() 

    # Draw the current_shape oan the board 
    self.current_shape = Board.draw_shape(the_shape) 

def create_new_shape(self): 
    ''' Return value: type: Shape 

     Create a random new shape that is centered 
     at y = 0 and x = int(self.BOARD_WIDTH/2) 
     return the shape 
    ''' 

    y = 0 
    x = int(self.BOARD_WIDTH/2) 
    self.shapes = [O_shape, 
        T_shape, 
        L_shape, 
        J_shape, 
        Z_shape, 
        S_shape, 
        I_shape] 

    the_shape = random.choice(self.shapes) 
    return the_shape 

내 문제에있는 "self.current_shape = Board.draw_shape (the_shape) 그것은 the_shape 정의하지만 내가 create_new_shape에 정의 생각하지 않습니다 말한다

답변

1

the_shape을.. 전화 할 때는 create_new_shape 기능에 로컬 이름은 함수가 종료 한 번 범위에서 떨어진다.

5
당신이 한

하지만 변수 the_shape 그 기능의 범위에 대해 로컬입니다. create_new_shape() 당신은 필드에 결과를 저장 sha를 참조 할 때 사용해야한다. pe :

self.current_shape = self.create_new_shape() 

# Draw the current_shape oan the board 
self.current_shape = Board.draw_shape(self.current_shape) 
0

두 가지 문제가 있습니다. 첫 번째는 다른 사람들이 지적한 범위 문제입니다. 다른 문제는 모양을 인스턴스화하지 않는다는 것입니다. 클래스에 대한 참조를 반환합니다. 먼저 도형을 인스턴스화합니다.

y = 0 
x = int(self.BOARD_WIDTH/2) 
self.shapes = [O_shape, 
       T_shape, 
       L_shape, 
       J_shape, 
       Z_shape, 
       S_shape, 
       I_shape] 

the_shape = random.choice(self.shapes) 
return the_shape(Point(x, y)) 

이제 모양이 적절한 시작점으로 인스턴스화됩니다. 다음으로 범위.

self.current_shape = self.create_new_shape() 

# Draw the current_shape oan the board 
self.board.draw_shape(self.current_shape) 

동일한 개체 (여기 게시판)의 데이터 조각을 참조 할 때 자체를 통해 데이터에 액세스해야합니다. . 그래서 우리는 칠판에 접근하여 그릴 모양을 말하고 싶습니다. 우리는 self.board에 의해 다음, 우리는 draw_shape 메서드에 추가합니다. 마지막으로 무엇을 그려야할지 알려줄 필요가 있습니다. the_shape은 범위를 벗어났습니다. create_new_shape 메서드에만 존재합니다. 이 메서드는 모양을 반환하지만, self.current_shape에 할당했습니다. 따라서 클래스 내부의 모든 모양을 다시 참조하려면 self.current_shape을 사용하십시오.