×

Keyboard Jump Game in Python

Keyword hop (jump) game is a speed composing game that aides in further developing the composing velocity of players

The object of Keyboard Jump (hop) Game Python Project is to fabricate a console bounce game that assists players with speeding up. We use pygame, arbitrary, and time modules in this task.

In this task, the player needs to press similar keys to the letters showed on the game screen. On the off chance that the player made a blunder while composing, the game moves past.

Project Prerequisites

  • To construct keyword hop game task we require pygame, irregular and time modules, and fundamental ideas of python.
  • Pygame module is utilized to make mixed media application and games
  • Arbitrary modules used to create irregular numbers
  • Time module gives usefulness like holding up during execution and furthermore gauges the effectiveness of code.
  • To install, we need the pip install command in prompt console:
pip install pygame
pip install random

Project (Keyboard Jump Game) File Structure

  • Import various module like Installing Pygame and Creating the game window
  • Main loop
  • Define functions
  • Initialize window

Approach to begin developing the game, are performed through multiple stages.

1. Importing various Modules

import pygame
import random
import time

2. Initializing required window

Code snippet: This shows basically the logic of Initializing required window (not meant for execution), part of the Source code:

import pygame
import random
import time
pygame.init ()
WIDTH1 = 855
HEIGHT1 = 650
black= (0,0,0)
gameDisplay = pygame.display.set_mode ( (WIDTH1, HEIGHT1))   #setting game display size
background = pygame.image.load ('keyback.jpg')
background = pygame.transform.scale (background,  (WIDTH1, HEIGHT1))  #scale image
font = pygame.font.Font ('comic.ttf', 45)

Explanation of the above snippet:

  • to instate pygame pygame.init ()
  • to set the subtitle of the game window pygame.display.set_caption
  • utilizing pygame.display.set_mode to set WIDTH1 and HEIGHT1 of game showcase size
  • game foundation set by pygame.image.load, which is utilized to set the foundation picture
  • pygame.transform.scale is utilized to scale picture to required aspect

3. Defining functions

Code snippet: This shows basically the logic of defining function (not meant for execution), part of the Source code:

word_speed11= 0.3
scores = 0
def new_word ():
    global displayword, yourword, x_cor1, y_cor1, text, word_speed1
    x_cor1 = random.randint (300,700)    
    y_cor1 = 255  #y - cor
    word_speed11+ = 0.10
    yourword1= ''
    words = open ("words.txt").read ().split (', ')
    displayword1= random.choice (words)
