Snake - Part 2: Life and death

Keep the window alive

For a window to stay alive i.e. not be labeled as “not responding” by your OS, we need to update the window in regular intervals.

To do just that we can call pygame.display.update().
Of course it does not suffice to run this once. We will need to update the window as long as it’s alive.
So let’s introduce a while loop into our code.

import pygame
pygame.init()
pygame.display.set_mode((800,600), pygame.HWSURFACE | pygame.DOUBLEBUF)
while(True):
    pygame.display.update()

Hm, weird.
It seems that wasn’t enough to make the OS believe our game is doing something.

But have you noticed the windows close button doesn’t do anything?
Well thats because the button is handled by the program, not the OS.

Let’s implement some logic to close the window. Maybe this will keep the window active.

Close the window

The press of the close button, as well as many other events, can be “listened” for by calling pygame.event.get() regularly.
This function will return a list of events which we will have to process.

Every event has a type, event.type, which defines what happened.
The type of event we are interested in is pygame.QUIT.

To close the window we can call pygame.quit().

Implementing that into our code, we get something like this:

import pygame
pygame.init()
pygame.display.set_mode((800,600), pygame.HWSURFACE | pygame.DOUBLEBUF)
while(True):
    pygame.display.update()
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()

Yay! We have got an empty window which doesn’t crash on itself and is closeable by pressing the close button.

Next up we will have a look at displaying something inside the window.