2017-10-30 1 views
1

예를 들어, 발사체가 화면을 벗어나서도 프로그램이 여전히 위치, 속도 등을 계산합니까?파이 게임과 파이썬을 사용할 때 메모리를 해제하는 것에 대해

그렇다면 해제하는 방법은 무엇입니까?

import pygame 
from pygame.locals import * 
from sys import exit 

pygame.init() 

screen = pygame.display.set_mode((640, 480), 0, 32) 

background = pygame.image.load(background_image_filename).convert() 
sprite = pygame.image.load(sprite_image_filename) 


x = 0. 

while True: 

    for event in pygame.event.get(): 
     if event.type == QUIT: 
      exit() 

    screen.blit(background, (0,0)) 
    screen.blit(sprite, (x, 100)) 
    x+= 10. 
    pygame.display.update() 

답변

1

예, 위치, 속도 등을 계산해야합니다. 그렇지 않으면 화면 외부에있는 객체가 화면 영역으로 다시 들어올 수 없습니다. 파이 게임은 이러한 객체를 렌더링하려고 시도하지 않을만큼 똑똑합니다.

보통 self.kill()을 호출하여 스프라이트를 제거 할 수있는 pygame sprites and sprite groups을 사용하는 것이 좋습니다. 또한 목록이나 세트를 사용하여 객체를 저장할 수도 있지만 직접 코드를 작성해야합니다.

그래서 먼저 화면의 크기 또는 조금 큰 (아래 예에서는 작은 것을 사용합니다) pygame.Rect (game_area)을 정의합니다. Rect는 contains 메서드를 사용하여 스프라이트의 rect가 game_area rect 내에 있는지 확인할 수 있습니다. 스프라이트가 바깥 쪽이면 self.kill()을 호출하면 파이 게임이 관련된 모든 스프라이트 그룹에서 스프라이트를 제거합니다.

import random 

import pygame as pg 
from pygame.math import Vector2 


class Projectile(pg.sprite.Sprite): 

    def __init__(self, pos, game_area): 
     super().__init__() 
     self.image = pg.Surface((5, 5)) 
     self.image.fill(pg.Color('aquamarine2')) 
     self.rect = self.image.get_rect(center=pos) 
     self.vel = Vector2(2, 0).rotate(random.randrange(360)) 
     self.pos = Vector2(pos) 
     self.game_area = game_area 

    def update(self): 
     self.pos += self.vel 
     self.rect.center = self.pos 
     if not self.game_area.contains(self.rect): 
      self.kill() 


def main(): 
    screen = pg.display.set_mode((640, 480)) 
    game_area = pg.Rect(60, 60, 520, 360) 
    game_area_color = pg.Color('aquamarine2') 
    clock = pg.time.Clock() 
    all_sprites = pg.sprite.Group(Projectile(game_area.center, game_area)) 

    done = False 

    while not done: 
     for event in pg.event.get(): 
      if event.type == pg.QUIT: 
       done = True 

     all_sprites.add(Projectile(game_area.center, game_area)) 
     all_sprites.update() 

     screen.fill((30, 30, 30)) 
     all_sprites.draw(screen) 
     pg.draw.rect(screen, game_area_color, game_area, 2) 

     pg.display.flip() 
     clock.tick(60) 


if __name__ == '__main__': 
    pg.init() 
    main() 
    pg.quit() 
+0

고마운데, 멋져 보인다! – wyp

1

예 그렇습니다,하지만 당신은 (X를 사용 증가) 단 하나의 사물이 있기 때문에, 당신은 쉽게 문 경우 몇 가지를 사용하여 수행 할 작업을 선택할 수 있습니다. 컨테이너에 저장해야하는 여러 개의 발사체가있을 때 프로세스가 더 어려워집니다.이를 적용해야합니다.

여기

for projectile in projectile_list: 

    # Check if the position is inside the screen 
    if 0 < projectile.x < WIDTH and 0 < projectile.y < HEIGHT: 
     # Do position operations 

이 방법은, 당신은 단지 필요한 사항을 처리하는 예입니다. 유사한 방법을 적용하여 사용하지 않은 투사 체를 목록이나 사용중인 컨테이너에서 제거 할 수 있습니다.

+0

감사합니다. 나는 간단한 그룹 컨테이너가이 문제를 해결할 것이라고 생각한다. – wyp

관련 문제