Spiel vorbei

Spiel vorbei#

Typically, the following happens during a game-over event:

  1. The game is paused

  2. A text appears (possibly with a high score)

  3. There is a way to restart the game.

First, it makes sense to create a method that creates all the actors that should be created at the start of a game:

def setup():
    player = Circle(40,100)
    @player.register
    def on_key_pressed(self, keys):
        global running
        if running:
            if 's' in keys:
                self.y += 1
            if 'w' in keys:
                self.y -= 1
        else:
            setup()
    @player.register
    def on_detect_actor(self, other):
        if other in enemies:
            game_over()

In this method, for example, a player object is created and events are already registered to this player object. If, for example, another actor is detected, then the game_over method is triggered.

In der game_over-Methode wird die Welt angehalten:

def game_over():
    global running
    running  = False
    Text(100,100, "Game Over")
    world.stop()

Es wird global überprüft, ob die SPACE-Taste gedrückt wird - Wenn die Welt angehalten wird, wird die restart-Methode ausgelöst:

@world.register
def on_key_down(self, keys):
    global running
    if not running and "SPACE" in keys:
        restart()

The restart method deletes all actors, restarts the world, and calls setup

def restart():
    global running
    enemies = []
    for actor in world.actors:
        actor.remove()
    world.start()
    running = True
    setup()

Overall sieht dies dann so aus:

from miniworlds import *
import random

running = True
enemies = []

world = World()

def setup():
    player = Circle(40,100)
    @player.register
    def on_key_pressed(self, keys):
        global running
        if running:
            if 's' in keys:
                self.y += 1
            if 'w' in keys:
                self.y -= 1
        else:
            setup()
    @player.register
    def on_detect_actor(self, other):
        if other in enemies:
            game_over()

def game_over():
    global running
    running  = False
    Text(100,100, "Game Over")
    world.stop()
    
def restart():
    global running
    enemies = []
    for actor in world.actors:
        actor.remove()
    world.start()
    running = True
    setup()
    
def create_enemy():
    global enemies
    enemy = Circle(400, random.randint(0,400))
    enemies.append(enemy)
    @enemy.register
    def act(self):
        self.x -= 1
        if self.x < 0:
            enemies.remove(self)
            self.remove()
    
@world.register
def act(self):
    if self.frame % 50 == 0:
        create_enemy()

@world.register
def on_key_down(self, keys):
    global running
    if not running and "SPACE" in keys:
        restart()
        
setup()
world.run()