Pygame, как нарисовать фигуру на экране и удалить предыдущую поверхность?

Итак, у меня есть этот код, и он делает то, что должен. Я хочу, чтобы он случайным образом масштабировал квадрат на разные величины, что он и делает. Моя проблема связана с функцией блит, мой квадрат только увеличивается, потому что блит не удаляет старую форму, а просто копирует новую на поверхность.

Как я могу заставить фигуру расширяться и сжиматься, а не просто расширяться?

Мой код:

import sys, random, pygame
from pygame.locals import *

pygame.init()

w = 640
h = 480

screen = pygame.display.set_mode((w,h))
morphingShape = pygame.Surface((20,20))
morphingShape.fill((255, 137, 0)) #random colour for testing
morphingRect = morphingShape.get_rect()

def ShapeSizeChange(shape, screen):
    x = random.randint(-21, 20)
    w = shape.get_width()
    h = shape.get_height()
    if w + x > 0 and h + x > 0:
        shape = pygame.transform.smoothscale(shape, (w + x, h + x))
    else:
        shape = pygame.transform.smoothscale(shape, (w - x, h - x))
    shape.fill((255, 137, 0))
    rect = shape.get_rect()
    screen.blit(shape, rect)
    return shape


while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    morphingShape = ShapeSizeChange(morphingShape, screen)
    pygame.display.update()

person Thegluestickman    schedule 01.08.2012    source источник


Ответы (1)


В каждом кадре (каждой итерации цикла While) вы должны стирать экран. По умолчанию цвет экрана (окна) черный, поэтому вы должны очистить экран, вызвав screen.fill( (0,0,0) ). Ниже приведен полный код, который теперь работает так, как вы ожидаете:

import sys, random, pygame
from pygame.locals import *

pygame.init()

w = 640
h = 480

screen = pygame.display.set_mode((w,h))
morphingShape = pygame.Surface((20,20))
morphingShape.fill((255, 137, 0)) #random colour for testing
morphingRect = morphingShape.get_rect()

# clock object that will be used to make the animation
# have the same speed on all machines regardless
# of the actual machine speed.
clock = pygame.time.Clock()

def ShapeSizeChange(shape, screen):
    x = random.randint(-21, 20)
    w = shape.get_width()
    h = shape.get_height()
    if w + x > 0 and h + x > 0:
        shape = pygame.transform.smoothscale(shape, (w + x, h + x))
    else:
        shape = pygame.transform.smoothscale(shape, (w - x, h - x))
    shape.fill((255, 137, 0))
    rect = shape.get_rect()
    screen.blit(shape, rect)
    return shape


while True:
    # limit the demo to 50 frames per second
    clock.tick( 50 );

    # clear screen with black color
    # THIS IS WHAT WAS REALLY MISSING...
    screen.fill( (0,0,0) )

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            sys.exit()
    morphingShape = ShapeSizeChange(morphingShape, screen)
    pygame.display.update()

Обратите внимание, что просто добавление screen.fill( (0,0,0) ) решает ваш вопрос.

person Leonel Machava    schedule 01.08.2012