问题描述
我正在制作 2p Space Invaders。我不明白为什么射击机制不起作用?我曾在 Google 上搜索过这种机制
代码:
import pygame
import sys
pygame.init()
window = pygame.display.set_mode((600,600))
player1 = pygame.image.load('player1.png')
player2 = pygame.image.load('player2.png')
bullet1 = pygame.image.load('bullet1.png')
bullet2 = pygame.image.load('bullet2.png')
bullets = []
p1x = 300
p2x = 300
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
if p1x <= 490:
p1x += 20
if event.key == pygame.K_LEFT:
if p1x > 0:
p1x -= 20
if event.key == pygame.K_a:
if p2x > 0:
p2x -= 20
if event.key == pygame.K_d:
if p2x <= 490:
p2x += 20
if event.key == pygame.K_DOWN:
bullets.append(['d',p1x,0])
if event.key == pygame.K_s:
bullets.append(['u',p2x,0])
for bi in bullets:
if bi[0] == 'd':
window.blit(bullet2,(bi[1],bi[2]))
if bi[0] == 'u':
window.blit(bullet1,bi[2]))
window.fill((0,0))
window.blit(player1,(p2x,488))
window.blit(player2,(p1x,0))
pygame.display.update()
for bj in bullets:
if bj[0] == 'd':
bj[2] += 1
if bj[0] == 'u':
bj[2] -= 1
[窗口图像][1]
提前致谢。 [1]:https://i.stack.imgur.com/SRvZr.png
解决方法
你必须在清除显示后绘制子弹:
while True:
# [...]
window.fill((0,0)) # <--- INSERT
for bi in bullets:
if bi[0] == 'd':
window.blit(bullet2,(bi[1],bi[2]))
if bi[0] == 'u':
window.blit(bullet1,bi[2]))
# window.fill((0,0)) <--- DELETE
# [...]