【发布时间】:2020-10-28 22:26:32
【问题描述】:
我正在尝试熟悉 Python,并尝试使用 Pygame 制作一款“外星入侵者”风格的游戏。我可以导入船的图像并左右移动。
现在我试图在按下空格键时向飞船发射子弹,但是当我按下它时没有任何反应。
这是我触发按键行为的主程序:
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
#calls a function that increments the x coordinate of the ship
if keys[pygame.K_RIGHT]:
ship.updateRight()
#calls a function that decrements the x coordinate of the ship
if keys[pygame.K_LEFT]:
ship.updateLeft()
#calls a function that updates the screen to create a bullet
if keys[pygame.K_SPACE]:
new_bullet = Bullet(ai_settings, screen, ship)
bullets.add(new_bullet)
bullets.update()
gf.update_screen(ai_settings, screen, ship, bullets)
pygame.quit()
sys.exit()
当按下空格键时,会调用 Bullet 类中的以下函数:
class Bullet(Sprite):
def __init__ (self, ai_settings, screen, ship):
"""Create a bullet object at the ship's current position"""
super().__init__()
self.screen = screen
#create bullet rect (0,0) and then set the correct position
self.rect = pygame.Rect(0, 0, ai_settings.bullet_width, ai_settings.bullet_height)
self.rect.centerx = ship.rect.centerx
self.rect.top = ship.rect.top
#store the bullet's position as a decimal value
self.y = float(self.rect.y)
self.color = ai_settings.bullet_color
self.speed_factor = ai_settings.bullet_speed_factor
def update(self):
"""Move the bullet up the screen"""
#update the decimal position of the bullet
self.y -= self.speed_factor
self.rect.y = self.y
def draw_bullet(self):
"""Draw the bullet to the screen."""
pygame.draw.rect(self.screen, self.color, self.rect)'''
最后是主循环中调用的“update_screen”函数(它包括飞船的一些其他更新):
def update_screen(ai_settings, screen, ship, bullets):
screen.fill(ai_settings.bg_color)
#ship.blitme()
pygame.display.flip()
for bullet in bullets.sprites():
bullet.draw_bullet()
如果有人对为什么没有出现子弹有任何想法,请帮忙!由于我对 Python 还很陌生,所以还没有弄清楚这一点。
非常感谢!
【问题讨论】:
-
pygame.display.flip()必须在for bullet in bullets.sprites():bullet.draw_bullet()之后完成 -
可能提供更多代码
-
@Mattiss 不,不是。你试过了吗?我们不在这里猜测。
标签: python python-3.x pygame sprite pygame-surface