I want to do something before the blender game engine stops. For example, print "THE END" on terminal when I press ESC to exit (scripting).


2 Answers 2


You can use an app event handler for this.

An event handler is a function (known as a "callback") that is launched when the event is triggered. You can append a custom function of your own to blender's event handlers, and it will be launched when these events are fired.

Conveniently, there's such an event for the end of the game engine (bpy.app.handlers.game_post).

import bpy

def execute_after_game( scene ):
    print( "GAME OVER!!" )

bpy.app.handlers.game_post.append( execute_after_game )

This example will add a function that prints "GAME OVER!!" to the terminal after the game is finished.

  • 1
    $\begingroup$ This solution is for Blender. It will not work with the BGE. $\endgroup$
    – Monster
    Feb 23, 2016 at 6:05

When does your game end?

It ends when you either press ESC (default setting), or you activate the Game Actuator.

The default setting does not let you much choice as you can't "intercept" the end of the game.

But, you can override the default.

Attention: be very careful with the next steps. Otherwise it is possible you can't stop your game anymore.

Therefore we first completely override the exit behavior with our own one.

KeyboardSensor ESC -> AND -> GameActuator Mode: Quit Game

Please do it exactly that way.

What happens?

When you setup ESC in any keyboard sensor the default exit will be disabled. Therefore you have to setup a custom exit (game actuator).

With that you know when the game ends as you sense the request for ending the game (pressing ESC).

Your requirement was

print "THE END" on terminal

So you can trigger a Python controller with the same keyboard sensor. (Do not replace or disconnect the AND Controller - most-likely you forget to activate the connected actuators from your Python controller)

Be aware actuators will not show any effect as the game ends within the next frame.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .