Keyboard Jump Game in Python

Free Python courses with 57 real-time projects - Learn Python

Keyboard jump game is a speed typing game that helps in improving the typing speed of players

The object of Keyboard Jump Game Python Project is to build a keyboard jump game that helps players to increase their typing speed. We use pygame, random, and time modules in this project.

In this project, the player has to press the same keys to the letters displayed on the game screen. If the player made an error while typing then the game gets over.

Project Prerequisites

To build a keyboard jump game project we require pygame, random and time modules, and basic concepts of python.

Pygame module is used to make multimedia application and games

Random modules used to generate random numbers

Time module provides functionality like waiting during execution and also measures the efficiency of code.

To install these modules we use the pip install command in the command prompt:

pip install pygame
pip install random

Download code of Keyboard Jump Game

Please download the source code of keyboard jump game: keyboard jump game in python

Project File Structure

  • Importing modules
  • Initialize window
  • Define functions
  • Main loop

1. Importing Modules

import pygame
import random
import time

In this step, we import the modules required for the project. In this project, we import pygame, random, time modules

2. Initialize window

pygame.init()
WIDTH = 800
HEIGHT = 600
black=(0,0,0)

gameDisplay = pygame.display.set_mode((WIDTH, HEIGHT))   #setting game display size

background = pygame.image.load('keyback.jpg')
background = pygame.transform.scale(background, (WIDTH, HEIGHT))  #scale image 

font = pygame.font.Font('comic.ttf', 40)

Explanation:

  • pygame.init() initialize pygame
  • pygame.display.set_caption will set the caption of the game window
  • WIDTH and HEIGHT are setting game display size by using pygame.display.set_mode
  • game background set by pygame.image.load, which is used to set the background image
  • pygame.transform.scale is used to scale image to required dimensions

3. Define functions

word_speed = 0.5
score = 0

def new_word():
    global displayword, yourword, x_cor, y_cor, text, word_speed
    x_cor = random.randint(300,700)     
    y_cor = 200  #y-cor
    word_speed += 0.10
    yourword = ''
    words = open("words.txt").read().split(', ')
    displayword = random.choice(words)
new_word()

font_name = pygame.font.match_font('comic.ttf')
def draw_text(display, text, size, x, y):
    font = pygame.font.Font(font_name, size)
    text_surface = font.render(text, True, black)
    text_rect = text_surface.get_rect()
    text_rect.midtop = (x, y)
    gameDisplay.blit(text_surface, text_rect)


def game_front_screen():
    gameDisplay.blit(background, (0,0))
    if not game_over :
        draw_text(gameDisplay, "GAME OVER!", 90, WIDTH / 2, HEIGHT / 4)
        draw_text(gameDisplay,"Score : " + str(score), 70, WIDTH / 2, HEIGHT /2)
    else:
        draw_text(gameDisplay, "Press any key to begin!", 54, WIDTH / 2, 500)
    pygame.display.flip()
    waiting = True
    while waiting:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
            if event.type == pygame.KEYUP:
                waiting = False

Explanation:

  • new_word() function will randomly take words from word.txt file and also initialize x and y coordinates of word
  • draw_text() function will help to draw text on display in a given font and size.
  • get_rect() method return a rect object
  • blit() is used to draw an image or write text on the screen at the specified position
  • game_front_screen() function display the front game screen and game over screen
  • pygame.event.get() will return all the event stored in the pygame event queue
  • pygame.display.flip() will update only a part of the screen but if no argument will pass then it will update the entire screen
  • event type equal is used to quit the pygame window
  • event.KEYUP event occurs when a keyboard key is pressed and released

4. Main loop

game_over = True
game_start = True
while True:
    if game_over:
        if game_start:
            game_front_screen()
        game_start = False
    game_over = False

    background = pygame.image.load('teacher-background.jpg')
    background = pygame.transform.scale(background, (WIDTH, HEIGHT))
    character = pygame.image.load('char.jpg')
    character = pygame.transform.scale(character, (50,50))
    wood = pygame.image.load('wood-.png')
    wood = pygame.transform.scale(wood, (90,50))
    gameDisplay.blit(background, (0,0))
    gameDisplay.blit(wood,(x_cor-50,y_cor+15))
    gameDisplay.blit(character,(x_cor-100,y_cor))
    draw_text(gameDisplay, str(displayword), 40, x_cor, y_cor)
    draw_text(gameDisplay, 'Score:'+str(score), 40, WIDTH/2 , 5)

    y_cor += word_speed
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit()
        elif event.type == pygame.KEYDOWN:
            yourword += pygame.key.name(event.key)

            if displayword.startswith(yourword):
                if displayword == yourword:
                    score += len(displayword)
                    new_word()
            else:
                game_front_screen()
                time.sleep(2)
                pygame.quit()
                
    if y_cor < HEIGHT-5:
        pygame.display.update()
    else:
        game_front_screen()

Explanation:

In this main loop, if the letters shown on the game screen is the same as the letter you pressed than your score will increase and this will continue but if your pressed letter is not the same as the display screen letter then the loop stops running and the game over screen will show and the game will over

Keyboard Jump Project Output

keyboard jump game output

Summary

We have successfully developed the keyboard jump game python project. We used popular pygame and random modules. We learned how to randomly generate words. In this way, we build a keyboard jump game. I hope you enjoyed building this game project.

Disclaimer: Few of the images used in this project have been taken from Google, we do not hold the copyright of those images.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

6 Responses

  1. Shruti Agarwal says:

    Thank you for this program!

    • DataFlair Team says:

      We appreciate your positive feedback regarding the project, we would like to extend an invitation to explore our more python games projects, we believe you will definitely enjoy them.

  2. bhavika saalunkhe says:

    this code is not run

  3. mustapha moruf says:

    dont get it. i try to install random. this is the error given.ERROR: Could not find a version that satisfies the requirement random (from versions: none)
    ERROR: No matching distribution found for random .
    and i dont know how to implement initialise window

  4. sims says:

    random might be already available in your python. try opening idle and running” import random “. if it is already available it wont show any traceback error.

  5. jeff says:

    PS C:\Users\adm> & C:/Users/adm/AppData/Local/Programs/Python/Python310/python.exe “c:/Users/adm/keyboard jump game”
    pygame 2.1.2 (SDL 2.0.18, Python 3.10.6)
    Hello from the pygame community. https://www.pygame.org/contribute.html
    Traceback (most recent call last):
    File “c:\Users\adm\keyboard jump game”, line 9, in
    background = pygame.image.load(‘keyback.jpg’)
    FileNotFoundError: No file ‘keyback.jpg’ found in working directory ‘C:\Users\adm’.
    PS C:\Users\adm>
    am having that and i don,t know how to deal with it.

Leave a Reply

Your email address will not be published. Required fields are marked *