Nav apraksta

game_functions.py 2.0KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import sys
  2. import pygame
  3. from bullet import Bullet
  4. def check_keydown_events(event, ai_settings, screen, ship, bullets):
  5. """Respond to keypresses."""
  6. if event.key == pygame.K_RIGHT:
  7. ship.moving_right = True
  8. elif event.key == pygame.K_LEFT:
  9. ship.moving_left = True
  10. elif event.key == pygame.K_SPACE:
  11. fire_bullet(ai_settings, screen, ship, bullets)
  12. def check_keyup_events(event, ship):
  13. """Respond to key releases."""
  14. if event.key == pygame.K_RIGHT:
  15. ship.moving_right = False
  16. elif event.key == pygame.K_LEFT:
  17. ship.moving_left = False
  18. def check_events(ai_settings, screen, ship, bullets):
  19. """Respond to keypresses and mouse events."""
  20. for event in pygame.event.get():
  21. if event.type == pygame.QUIT:
  22. sys.exit()
  23. elif event.type == pygame.KEYDOWN:
  24. check_keydown_events(event, ai_settings, screen, ship, bullets)
  25. elif event.type == pygame.KEYUP:
  26. check_keyup_events(event, ship)
  27. def fire_bullet(ai_settings, screen, ship, bullets):
  28. """Fire a bullet, if limit not reached yet."""
  29. # Create a new bullet, add to bullets group.
  30. if len(bullets) < ai_settings.bullets_allowed:
  31. new_bullet = Bullet(ai_settings, screen, ship)
  32. bullets.add(new_bullet)
  33. def update_screen(ai_settings, screen, ship, bullets):
  34. """Update images on the screen, and flip to the new screen."""
  35. # Redraw the screen, each pass through the loop.
  36. screen.fill(ai_settings.bg_color)
  37. # Redraw all bullets, behind ship and aliens.
  38. for bullet in bullets.sprites():
  39. bullet.draw_bullet()
  40. ship.blitme()
  41. # Make the most recently drawn screen visible.
  42. pygame.display.flip()
  43. def update_bullets(bullets):
  44. """Update position of bullets, and get rid of old bullets."""
  45. # Update bullet positions.
  46. bullets.update()
  47. # Get rid of bullets that have disappeared.
  48. for bullet in bullets.copy():
  49. if bullet.rect.bottom <= 0:
  50. bullets.remove(bullet)