Home > Back-end >  What is a good way to restart a game?
What is a good way to restart a game?

Time:09-07

So right now, i have a platformer and i want to make it so when i click on a button, the whole game restarts.

In main.py:

level=Level(level_map,screen)
while running:
    if game_state=='game_active':
        for event in pygame.event.get():
            if event.type==pygame.QUIT:
                pygame.quit()
                pygame.font.quit()
                sys.exit()
        level.run()
        screen.blit(sky_surface,(0,0))
        pygame.display.update()
        clock.tick(60)

in level.py:

class Level:
    def __init__(self,level_data,surface):
        self.display_surface=surface
        self.level_building(level_data)
    def level_building(self,tilesheet):
        self.coins=pygame.sprite.Group()
        self.player=pygame.sprite.GroupSingle()
        for row_index,row in enumerate(level_map):
            for col_index,cell in enumerate(row):
                self.x=col_index*tile_size
                self.y=row_index*tile_size
                if cell=='R':
                    self.coin_sprite=Recyclables((self.x 22,self.y 55))
                    self.coins.add(self.coin_sprite)
                if cell=='P':
                    self.player_sprite=Player((self.x 10,self.y))
                    self.player.add(self.player_sprite)
    def collisions(self):
        playercoin=pygame.sprite.groupcollide(self.coins,self.player,True,False) # kills the coin (to show it has been picked up)
        if len(playercoin)==1:
            self.score =1
    def run(self):
        self.coins.draw(self.display_surface)
        self.collisions()
        self.player.draw(self.display_surface)

After my game finishes running, what is a good way to restart everything, and respawn all the sprites that were killed? (did not show the kill code since it'd be too long) so far i've tried killing all sprites after the game but i don't know how to re-draw everything.

CodePudding user response:

In PyGame, you're in full control of what's being drawn on the screen every frame, so I'm not sure why you wouldn't be sure how to redraw things.

Since you apparently have already encapsulated your game logic into the Level class, restarting the level shouldn't require more than just

level = Level(level_map, screen)

so subsequent calls to level.run() use a fresh level.

(Also, unless you're doing esoteric things that you're not showing us here, you shouldn't necessarily need to even "kill sprites".)

  • Related