Typing Tutor Game

Game states and loops

All games work similarly in that it has states and loops.

Typical game states are playing and game over states.

And the game loop is where we sert up the levels and user game play (when is the 'game over'). It is where we determine how complex the game is.

Game states

Now that we have our object oriented game object. Let's add our game states: START, PLAYING and GAMEOVER.

# States START = 1 PLAYING = 2 GAMEOVER = 3

Game loop and events

With our game states, we can now set up our main game loop.

We will have two loops in our game, the main game loop with the game states, and our inner play loop that we go into for each level that we will add in later.

And in addition to our checking of QUIT event, we check for KEYUP event and increment the state or reset it if it is GAMEOVER.

But only for the spacebar. Since this is a typing game, we want to prevent accidentally switching state with our typing keys.

No we can use the state flag

        self.running = True if self.disp_surf else False
self.state = START
def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False
self.state = GAMEOVER return elif event.type == pygame.KEYUP: if event.key == pygame.K_SPACE: if self.state == GAMEOVER: self.state = START else: self.state +=1
return

It's hard to tell which state we are at for now, we'll take care of that when we draw text.

The inner loop will be taking care of rendering when the game is playing. So we only need to bother with START and GAMEOVER.

So let's add a render function.

Fill the surface with black:

# R G B BLACK = ( 0, 0, 0)
. . . def execute(self): # Event loop while self.running: self.check_events()
self.render() return def render(self): '''Render surface''' self.disp_surf.fill(BLACK) # Blit everything to screen self.screen.blit(self.disp_surf, (0,0)) pygame.display.flip() return

blit(), stands for block transfer, will prepare image for 'transfer' onto the display surface. Or in other words, draw in buffer for transfer to surface.

flip(), will flip and update the whole display and show the changes to the game display.

update(), will only update a portion of the screen, that is the drawn rect or area without updating the whole display.

I would do a quick test and run the script now, to check that nothing is broken. There is nothing new to observe when the screen comes up, except that our screen is black instead of grey.