The*_*man 4 python pygame python-3.x
所以我有这个代码,它做的应该是好的.我想要它做的是随机地按照不同的数量缩放正方形.我的问题在于blit功能,我的方块似乎只是向上扩展,因为blit不会删除旧形状,只是将新形状复制到表面.
如何使形状扩大和缩小,而不仅仅是扩展?
我的代码:
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()
Run Code Online (Sandbox Code Playgroud)
在每个帧(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()
Run Code Online (Sandbox Code Playgroud)
请注意,只需添加即可screen.fill( (0,0,0) )解决您的问题.
| 归档时间: |
|
| 查看次数: |
8199 次 |
| 最近记录: |