Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Pygame
3.
Handling Keyboards Inputs
4.
OUTPUT
5.
Handling Mouse Inputs:
6.
Frequently Asked Questions.
6.1.
How do you wait for input in pygame?
6.2.
What does Pygame quit () do?
6.3.
In Pygame, how do I rotate an image?
6.4.
How do you wait 5 seconds in Python?
6.5.
How do you input a key in Python?
7.
Conclusion
Last Updated: Mar 27, 2024
Easy

Input handling in pygame

Introduction

Pygame is a Python multimedia toolkit for making games and other multimedia applications. In this tutorial, we'll look at utilizing the pygame module to create various forms on the screen while considering their height, width, and position in the pygame window.

Pygame is a Python wrapper for SDL, for Simple DirectMedia Layer. SDL allows you to access your system's multimedia hardware, such as sound, video, mouse, keyboard, and joystick, from any platform. pygame was developed as a replacement for the now-defunct PySDL project. You can construct games and rich multimedia Python programs for any platform that supports SDL and pygame since they are cross-platform!

Pygame

Pygame is a suite of cross-platform Python modules for creating video games. It contains sound and graphics libraries for use with the Python programming language.

Python's sys module contains methods and variables for manipulating many aspects of the Python runtime environment. It helps you work with the interpreter since it gives you access to variables and functions that work closely with it.

Handling Keyboards Inputs

Basic steps to handle keyboard input:

  • Import the necessary libraries.
  • Using the pygame display.set mode() function, create a display surface object.
  • Bring up the image/object.
  • Create a KEYDOWN click event.
  • Define all event keys and complete the task.
  • Make a pause event, such as KEYUP.
  • Using the blit() function of the pygame display surface object, copy the Text surface object to the display surface object.
  • The display.update() function of pygame shows the display surface object on the pygame window.
# importing all the required libraries
import pygame
from pygame.locals import *
from sys import exit

# initiating pygame library to use its
# required function
pygame.init()

#defining the width and height of windows/surfaces
sze = width, height = 740, 480
scrn = pygame.display.set_mode(sze)

# convert() creates a copy of the picture on the surface by loading a new # image from a file.
image = pygame.image.load("char.png").convert()

# declaring value to variables
x, y = 0, 0
mv_x, mv_y = 0, 0

while True:
for vnt in pygame.event.get():
if vnt.type == pygame.QUIT:
# pygame.QUIT deactivates pygame
exit()
# exit() is sys function used to
# kill the program

# KEYDOWN event will be triggered everytime
# we press a button
if vnt.type == KEYDOWN:

if vnt.key == K_LEFT:
mv_x = -0.3 # object moves -0.3 towards x axis
print("pressed LEFT")
elif vnt.key == K_RIGHT:
mv_x = +0.3 # object moves 0.3 towards x axis
print("pressed RIGHT")
elif vnt.key == K_UP:
mv_y = -0.3 # object moves -0.3 towards y axis
print("pressed UP")
elif vnt.key == K_DOWN:
mv_y = +0.3 # object moves 0.3 towards y axis
print("pressed DOWN")

# When we hit the left CTRL button, 
                # the K LCTRL event is triggered.
elif vnt.key == K_LCTRL:

# declaring new image file to update image
# everytime left CTRL is pressed
image = pygame.image.load("char1.png")
pygame.display.update() # update image
elif vnt.key == K_BACKSPACE:

# This is the default file we specified at the start, 
#and pressing backspace will restore it.
image = pygame.image.load("char.png")
pygame.display.update() # updated image

# When the left key is released, it will be activated.
if vnt.type == KEYUP:
if vnt.key == K_LEFT:
mv_x = 0 # movement stops
elif vnt.key == K_RIGHT:
mv_x = 0 # movement stops
elif vnt.key == K_UP:
mv_y = 0 # movement stops
elif vnt.key == K_DOWN:
mv_y = 0 # movements stops
"""When the keys are released and the x,y coordinates do not change, the KEYUP event is triggered."""

x += mv_x
y += mv_y
# changing x,y coordinate values
screen.fill((255, 255, 255))

# The function will generate a white backdrop.
screen.blit(img, (x, y))

# The blit() method copies an image to x,y coordinates..
pygame.display.update()
# draw the objects on screen
You can also try this code with Online Python Compiler
Run Code

