The Wayback Machine - https://web.archive.org/web/20240820135933/https://www.geeksforgeeks.org/python-moving-an-object-in-pygame/
Open In App

Python – Moving an object in PyGame

Last Updated : 17 Nov, 2022
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit.

In this tutorial, we are going to learn how to move an object such that it moves horizontally when pressing the right arrow key or left arrow key on the keyboard and it moves vertically when pressing up arrow key or down arrow key.

The main concept of doing this is by changing the co-ordinates of the object and refreshing the screen. When the screen refreshes every time window color gets filled with original color and the new rectangle is formed, so when arrow keys get pressed co-ordinates changes and it appears that the object is moving.

Change in Co-ordinates for respective keys pressed :

Left arrow key: Decrement in x co-ordinate
Right arrow key: Increment in x co-ordinate
Up arrow key: Decrement in y co-ordinate
Down arrow key: Increment in y co-ordinate

Below is the implementation.




# import pygame module in this program 
import pygame
  
# activate the pygame library .  
# initiate pygame and give permission  
# to use pygame's functionality.  
pygame.init()
  
# create the display surface object  
# of specific dimension..e(500, 500).  
win = pygame.display.set_mode((500, 500))
  
# set the pygame window name 
pygame.display.set_caption("Moving rectangle")
  
# object current co-ordinates 
x = 200
y = 200
  
# dimensions of the object 
width = 20
height = 20
  
# velocity / speed of movement
vel = 10
  
# Indicates pygame is running
run = True
  
# infinite loop 
while run:
    # creates time delay of 10ms 
    pygame.time.delay(10)
      
    # iterate over the list of Event objects  
    # that was returned by pygame.event.get() method.  
    for event in pygame.event.get():
          
        # if event object type is QUIT  
        # then quitting the pygame  
        # and program both.  
        if event.type == pygame.QUIT:
              
            # it will make exit the while loop 
            run = False
    # stores keys pressed 
    keys = pygame.key.get_pressed()
      
    # if left arrow key is pressed
    if keys[pygame.K_LEFT] and x>0:
          
        # decrement in x co-ordinate
        x -= vel
          
    # if left arrow key is pressed
    if keys[pygame.K_RIGHT] and x<500-width:
          
        # increment in x co-ordinate
        x += vel
         
    # if left arrow key is pressed   
    if keys[pygame.K_UP] and y>0:
          
        # decrement in y co-ordinate
        y -= vel
          
    # if left arrow key is pressed   
    if keys[pygame.K_DOWN] and y<500-height:
        # increment in y co-ordinate
        y += vel
         
              
    # completely fill the surface object  
    # with black colour  
    win.fill((0, 0, 0))
      
    # drawing object on screen which is rectangle here 
    pygame.draw.rect(win, (255, 0, 0), (x, y, width, height))
      
    # it refreshes the window
    pygame.display.update() 
  
# closes the pygame window 
pygame.quit()




Previous Article
Next Article

Similar Reads

