一个简单的问题,但我是 Python/Pygame 的新手。我想 blit 一个图像 (old.png),然后在按键(空格键)时用另一个图像(new.png)替换该图像:顺序演示。目前,old.png 保留在表面上,new.png 结束在它上面。
这是我的代码:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(old, (display_width/2, display_height/2))
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
screen.blit(new, (display_width/2, display_height/2))
pygame.display.flip()
clock.tick(30)
请您参考如下方法:
您可以将图像保存在列表中并使用索引 current_image 选择要显示的图像。这样您就可以拥有 2 张以上的图片。
# All images in list
images = []
images.append(old)
images.append(new)
images.append(another_image)
#images.append(another_image_2)
#images.append(another_image_3)
# How many images we have
images_number = len(image)
# Index of currently displayed image
current_image = 0
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
# Get next index (if it is bigger than `images_number` then get `0`)
current_image = (current_image + 1) % images_number
# Clear screen
screen.fill((0,,0)) # black
# Display (blit) current image
screen.blit(images[current_image], (display_width/2, display_height/2))
pygame.display.flip()
clock.tick(30)
顺便说一句,您可以使用:
screen_rect = screen.get_rect()
然后你可以使用:
screen_rect.center
代替:
(display_width/2, display_height/2)
在:
screen.blit(images[current_image], screen_rect.center)
但是,如果你想正确地居中图像,你需要 image_rect,像这样:
# Get image_rect
image_rect = images[current_image].get_rect()
# Center the image_rect on the screen
image_rect.center = screen_rect.center
# Draw (blit) the image using 'image_rect'
screen.blit(images[current_image], image_rect)
