2017-05-05 1 views
1
import pygame as pg # rename pygame module with pg 
import sys # application termination for some windows machines 

def main(): 
    pg.init() #initialize pygame 
    clock = pg.time.Clock() #create a time object 
    fps = 30 #game frame rate 
    size = [400, 400] #screen size 
    bg = [255, 255, 255] #screen background 

    screen = pg.display.set_mode(size) 
    surface = pg.Surface(screen.get_size()) 

    blocks = [] 
    block_color = [255, 0, 0] 

    def create_blocks(blocks): 
     """ function will create blocks and assign a position to them""" 

     block_width = 20 
     block_height = 20 

     # nested for loop for fast position assignment 
     for i in range(0, 40, block_width): 
      for j in range(0, 40, block_height): 
       # offsets block objects 20px from one another 
       x = 2*i 
       y = 2*j 

       #block rect object 
       rect = pg.Rect(x, y, block_width, block_height) 

       #append rect to blocks list 
       blocks.append(rect) 

    def draw_blocks(surface, blocks, block_color): 
     """ draws blocks object to surface""" 

     #loops through rects in the blocks list and draws them on surface 
     for block in blocks: 
      pg.draw.rect(surface, block_color, block) 

    create_blocks(blocks) 

    while True: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       return False 

     screen.blit(surface, [0, 0]) 
     surface.fill(bg) 

     draw_blocks(surface, blocks, block_color) 

     pg.display.update() 
     clock.tick(fps) 

    pg.quit() # closses pygame window 
    sys.exit # for machines that wont accept pygame quit() event 

if __name__ == '__main__': 
    main() 

이것은 내 질문을 시각화하기 위해 만든 테스트 코드입니다. 내가 물어 보는 것은 기본적으로 내 서페이스 개체 내부의 자식 유형과 수를 어떻게 든 요청할 수있는 메서드입니다. 예를 들어, 서클, 사각형, 선 또는 다른 유형의 오브젝트가 표면에있는 경우 내 표면에있는 모든 유형의 목록이 필요하며 숫자도 필요합니다.파이 게임에서 표면 어린이의 유형과 수를 어떻게 요청합니까?

답변

1

표면에는 그리는 모양이 아니라 구성되는 픽셀/색상에 대한 정보 만 들어 있습니다. 얼마나 많은 도형이 있는지 알고 싶다면 pygame.sprite.Group 또는 다른 데이터 구조를 사용하여 목록에 대한 정보를 저장해야합니다.

blocks 목록에 이미 블록 (pygame.Rect 초)이 있으므로 블록 수를 얻으려면 len(blocks)을 호출하기 만하면됩니다. 또한 circles 목록에 rect를 사용하여 서클을 저장할 수 있습니다.

결국 Shape 클래스를 만들거나 pygame.sprite.Sprite 초를 사용하여 목록/스프라이트 그룹에 인스턴스를 넣을 수 있습니다.

관련 문제