您必须完成几个步骤。您将需要项目符号的图片,存储项目符号位置的方法,创建项目符号的方法,呈现项目符号的方法以及更新项目符号的方法。您似乎已经知道如何导入图片,因此我将跳过这一部分。
您可以通过多种方式存储信息。我将使用项目符号左上角的列表。在最终循环之前的任何位置创建列表
bullets = []。
要创建项目符号,您将需要使用鼠标的位置。加入
bullets.append([event.pos[0]-32,500])后
shot.play(),缩进相同的数量。
要渲染项目符号,您将在游戏循环中添加一个for循环。在该行之后
screen.blit(background, (0, 0)),添加以下代码:
for bullet in bullets: screen.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0)
要更新项目符号,您需要在游戏循环中的某处放置如下内容:
for b in range(len(bullets)): bullets[b][0] -= 10
最后,您需要在项目符号到达屏幕顶部时将其删除。在刚刚创建的for循环之后添加此内容(在切片副本上进行迭代,因为列表不应在迭代过程中进行修改):
for bullet in bullets[:]: if bullet[0] < 0: bullets.remove(bullet)
将所有内容放入代码后,它应如下所示:
import sys, pygame, pygame.mixerfrom pygame.locals import *pygame.init()size = width, height = 800, 600screen = pygame.display.set_mode(size)clock = pygame.time.Clock()bullets = []background = pygame.image.load("bg.png").convert()ship = pygame.image.load("ship.png").convert_alpha()ship = pygame.transform.scale(ship, (64, 64))bulletpicture = pygame.image.load("You know what to do").convert_alpha()shot = pygame.mixer.Sound("shot.wav")soundin = pygame.mixer.Sound("sound.wav")soundin.play()while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == MOUSEBUTTONDOWN: shot.play() bullets.append([event.pos[0]-32, 500]) clock.tick(60) mx, my = pygame.mouse.get_pos() for b in range(len(bullets)): bullets[b][0] -= 10 # Iterate over a slice copy if you want to mutate a list. for bullet in bullets[:]: if bullet[0] < 0: bullets.remove(bullet) screen.blit(background, (0, 0)) for bullet in bullets: screen.blit(bulletpicture, pygame.Rect(bullet[0], bullet[1], 0, 0)) screen.blit(ship, (mx-32, 500)) pygame.display.flip()如果您和我都正确地完成了所有操作,那么应该可以使您正常运行。请不要犹豫,问我任何问题,如果您不了解正在发生的事情或某些事情不起作用。
请注意,应该使用
convert或
convert_alpha方法转换images
/ pygame.Surfaces以提高性能。



