×

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

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.

Class and Static Methods in Python

The method is an important concept to learn for every programmer or data analyst. We know that in OOP's concept, each object has its attributes and behaviors defined through methods....

3 minutes read.

Augmented reality in python

In this article, we shall learn about augmented reality in python. Augmented reality is a technology that captures the world around you and adds virtual content or objects on top of...

3 minutes read.

Type casting in Python

Introduction Type Casting is defined as the method of converting the variables/values data type into a certain data type for matching the operation needed to be performed by the users. This...

4 minutes read.

Python program to add two number

Python program to add two number This program will add the two numbers and display their sum on the screen. Example: Input: Number1 = 20        Number2 = 30   Output: Sum =...

2 minutes read.

Python float()

Python float() class The float() class in Python returns a floating point number constructed from a number or string x. Syntax class float([x]) Parameter x: This parameter represents a number or a string that can be converted...

1 minute read.

Uint8 Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

3 minutes read.

Closest Pair of Points in Python

We are given an array of n points in the plane, and our task is to find the pair of points in the array that are the closest to each...

3 minutes read.

Python vs HTML

Python and HTML are not comparable since they are two separate categories of programming languages. Building the structures and layouts of a web page or app requires the usage of HTML,...

8 minutes read.

Weight Conversion GUI 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...

3 minutes read.

Python vs Java

There are a lot of programming languages out there, and every day, a new programming language is developing in some parts of the world. Each programming language is a mixture...

5 minutes read.

Salary of Python Developers in India

In this tutorial, we will understand who python developers are and what is their salary when they work in India. Python Developers Python Developers are the people who are involved in designing...

4 minutes 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 Key Error

What is an Error? Errors are nothing but problems in the program which occur in a program code, and this will stop the execution of the program. It is also called...

6 minutes read.

Python Parse Text File

We will learn different ways of read text records in Python. TL;DR The accompanying tells the best way to read all texts from the readme.txt document into a string: with open('readme.txt') as f: lines...

5 minutes read.

Standard GUI Unit Converter using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

12 minutes read.

Python Set remove() method

Python Set remove() method The set.remove() method in Python removes the specified element from the set if it is present in the set else this method will raise an error if the specified item does...

2 minutes read.

Sklearn linear Model in Python

The most effective and reliable Python machine learning library is Sklearn. Through a Python consistency interface, it offers a variety of effective tools for statistical modeling and machine learning, including...

5 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.

Cross Entropy in Python

Introduction Cross-entropy loss is frequently combined with the softmax function. Determine the total entropy among the distributions or the cross-entropy, which is the difference between two probability distributions. For the purpose...

5 minutes read.