好的,所以我正在为学校做这个项目。我应该做一个太空入侵者类型的游戏。我已经完成了让我的船移动并开枪的机会。现在这就是问题所在,当我尝试多次射击时,它会擦除之前发射的子弹,然后发射一个根本不是一个好网站的新子弹。我怎样才能让它实际射击多次?
while (running == 1):
screen.fill(white)
for event in pygame.event.get():
if (event.type == pygame.QUIT):
running = 0
elif (event.type == pygame.KEYDOWN):
if (event.key == pygame.K_d):
dir = "R"
move = True
elif (event.key == pygame.K_a):
dir = "L"
move = True
elif (event.key == pygame.K_s):
dir = "D"
move = True
elif (event.key == pygame.K_w):
dir = "U"
move = True
elif (event.key == pygame.K_ESCAPE):
sys.exit(0)
elif (event.key == pygame.K_SPACE):
shot=True
xbul=xgun + 18
ybul=ygun
#if key[K_SPACE]:
#shot = True
if (event.type == pygame.KEYUP):
move = False
#OBJECT'S MOVEMENTS
if ((dir == "R" and xgun<460) and (move == True)):
xgun = xgun + 5
pygame.event.wait
elif ((dir == "L" and xgun>0) and (move == True)):
xgun = xgun - 5
pygame.event.wait
elif ((dir == "D" and ygun<660) and (move == True)):
ygun = ygun + 5
pygame.event.wait
elif ((dir == "U" and ygun>0) and (move == True)):
ygun = ygun - 5
screen.blit(gun, (xgun,ygun))
#PROJECTILE MOTION
#key = pygame.key.get_pressed()
if shot == True:
ybul = ybul - 10
screen.blit(bullet, (xbul, ybul))
if xbul>640:
shot=False
pygame.display.flip()
time.sleep(0.012)
答案 0 :(得分:7)
你只有一个子弹的变量 - xbul和ybul。如果你想要多个项目符号,那么你应该将每个项目符号列为一个列表。您可以附加到每个列表以添加新项目符号,弹出以删除旧项目符号,并在绘制时迭代列表。
答案 1 :(得分:1)
您可以为子弹创建一个类,其中包含x和y坐标以及与项目符号相关的其他内容。然后按下每个按钮按钮,创建一个新实例并将其追加到列表中。这样你可以拥有你想要的子弹数量
(更改了新 move
功能的代码)
class Bullet:
def __init__(self,x,y,vx,vy):# you can add other arguments like colour,radius
self.x = x
self.y = y
self.vx = vx # velocity on x axis
self.vy = vy # velocity on y axis
def move(self):
self.x += self.vx
self.y += self.vy
要添加以使用list
并更新项目符号位置的示例代码(move()
在上面):
if shot == True: # if there are bullets on screen (True if new bullet is fired).
if new_bullet== True: # if a new bullet is fired
bullet_list.append(Bullet(n_x,n_y,0,10)) # n_x and n_y are the co-ords
# for the new bullet.
for bullet in bullet_list:
bullet.move()