OUTPUT

 

You can practice by yourself with the help of online python compiler for better understanding.

Handling Mouse Inputs:

Basic steps to take mouse input:

  • Import required libraries.
  • Using the pygame display.set mode() function, create a display surface object.
  • Bring up the image/object.
  • Create a MOUSEBUTTONDOWN click event.
  • Define all event keys and complete the task.
  • Create a MOUSEBUTTONUP pause event.
  • Using the blit() function of the pygame display surface object, copy the Text surface object to the display surface object.
  • The display.update() function of pygame shows the display surface object on the pygame window.
# importing all the required libraries
import pygame
from pygame.locals import *
from sys import exit

# launching the pygame library and using its features
pygame.init()

# defining the width and height of windows/surfaces
sze = width, height = 740, 480
screen = pygame.display.set_mode(sze)


# convert() creates a copy of the picture on the surface by loading a new # image from a file.
img = pygame.image.load("char.png").convert()

# declaring value to variables
clckng = False
rght_clckng = False
mddl_clck = False

while True:
Mx, My = pygame.mouse.get_pos() # the x,y coordinates of the 
# mouse
location = [Mx, My]
for vnt in pygame.event.get():
if vnt.type == pygame.QUIT:

# pygame.QUIT turns off pygame.
exit()
# exit() is a system function that terminates a programme.

# When a button is pushed, the MOUSEBUTTONDOWN event is fired.
if vnt.type == MOUSEBUTTONDOWN:

# When the mouse left button is pressed, it returns true.
if vnt.button == 1:
clckng = True

# declaring new image file to update image
# everytime left button clicking is true
image = pygame.image.load("char1.png")
pygame.display.update() # updated image

# When the mouse right button is pressed, it returns true.
if vnt.button == 3:
rght_clckng = True

# declaring new image file to update image
# everytime right button is clicked
image = pygame.image.load("char.png")
pygame.display.update() # updated image

# When the mouse's centre button is pressed, it returns true.
if vnt.button == 2:
mddl_clck = middle_click

# when the centre button is clicked, rescale the picture
image = pygame.transform.scale(img, (100, 100))
pygame.display.update() # update image

# When the mouse button is pressed, MOUSEBUTTONUP is activated.
# is released(not clicked)
if vnt.type == MOUSEBUTTONUP:
if vnt.button == 1:
clckng = False

screen.fill((255, 255, 255))

# the function will fill the background
# with white color
screen.blit(image, (location[0], location[1]))

# blit() function will copy image file
# to x,y coordinates.
pygame.display.update()
# draw the objects on screen
You can also try this code with Online Python Compiler
Run Code

Frequently Asked Questions.

How do you wait for input in pygame?

You may use the event.wait() function to wait for a key to be pressed. This is beneficial since it does not require considerable processing.pygame

import from pygame

What does Pygame quit () do?

The pygame. quit() method is similar to the pygame. init() function in that it executes code that disables the Pygame library. Always use pygame in your projects.

In Pygame, how do I rotate an image?

We use the pygame. transform. rotate(image, degree) function to turn the picture, where we supply the image to be rotated and the degree of rotation to be done.

How do you wait 5 seconds in Python?

If you have a Python application that has to wait, you may use the time function. sleep(x), where x is when you want your application to stay in seconds.

How do you input a key in Python?

Use the input() function to get Python user input from the keyboard. Press the enter key after entering the value. The program waits for user input indefinitely, there is no timeout. The input function returns a string, that you can store in a variable.

Conclusion

So that's the end of the article Input handling in pygame

After reading about the Input handling in pygame, are you not feeling excited to read/explore more articles on the topic of pygame? Don't worry; Coding Ninjas has you covered. 

However, you may want to pursue our premium courses to give your job an advantage over the competition!

Upskill yourself in Data Structures and Algorithms, Competitive Programming, JavaScript, System Design, and more with our Coding Ninjas Studio Guided Path! If you want to put your coding skills to the test, check out the mock test series and enter the contests on Coding Ninjas Studio! But if you've only recently started your schooling and are looking for answers to issues presented by digital titans like Amazon, Microsoft, Uber, and others. In this situation, you must consider the obstaclesinterview experiences, and interview package as part of your placement preparations. Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass