为此,您必须执行几个步骤。您将需要项目符号的图片、存储项目符号位置的方法、创建项目符号的方法、渲染项目符号的方法以及更新项目符号的方法。您似乎已经知道如何导入图片,所以我将跳过这一部分。
有多种方法可以存储信息。我将使用左上角的项目符号列表。在最终循环之前的任何位置创建列表bullets = []
.
要创建项目符号,您需要使用鼠标的位置。加入bullets.append([event.pos[0]-32, 500])
after 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.mixer
from pygame.locals import *
pygame.init()
size = width, height = 800, 600
screen = 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()
如果你和我都正确地完成了所有操作,这应该会给你带来功能性的子弹。如果您不明白发生了什么或者某些事情不起作用,请随时向我提问。
请注意,images/pygame.Surfaces 应使用convert http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert or convert_alpha
提高性能的方法。