2011-12-22 4 views
1

목표는 파이 게임 캔버스에 그리드를 만들고 x 및 y 좌표로 상자를 강조 표시하는 모듈을 만드는 것입니다.파이 게임 클래스 구조

다음은 간단한 사용 예입니다.

from grid import Grid 

g = Grid(100, 100, 10) # width and height in cells, cell width in pixels 
g.highlightBox(2, 2, (0, 255, 0)) # cell x and y, rgb color tuple 
g.clearGrid() 

여기는 제가 지금까지 가지고있는 코드입니다. 문제는, 윈도우를 열어두고 닫기 버튼을 기능시키기 위해 이벤트 루프가 있어야하지만, 다른 함수가 화면에 그릴 수 있도록해야합니다.

import pygame 
import sys 

class Grid: 
    colors = {"blue":(0, 0, 255), "red":(255, 0, 0), "green":(0, 255, 0), "black":(0, 0, 0), "white":(255, 255, 255)} 

    def __init__(self, width, height, cellSize, borderWidth=1): 
     self.cellSize = cellSize 
     self.borderWidth = borderWidth 
     self.width = width * (cellSize + borderWidth) 
     self.height = height * (cellSize + borderWidth) 
     self.screen = pygame.display.set_mode((self.width, self.height)) 

     running = True 
     while running: 
      event = pygame.event.poll() 
      if event.type == pygame.QUIT: 
       running = False 

    def clearGrid(self): 
     pass 

    def highlightBox(self, x, y, color): 
     xx = x * (self.cellSize + self.borderWidth) 
     yy = y * (self.cellSize + self.borderWidth) 
     pygame.draw.rect(self.screen, color, (xx, yy, self.cellSize, self.cellSize), 0) 

내가 처음 샘플을 실행

이 코드가 루프에 갇혀 루프가 완료 될 때까지 나를 highlightBox 기능을 실행할 수있게되지 않을 것입니다 (종료 버튼을 누르면).

답변

0

을 줄 것입니다 예를 들어 표면을 반환하거나, 모든 게임 루프

한 번 호출 할 것 get_surface 방법을 만들 수 라이브러리 및 파이프 multiprocessing. 그것은 약간 unpythonic 보인다 그러나 그것은이 프로젝트를 위해 작동 할 것이다.

import pygame 
import sys 
from multiprocessing import Process, Pipe 

class Grid: 
    colors = {"blue":(0, 0, 255), "red":(255, 0, 0), "green":(0, 255, 0), "black":(0, 0, 0), "white":(255, 255, 255)} 

    def __init__(self, width, height, cellSize, borderWidth=1): 
     self.cellSize = cellSize 
     self.borderWidth = borderWidth 
     self.width = width * (cellSize + borderWidth) 
     self.height = height * (cellSize + borderWidth) 

     #pygame.draw.rect(self.screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0) 
     self.parent_conn, self.child_conn = Pipe() 
     self.p = Process(target=self.mainLoop, args=(self.child_conn, self.width, self.height,)) 
     self.p.start() 

    def close(): 
     self.p.join() 

    def clearGrid(self): 
     pass 

    def highlightBox(self, x, y, color): 
     xx = x * (self.cellSize + self.borderWidth) 
     yy = y * (self.cellSize + self.borderWidth) 
     self.parent_conn.send(["box", color, xx, yy, self.cellSize, self.cellSize]) 

    def mainLoop(self, conn, width, height): 
     #make window 
     screen = pygame.display.set_mode((self.width, self.height)) 

     running = True 
     while running: 
      # is there data to read 
      if conn.poll(): 
       #read all data 
       todo = conn.recv() 
       print("Recived " + str(todo)) 

      #do the drawing 
      if todo[0] == "box": 
       print("drawing box") 
       pygame.draw.rect(screen, todo[1], (todo[2], todo[3], todo[4], todo[5]), 0) #color, x, y, width, height 
       todo = ["none"] 

      #draw to screen 
      pygame.display.flip() 

      #get events 
      event = pygame.event.poll() 
      if event.type == pygame.QUIT: 
       running = False 
1

처음에는 게임 루프를 초기화 함수 안에 넣지 않을 것입니다. 그것을위한 다른 장소를 찾으십시오. 이 문제를 해결하려면 이벤트 처리에 대한 코드 옆에, 당신은 게임 루프에서 실행하고자하는 코드를 넣어 :

running = True 
while running: 
    event = pygame.event.poll() 
    if event.type == pygame.QUIT: 
     running = False 

    # Print your screen in here 
    # Also do any other stuff that you consider appropriate 
+0

사실, init 함수에서 루프가 발생하는 것이 가장 좋지 않을 수 있습니다. 결코 적게는,이 여전히 외부 함수에서 화면에 쓰기의 문제를 해결하지 않습니다. – giodamelio

+1

@giodamelio 귀하는 귀하의 문제가 무엇인지 명확하게 밝히지 않았습니다. 전화해야하는 다른 기능이 있다면 잘 (루프에서) 호출하십시오. 아니면 특정 이벤트가 발생할 때만 호출되도록하고 싶다고 말하는 것입니까? 문제가 무엇인지 구체적으로 설명하십시오. –

1

난 당신이 그것의 디스플레이에서 그리드 클래스를 분리하는 것입니다 필요 생각합니다. 당신은 메인 게임 루프에 의해 스크린 표면에 인쇄 될 표면을 생성하도록 만들 수 있습니다. 귀하의 초기화, highlight_cell 및 clear_grid 방법이 내가 함께 작업 버전을 가지고 더 많은 유연성을

+0

아픈 표면을 점검해야합니다. 이것은 파이 게임 (pygame)을 처음 사용하기 때문에 그들의 존재를 알지 못했습니다. – giodamelio

+0

자습서를 확인해야합니다. 원하는 것을 얻기위한 여러 가지 방법이 있습니다. 여기에는 또 다른 링크가 있습니다 : [link] (http://www.penzilla.net/tutorials/python/pygame/). 이 객체에서 표시 할 객체에는 자체 프로젝트 draw() 메서드가 있습니다.이 메서드는 작은 프로젝트에서는 더 쉽지만 유지 관리가 어려워 질 수 있습니다. – CGGJE