Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Using pygame.time.get_ticks() to display remaining time

I’m currently looking to display the time remaining for power ups on my scoreboard. I’m using pygame.time.get_ticks() to determine the remaining time left for a power up and it seems to be functioning as expected. When a power up is received it lasts for 5 seconds (5000 ticks), unless the same power up is picked up again, then the time is extended by another 5 seconds. This is determined by my power level; picking up a power up increases power up level by 1, once 5 seconds pass, decrease power level by 1.

I’m having trouble working out how to get this to properly display on my scoreboard, as currently it just displays -5000, which would be my starting power up time (0) minus my power up time allowed per level (5000). When a power up is picked up the time does not change at all and just stays at -5000.

Example Image

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

main.py

class AlienInvasion:
    """Overall class to manage game assets and behavior."""

    def __init__(self):
        """Initlize the game, and create game resources."""
        pygame.init()
        self.settings = Settings()

        self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
        self.settings.screen_width = self.screen.get_rect().width
        self.settings.screen_height = self.screen.get_rect().height

        pygame.display.set_caption("Alien Invasion")

        self.stats = GameStats(self)
        self.sb = Scoreboard(self)

        self.ship = Ship(self)

        self._wall_setup()
        self._create_multiple_walls(*self.wall_x_positions,
                                    x_start=self.settings.screen_width / 8, y_start=850)

        self._create_groups()
        self._create_fleet()
        self._create_buttons()

    def run_game(self):
        """Start main loop for our game."""
        while True:
            self._check_events()

            if self.stats.game_active:
                self.ship.update()
                self._update_bullets()
                self._check_bomb_ship_collisions()
                self._update_aliens()
                self._check_power_time()

            self._update_screen()

   def _check_pow_collisions(self):
        collisions = pygame.sprite.spritecollide(
            self.ship, self.powerups, True
        )

        for collosion in collisions:
            if collosion.type == 'gun':
                self.settings.ship_power += 1
                self.settings.powerup_time = pygame.time.get_ticks()
                self._check_power_time()

            if collosion.type == 'shield' and self.stats.ships_left < 3:
                self.stats.ships_left += 1
                self.sb.prep_ships()

    def _check_power_time(self):
        if (self.settings.ship_power >= 2 and pygame.time.get_ticks() -
                self.settings.powerup_time > self.settings.POWERUP_TIME_ALLOWED):
            self.settings.ship_power -= 1
            self.settings.powerup_time = pygame.time.get_ticks()

    def _update_screen(self):
        """Update images on screen and flip to the new screen."""
        # fill our background with our bg_color
        self.screen.fill(self.settings.bg_color)

        # draw scoreboard to screen
        self.sb.show_score()

        # draw ship to screen
        self.ship.blitme()

        for bullet in self.bullets.sprites():
            bullet.draw_bullet()

        self.alien_bombs.update()
        self.alien_bombs.draw(self.screen)

        self.aliens.draw(self.screen)

        self.powerups.draw(self.screen)
        self.powerups.update()
        self._check_pow_collisions()

        self.blocks.draw(self.screen)
        self._check_wall_collisions()

        # draw play button if game is inactive
        if not self.stats.game_active:
            if self.stats.level == 1:
                self.play_button.draw_button()

            elif not self.stats.ships_left:
                self.game_over_button.draw_button()
                pygame.mouse.set_visible(True)

            elif self.stats.ships_left != 0:
                self.continue_button.draw_button()

        # Make the most recently drawn screen visible.
        # this clears our previous screen and updates it to a new one
        # this gives our programe smooth movemnt
        pygame.display.flip()

if __name__ == '__main__':
    # Make a game instance, and run the game
    ai = AlienInvasion()
    settings = Settings()

    ALIENBOMB = pygame.USEREVENT + 1
    pygame.time.set_timer(ALIENBOMB, settings.alien_bomb_speed)

    ai.run_game()

scoreboard.py

class Scoreboard:
    """a class to report score information"""

    def __init__(self, ai_game):
        self.ai_game = ai_game
        self.screen = ai_game.screen
        self.screen_rect = self.screen.get_rect()
        self.settings = ai_game.settings
        self.stats = ai_game.stats

        # font settings for scoreboard
        self.text_color = (255, 255, 255)
        self.font = pygame.font.Font('fonts/font.ttf', 20)

        self.prep_score()
        self.prep_high_score()
        self.prep_level()
        self.prep_remaining_pow_time()
        self.prep_empty_hearts()
        self.prep_ships()

    def prep_remaining_pow_time(self):
        """turn remainging pow time into an image"""
        pow_time_left = self.settings.powerup_time - self.settings.POWERUP_TIME_ALLOWED
        pow_time_str = "{}".format(pow_time_left)
        self.powtime_image = self.font.render(pow_time_str, True, 
        self.text_color, self.settings.bg_color)

        # place image below score and level
        self.powtime_rect = self.powtime_image.get_rect()
        self.powtime_rect.right = self.screen_rect.right - 20
        self.powtime_rect.top = self.level_rect.bottom + 10

  def show_score(self):
        """draw score to screen"""
        self.screen.blit(self.score_image, self.score_rect)
        self.screen.blit(self.high_score_image, self.high_score_rect)
        self.screen.blit(self.level_image, self.level_rect)
        self.screen.blit(self.powtime_image, self.powtime_rect)
        self.empty_hearts.draw(self.screen)
        self.ships.draw(self.screen)

settings.py

class Settings:
    """A class to store our settings for Alien Invasion game."""

    def __init__(self):
        """Initlize the games settings."""
        # screen settings
        self.screen_width = 1600
        self.screen_height = 900
        self.bg_color = (0, 0, 0)

        # ship settings
        self.ship_limit = 3
        self.ship_power = 1
        self.POWERUP_TIME_ALLOWED = 5000

        # bullet settings
        self.bullet_width = 3
        self.bullet_height = 15
        self.bullet_color = (255, 51, 51)
        self.bullets_allowed = 3
        self.upgraded_bullets_allowed = 6


        # alien settings
        self.fleet_drop_speed = 10
        self.increse_bomb_rate = 75

        # how quickly the game speeds up
        self.speedup_scale = 1.1

        # how muct alien poits value increses
        self.score_scale = 1.5

        self.initialize_dynamic_settings()

    def initialize_dynamic_settings(self):
        """settings that change through the game"""
        self.ship_speed = 1.5
        self.bullet_speed = 1.5

        self.alien_speed = 0.5

        self.alien_bomb_speed = 999
        self.wall_speed = 0.5

        self.fleet_direction = 1

        # scoring
        self.alien_points = 50

        self.powerup_time = 0

    def increse_speed(self):
        """increse speed settings"""
        self.ship_speed *= self.speedup_scale
        self.bullet_speed *= self.speedup_scale
        self.alien_speed *= self.speedup_scale
        self.wall_speed *= self.speedup_scale
        self.alien_bomb_speed -= self.increse_bomb_rate

        self.alien_points = int(self.alien_points * self.score_scale)

>Solution :

You are only doing the following two things once since prep_remaining_pow_time is called in init.

pow_time_str = "{}".format(pow_time_left)
self.powtime_image = self.font.render(pow_time_str, True, 
        self.text_color, self.settings.bg_color)

You need to do it every frame for the self.powtime_image to be updated with the latest pow_time_left value.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading