python – Pygame,如何在屏幕上绘制一个形状并删除前一个表面?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Pygame,如何在屏幕上绘制一个形状并删除前一个表面?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2294字,纯文字阅读大概需要4分钟。
内容图文
![python – Pygame,如何在屏幕上绘制一个形状并删除前一个表面?](/upload/InfoBanner/zyjiaocheng/816/592d740827944cbb93bf0186f1623a91.jpg)
所以我有这个代码,它做的应该是好的.我想要它做的是随机地按照不同的数量缩放正方形.我的问题在于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()
解决方法:
在每个帧(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))即可解决您的问题.
内容总结
以上是互联网集市为您收集整理的python – Pygame,如何在屏幕上绘制一个形状并删除前一个表面?全部内容,希望文章能够帮你解决python – Pygame,如何在屏幕上绘制一个形状并删除前一个表面?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。