Adding Collisions Using pygame.Rect.colliderect in Pygame
Prerequisite: Drawing shapes in Pygame, Introduction to pygame In this article, we are going to use pygame.Rect.colliderect for adding collision in a shape using Pygame in Python. We can easily add collisions in Pygame shapes using the colliderect( ). For this, we are going to draw two rectangles then we will check if the rectangles are colliding o
3 min read
How to add moving platforms in PyGame
Prerequisite: Drawing in Pygame In this article, we will learn how we can add moving platforms to our game using PyGame in Python. Creating a Platform We can easily create any type of platform in pygame using the draw( ) method. For this, we will create react with specific width and height using the draw.rect() function. Syntax: pygame.draw.rect(su
5 min read
Python | Making an object jump in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. So, in this article, we will learn how
3 min read
Draw moving object using Turtle in Python
Prerequisite: Python Turtle Basics Turtle is an inbuilt module in python. It provides drawing using a screen (cardboard) and turtle (pen). To draw something on the screen, we need to move the turtle. To move turtle, there are some functions i.e forward(), backward(), etc. 1.)Move the Object (ball) : Following steps are used: Import Turtle package.S
2 min read
Pygame - Random Movement of Object
Prerequisite: How to draw rectangle in Pygame? In this article, we will learn how we can add random movements in objects using PyGame in Python. Random movement in a single object To add random movement in our object we are going to use randint method of the random module. Syntax: random.randint(a, b) Parameters: a and b : Two integers Returns: Ret
6 min read
Adding Boundary to an Object in Pygame
Boundaries to any game are very important. In snake games, space invaders, ping pong game, etc. the boundary condition is very important. The ball bounces at the boundaries of the screen in ping pong games. So, the idea behind this boundaries is to change the position of the ball or object in reverse direction as soon as it hits the wall. Let us se
5 min read
Python | Display images with PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip in
2 min read
Python | Display text to PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of the developer, what type of game he/she wants to develop using this toolkit.. Command to install pygame on wind
6 min read
Python | Drawing different shapes on PyGame window
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. Command to install pygame : pip instal
3 min read
Python | Playing audio file in Pygame
Game programming is very rewarding nowadays and it can also be used in advertising and as a teaching tool too. Game development includes mathematics, logic, physics, AI and much more and it can be amazingly fun. In python, game programming is done in pygame and it is one of the best modules for doing so. Note: For more information, refer to Introdu
2 min read
Slide Puzzle using PyGame - Python
Slide Puzzle game is a 2-dimensional game i.e the pieces can only be removed inside the grid and reconfigured by sliding them into an empty spot. The slide puzzle game developed here is a 3X3 grid game i.e 9 cells will be there from 1 to 8(9 is not here since a blank cell is needed for sliding the neighboring cells). In this article, we are going t
15 min read
Python - Drawing design using arrow keys in PyGame
Pygame is a cross-platform set of Python modules designed for writing video games. It includes computer graphics and sound libraries designed to be used with the Python programming language. Now, it’s up to the imagination or necessity of developer, what type of game he/she wants to develop using this toolkit. In this article we will see how we can
3 min read
Binary Search Visualization using Pygame in Python
An algorithm like Binary Search can be understood easily by visualizing. In this article, a program that visualizes the Binary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with ba
4 min read
Ternary Search Visualization using Pygame in Python
An algorithm like Ternary Search can be understood easily by visualizing. In this article, a program that visualizes the Ternary Search Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach Generate random array, sort it using any sorting algorithm, and fill the pygame window with
5 min read
Snowfall display using Pygame in Python
Not everybody must have witnessed Snowfall personally but wait a minute, What if you can see the snowfall right on your screen by just a few lines of creativity and Programming. Before starting the topic, it is highly recommended revising the basics of Pygame. Steps for snowfall creation 1. Importing modules First, we need to import the Pygame modu
3 min read
Difference between Pygame VS Arcade Library in Python
Game programming is very rewarding nowadays and it can also be used in advertising or as a teaching tool. Game development encompasses mathematics, logic, physics, AI, and much more and it can be amazingly fun. In Python, up until now, Pygame library was employed for the same, but there is a new module: Arcade Library. Here we will discuss how they
3 min read
Building Space Invaders Using PyGame - Python
In this article, we're going to build a Space Bullet shooter game using PyGame in Python. The used file can be downloaded from here. Approach: Import the required module.Initialize the pygame.Create three functions:isCollision(): Which tells us whether the collision has occurred or not?game_over(): Which returns True or False on the basis of which
13 min read
How to create MS Paint clone with Python and PyGame?
In this article, we will create a simple MS paint program with Python and PyGame. MS Paint is a simple program made by Microsoft, it allows users to create basic art and painting. Since its inception, MS Paint has been included with every version of Microsoft Windows. MS Paint provides features for drawing and painting in color and tools to create
9 min read
Differences Between Pyglet and Pygame in Python
In this article, we will see the difference between Pygame and Pyglet gaming libraries. What is Pyglet? Pyglet is a cross-platform window and media library for Python, intended for developing games and other visually rich applications. It supports windows, UI event handling, gamepads, OpenGL graphics, image and video loading, and sound and music pl
4 min read
Brick Breaker Game In Python using Pygame
Brick Breaker is a 2D arcade video game developed in the 1990s. The game consists of a paddle/striker located at the bottom end of the screen, a ball, and many blocks above the striker. The basic theme of this game is to break the blocks with the ball using the striker. The score is calculated by the number of blocks broken and each time the player
14 min read
Create Settings Menu in Python - Pygame
Python is a flexible programming language with a large selection of libraries and modules for a variety of applications. Pygame menu is one such toolkit that enables programmers to design graphical user interfaces for games and apps. In this tutorial, we'll look at how to use the pygame menu package to build a simple options menu. Users will have c
9 min read
Build a Music Player with Tkinter and Pygame in Python
We all use music players like Windows Media Player or VLC to play music on our system. Have you ever wanted to create your own music player if your answer is yes then with Python, you can build a customized Music Player. In this article, you will see how to build a simple yet functional music player using two powerful Python libraries: Tkinter and
7 min read
Create a "Play Again" Option with Python Pygame
Adding a "Play Again" feature to your Snake game using Python's Pygame module involves several steps. Game Variables Reset: restart_game method resets the snake, food, direction, and game over flag.Game Over Display: show_game_over method displays a message and a button to restart the game.Event Binding: We bind the keyboard events to control the s
6 min read
Snake Game in Python - Using Pygame module
Snake game is one of the most popular arcade games of all time. In this game, the main objective of the player is to catch the maximum number of fruits without hitting the wall or itself. Creating a snake game can be taken as a challenge while learning Python or Pygame. It is one of the best beginner-friendly projects that every novice programmer s
15+ min read
Dodger Game using Pygame in Python
A Dodger game is a type of game in which a player has access to control an object or any character to dodge (to avoid) upcoming obstacles and earn points according to the number of items dodged if the player is not able to dodge the object the game will be over and final score will be displayed in the console. After certain points or times the spee
5 min read
Python Tkinter | Moving objects using Canvas.move() method
The Canvas class of Tkinter supports functions that are used to move objects from one position to another in any canvas or Tkinter top-level. Syntax: Canvas.move(canvas_object, x, y)Parameters: canvas_object is any valid image or drawing created with the help of Canvas class. To know how to create object using Canvas class take reference of this. x
2 min read
Python Arcade - Adding Moving Platforms
In this article, we will discuss how to add moving platforms to our arcade games in Python. Adding Moving Platform We can easily add moving platforms in our arcade game by following the below steps: Create 2 new variables for sprite and velocity of moving platform.self.moving_vel = 3 self.moving_platform = NoneLoad the sprite and add the initial co
4 min read
How to Calculate an Exponential Moving Average in Python?
Moving Averages are financial indicators which are used to analyze stock values over a long period of time. i.e. Average value for that long period is calculated. Exponential Moving Averages (EMA) is a type of Moving Averages. It helps users to filter noise and produce a smooth curve. In Moving Averages 2 are very popular. Simple Moving AverageExpo
3 min read
How to Calculate Moving Averages in Python?
In this discussion we are going to see how to Calculate Moving Averages in Python in this discussion we will write a proper explanation What is Moving Averages?Moving Averages, a statistical method in data analysis, smooths fluctuations in time-series data to reveal underlying trends. Calculating the average within a specified window and shifting i
11 min read
How to create a text input box with Pygame?
In this article, we will discuss how to create a text input box using PyGame. Installation Before initializing pygame library we need to install it. This library can be installed into the system by using pip tool that is provided by Python for its library installation. Pygame can be installed by writing these lines into the terminal. We can install
3 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg