Typing Tutor Game

Game Play

Now that we have our main loop, let us create our inner game play loop, where the playing of levels happen:

# game.py
import pygame
from play import GamePlay
. . . class TypingTutor(): def __init__(self): pygame.init() # initialises Pygame libraries self.screen = pygame.display.set_mode((WIDTH, HEIGHT)) self.disp_surf = self.init_display() self.size = WIDTH, HEIGHT self.running = True if self.disp_surf else False self.state = START self.font = pygame.font.Font('Consolas Bold.ttf', 36)
self.game = None
return . . . def execute(self): # Event loop while self.running: self.check_events()
if self.state == PLAYING: self.game = GamePlay(self.screen) self.game.execute() self.state += 1 else: self.render()
return

Let's create a new script, play.py.

So that we have a class to store our game play settings and status.

The base code of our play.py is almost identical to our game.py, it just requires a few adjustments:

# play.py
import pygame # Colours R G B
BLUE = ( 0, 0, 128) WHITE = (255, 255, 255) class GamePlay(): def __init__(self, screen): self.screen = screen
pygame.init() self.disp_surf = pygame.Surface(self.screen.get_size()).convert() self.width, self.height = screen.get_size()
self.font = pygame.font.Font('Consolas Bold.ttf', 16)
self.playing = True def execute(self): while self.playing: self.check_events()
self.loop()
self.render() return def check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() elif event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE: self.playing = False
return
def loop(self): pass
def render(self): '''Render surface'''
self.disp_surf.fill(BLUE) # Fill background # Draw some text self.draw_word('Playing...', WHITE, (0, 0))
# Blit everything to screen self.screen.blit(self.disp_surf, (0,0)) pygame.display.flip() return
def draw_word(self, text, colour, coord):
'''Display given text''' text_surf = self.font.render(text, True, colour) text_rect = text_surf.get_rect()
text_rect.topleft = coord
self.disp_surf.blit(text_surf, text_rect) return

We use a different sized font and background colour for our inner play loop.

And instead of checking for spacebar, we now check for the quit button to advance to the next state.

Further difference is instead of center of our text, we draw from the top left corner of our text surf.