Typing Tutor Game

sound

Other than giving user feedback visually, we can also provide auditory feedback.

To add some sounds, we use the Pygame.mixer.Sound()

# play.py
# Sound types SOUND_KEYHIT = 1 SOUND_ERROR = 2 SOUND_SUCCESS = 3
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 self.game_objects = GameObjects(self.width, self.height) self.last_add = 0 # time of adding word self.add_timeout = 2000 # 2 seconds self.fps = 25 self.fps_clock = pygame.time.Clock() self.y_delta = 1 self.typing_flag = False self.key_hit = None self.score = 0 self.level = 1 self.typed_count = 0
self.init_sound()
def init_sound(self): self.type_sound = pygame.mixer.Sound("typewriter-snippet.wav") self.err_sound = pygame.mixer.Sound("glitch-noise.wav") self.success_sound = pygame.mixer.Sound("typewriter-ding.wav") return
def play_sound(self, type): if type == SOUND_KEYHIT: self.type_sound.play() elif type == SOUND_ERROR: self.err_sound.play() elif type == SOUND_SUCCESS: self.success_sound.play()

And then play the sound when we have a key_hit:

    def check_key_hit(self):
        '''Check user's typed key'''
        if not self.key_hit:
            return
        
        if self.typing_flag:
            for word in self.game_objects.game_words:
                if word.typed_idx != -1:
                    if word.text[word.typed_idx+1] == self.key_hit:
                        if word.typed():
                            self.typing_flag = False
                            self.add_score(len(word))
self.play_sound(SOUND_SUCCESS) else: self.play_sound(SOUND_KEYHIT)
else: word.typed_reset() self.typing_flag = False
self.play_sound(SOUND_ERROR)
else: for word in self.game_objects.game_words: if word.text[0] == self.key_hit: if word.typed(): self.add_score(1)
self.play_sound(SOUND_SUCCESS)
else: self.typing_flag = True
self.play_sound(SOUND_KEYHIT)
break # Remove words set for removal self.game_objects.clean_up() self.key_hit = None return

Feel free to add more sounds of your liking:

    def init_sound(self):
        self.type_sound = pygame.mixer.Sound("typewriter-snippet.wav")
        self.err_sound = pygame.mixer.Sound("glitch-noise.wav")
        self.success_sound = pygame.mixer.Sound("typewriter-ding.wav")
self.crash_sound = pygame.mixer.Sound("concrete-hit.wav")
return