No Description

scoreboard.py 2.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. import pygame.font
  2. from pygame.sprite import Group
  3. from ship import Ship
  4. class Scoreboard():
  5. """A class to report scoring information."""
  6. def __init__(self, ai_settings, screen, stats):
  7. """Initialize scorekeeping attributes."""
  8. self.screen = screen
  9. self.screen_rect = screen.get_rect()
  10. self.ai_settings = ai_settings
  11. self.stats = stats
  12. # Font settings for scoring information.
  13. self.text_color = (30, 30, 30)
  14. self.font = pygame.font.SysFont(None, 48)
  15. # Prepare the initial score images.
  16. self.prep_score()
  17. self.prep_high_score()
  18. self.prep_level()
  19. self.prep_ships()
  20. def prep_score(self):
  21. """Turn the score into a rendered image."""
  22. rounded_score = int(round(self.stats.score, -1))
  23. score_str = "{:,}".format(rounded_score)
  24. self.score_image = self.font.render(score_str, True, self.text_color,
  25. self.ai_settings.bg_color)
  26. # Display the score at the top right of the screen.
  27. self.score_rect = self.score_image.get_rect()
  28. self.score_rect.right = self.screen_rect.right - 20
  29. self.score_rect.top = 20
  30. def prep_high_score(self):
  31. """Turn the high score into a rendered image."""
  32. high_score = int(round(self.stats.high_score, -1))
  33. high_score_str = "{:,}".format(high_score)
  34. self.high_score_image = self.font.render(high_score_str, True,
  35. self.text_color, self.ai_settings.bg_color)
  36. # Center the high score at the top of the screen.
  37. self.high_score_rect = self.high_score_image.get_rect()
  38. self.high_score_rect.centerx = self.screen_rect.centerx
  39. self.high_score_rect.top = self.score_rect.top
  40. def prep_level(self):
  41. """Turn the level into a rendered image."""
  42. self.level_image = self.font.render(str(self.stats.level), True,
  43. self.text_color, self.ai_settings.bg_color)
  44. # Position the level below the score.
  45. self.level_rect = self.level_image.get_rect()
  46. self.level_rect.right = self.score_rect.right
  47. self.level_rect.top = self.score_rect.bottom + 10
  48. def prep_ships(self):
  49. """Show how many ships are left."""
  50. self.ships = Group()
  51. for ship_number in range(self.stats.ships_left):
  52. ship = Ship(self.ai_settings, self.screen)
  53. ship.rect.x = 10 + ship_number * ship.rect.width
  54. ship.rect.y = 10
  55. self.ships.add(ship)
  56. def show_score(self):
  57. """Draw score to the screen."""
  58. self.screen.blit(self.score_image, self.score_rect)
  59. self.screen.blit(self.high_score_image, self.high_score_rect)
  60. self.screen.blit(self.level_image, self.level_rect)
  61. # Draw ships.
  62. self.ships.draw(self.screen)