Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

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.



ADVERTISEMENT
ADVERTISEMENT