new_word ()
font_name1 = pygame.font.match_font ('comic.ttf')
def draw_text (display, text, size, x, y):
    font = pygame.font.Font (font_name1, 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 new_word ():
    global displayword, yourword, x_cor1, y_cor1, text, word_speed1
    x_cor1 = random.randint (300, 700)     #randomly choose x - cor between 300 - 700
    y_cor1 = 255  
    word_speed11+ = 0.10
    yourword1= ''
    words = open ("words.txt").read ().split (', ')
    displayword1= random.choice (words)
new_word ()
def game_front_screen ():
    gameDisplay.blit (background,  (0,0))
    if not game_over1 :
        draw_text (gameDisplay, "GAME OVER!", 95, WIDTH1 / 2, HEIGHT1 / 4)
        draw_text (gameDisplay,"Scores : " + str (scores), 70, WIDTH1 / 2, HEIGHT1 /2)
    else:
        draw_text (gameDisplay, "Press any key to begin!", 54, WIDTH1 / 2, 550)
    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
game_over1 = True
game_start1 = True
while True:
    if game_over1:
        if game_start1:
            game_front_screen ()
        game_start1 = False
    game_over1 = False

Explanation of the above snippet:

  • new_word () capacity will haphazardly take words from word.txt document and furthermore introduce x and y directions of word
  • draw_text () capacity will assist with attracting text in plain view a given textual style and size.
  • get_rect () strategy return a rect object
  • blit () is utilized to draw a picture or compose text on the screen at the predefined position
  • game_front_screen () work show the front game screen and game over screen
  • pygame.event.get () will return all the occasion put away in the pygame occasion line
  • pygame.display.flip () will refresh just a piece of the screen yet in the event that no contention will pass, it will refresh the whole screen
  • occasion type equivalent is utilized to stop the pygame window
  • event.KEYUP occasion happens when a console key is squeezed and delivered

4. Main loop

Code snippet: This shows basically the logic of main loop stage (not meant for execution), part of the Source code:

import pygame
import random
import time
game_over1 = True
game_start1 = True
while True:
    if game_over1:
        if game_start1:
            game_front_screen ()
        game_start1 = False
    game_over1 = False
    background = pygame.image.load ('teacher - background.jpg')
    background = pygame.transform.scale (background,  (WIDTH1, HEIGHT1))
    character = pygame.image.load ('char.jpg')
    character = pygame.transform.scale (character,  (55,55))
    wood = pygame.image.load ('wood - .png')
    wood = pygame.transform.scale (wood,  (95,55))
    gameDisplay.blit (background, (0,0))
    gameDisplay.blit (wood, (x_cor1 - 55, y_cor1+15))
    gameDisplay.blit (character, (x_cor1 - 100, y_cor1))
    draw_text (gameDisplay, str (displayword), 45, x_cor1, y_cor1)
    draw_text (gameDisplay, 'Scores:'+str (scores), 45, WIDTH1/2 , 5)
def new_word ():
    global displayword, yourword, x_cor1, y_cor1, text, word_speed1
    x_cor1 = random.randint (300, 700)     #randomly choose x - cor between 300 - 700
    y_cor1 = 255  
    word_speed11+ = 0.10
    yourword1= ''
    words = open ("words.txt").read ().split (', ')
    displayword1= random.choice (words)
new_word ()
    y_cor1 + = word_speed1
   
    for event in pygame.event.get ():
        if event.type = = pygame.QUIT:
            pygame.quit ()
            quit ()
        elif event.type = = pygame.KEYDOWN:
            yourword1+ = pygame.key.name (event.key)
            if displayword.startswith (yourword):
                if displayword1= = yourword:
                    scores + = len (displayword)
                    new_word ()
            else:
                game_front_screen ()
                time.sleep (2)
                pygame.quit ()
               
    if y_cor1 < HEIGHT1 - 5:
        pygame.display.update ()
    else:
        game_front_screen ()

Main logic Function

  • We take care of key occasions
  • Moving the keys across the screen
  • we don't need any invalid keys to move into screen
  • Assuming two keys squeezed at the same time
  • headings all the while

The complete consolidated source code:

#importing modules
import pygame
import random
import time
#initializing window
pygame.init ()
WIDTH1 = 855
HEIGHT1 = 650
black= (0,0,0)
gameDisplay = pygame.display.set_mode ( (WIDTH1, HEIGHT1))
pygame.display.set_caption ('your Keyboard Jumping Game ')
background = pygame.image.load ('keyback.jpg')
background = pygame.transform.scale (background,  (WIDTH1, HEIGHT1))
font = pygame.font.Font ('comic.ttf', 45)
## function to get words randomly
word_speed11= 0.3
scores = 0
def new_word ():
    global displayword, yourword, x_cor1, y_cor1, text, word_speed1
    x_cor1 = random.randint (300, 700)     #randomly choose x - cor between 300 - 700
    y_cor1 = 255  
    word_speed11+ = 0.10
    yourword1= ''
    words = open ("words.txt").read ().split (', ')
    displayword1= random.choice (words)
new_word ()
def game_over1 ():
            my_font1= pygame.font.SysFont ('times new roman', 51)
            game_over1_surface = my_font.render ('Your Scores is : ' + str (Scores), True, red_color)
            game_over1_rect = game_over1_surface.get_rect ()
            game_over1_rect.midtop =  (window_x1/2, window_y1/4)
            game_window.blit (game_over1_surface, game_over1_rect)
            pygame.display.flip ()
            time.sleep (2)
            pygame.quit ()
            quit ()
#function drawing text
font_name1 = pygame.font.match_font ('comic.ttf')
def draw_text (display, text, size, x, y):
    font = pygame.font.Font (font_name1, 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_over1 :
        draw_text (gameDisplay, "GAME OVER!", 95, WIDTH1 / 2, HEIGHT1 / 4)
        draw_text (gameDisplay,"Scores : " + str (scores), 70, WIDTH1 / 2, HEIGHT1 /2)
    else:
        draw_text (gameDisplay, "Press a key to begin!", 54, WIDTH1 / 2, 550)
    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
#main looping
game_over1 = True
game_start1 = True
while True:
    if game_over1:
        if game_start1:
            game_front_screen ()
        game_start1 = False
    game_over1 = False
   
    background = pygame.image.load ('teacher - background.jpg')
    background = pygame.transform.scale (background,  (WIDTH1, HEIGHT1))
    character = pygame.image.load ('char.jpg')
    character = pygame.transform.scale (character,  (55,55))
    wood = pygame.image.load ('wood - .png')
    wood = pygame.transform.scale (wood,  (95,55))
    gameDisplay.blit (background,  (0,0))
    y_cor1 + = word_speed1
    gameDisplay.blit (wood, (x_cor1 - 55,y_cor1+15))
    gameDisplay.blit (character, (x_cor1 - 100,y_cor1))
    draw_text (gameDisplay, str (displayword), 45, x_cor1, y_cor1)
    draw_text (gameDisplay, 'Scores:'+str (scores), 45, WIDTH1/2 , 5)
   
    for event in pygame.event.get ():
        if event.type = = pygame.QUIT:
            pygame.quit ()
            quit ()
        elif event.type = = pygame.KEYDOWN:
            yourword1+ = pygame.key.name (event.key)
            if displayword.startswith (yourword):
                if displayword1= = yourword:
                    scores + = len (displayword)
                    new_word ()
            else:
                game_front_screen ()
                time.sleep (2)
                pygame.quit ()
               
    if y_cor1 < HEIGHT1 - 5:
        pygame.display.update ()
    else:
        game_front_screen ()

Explanation:

In this principle circle, assuming that the letters displayed on the game screen is equivalent to the letter you squeezed than your scores will increment and this will go on however on the off chance that your squeezed letter isn't equivalent to the showcase screen letter then the circle quits running and the game over screen will show and the game will over

Output:

Screenshot of output is presented below

Keyboard Jump Game In Python Keyboard Jump Game In Python

Summary

With this undertaking in Python, we have effectively fostered the  game. We utilized the famous time and arbitrary modules to deliver our program. Executing various capacities and utilizing circles assisted us with a superior comprehension of python fundamentals.

We have effectively fostered the console bounce game python project. We utilized famous pygame and arbitrary modules. We figured out how to arbitrarily create words. Along these lines, we construct a console bounce game. I truly want to believe that you appreciated building this game task.


Related Topics

Python Tuple index() Method

Python Tuple index() Method The tuple.index() method of Python finds the first occurrence of the specified value and returns its index if the value is found else raises an exception if...

1 minute read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

Python variance() function

Variance The variance is the average of the square deviations from the mean. The variance will measure the spread of the dataset from its mean or median value. The greater the...

4 minutes read.

apply() function in python

Pandas: Pandas is a library in python. It is an open source package in python. Pandas in python are used for data cleaning and data analysis. Data frame mainly consists of...

3 minutes read.

Python exe() function

Python exe() function The exec() function in Python executes the specified Python code and accepts large blocks of code. It supports dynamic execution of Python code where the object must be either a string...

1 minute read.

How to comment out a block of code in Python

When you are writing code in Python, you may want to document it. You need to mention why a piece of code functions, for instance. Mathematics, algorithms, and intricate business...

4 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

Binary Search Visualization using Pygame in Python

A calculation like Binary Search is seen effectively by picturing. Here in this tutorial, a function that pictures the Binary Search Algorithm is carried out. The Graphical User’s Interface (GUI)...

15 minutes read.

ModuleNotFoundError No module named 'mysql' in Python

mysql module not found is an error that occurs in python. It appears like ModuleNotError: No module named 'mysql.' This error occurs when you forget to install a module called...

3 minutes read.

Python List remove() method

Python List remove() method The list.remove () method in Python removes the item at the specified position in the given list. Syntax list.remove(x) Parameter x: This parameter represents the element you want to remove and accepts any type...

1 minute read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

End Parameter in python

print(): The python print() function prints the program’s output to the output screen. The output can be an integer value, string value or other value. Syntax: print(“hi”) Output: hi will be displayed on the output...

3 minutes read.

What is the re.sub() function in Python

There. sub () function is used to return a string by replacing the occurrences of a specific character or pattern with a replacement string. To use this function, import the...

3 minutes read.

Implementing geometric shapes into the game in python

Geometric Drawings We are trying to draw various shapes of geometry by using pygame module to implement Geometric Drawings in game. Let us revise few syntax of basic shapes, to get started...

7 minutes read.

How to set font for Text in Python

As a tuple with the font family as the first component, a size in point as the second, and possibly a string with one or more of the style modifiers...

5 minutes read.

GUI to Shut down, Restart and Logout from the PC using Tkinter in Python

GUI: One of the most significant factors that increased the usability of computer and digital technologies for common, less tech-savvy users is likely the development and widespread adoption of GUIs. GUIs...

4 minutes read.

How to Download all Modules in Python

Python: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

Python OOPs: Class, Object, Inheritance and Constructor

Basic Object-Oriented Programming (OOP) Concepts in Python Python is similar to most general-purpose programming languages with an Object-Oriented environment system since its existence. Being an Object-Oriented Programming language, Python provides ease...

9 minutes read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

Io stringio Python

Python programming language: Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a...

7 minutes read.