Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Turtle
  • Tkinter
  • Matplotlib
  • Python Imaging Library
  • Pyglet
  • Python
  • Numpy
  • Pandas
  • Python Database
  • Data Science With Python
  • Machine Learning with Python
  • Django
  • Flask
  • R
Open In App
Next Article:
Brick Breaker Game In Python using Pygame
Next article icon

Slide Puzzle using PyGame - Python

Last Updated : 26 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

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 to see how to create a slide puzzle in Pygame using Python.

Slide_game Python

Importing necessary modules 

Python3
# Code for the sliding puzzle game in python using pygame. import pygame import random import pyautogui from pygame.locals import * 

Call the main function 

  • The main() function is called to start the program i.e initialize the necessary variables
Python3
class Tiles:     # main method for initializing different variables     def __init__(self, screen, start_position_x,                   start_position_y,                   num, mat_pos_x,                   mat_pos_y):                self.color = (0, 255, 0)         # complete screen         self.screen = screen         # screen(x)         self.start_pos_x = start_position_x         # screen(y)         self.start_pos_y = start_position_y         # total nums         self.num = num         # width of each tile         self.width = tile_width         # depth of each tile(shadow)         self.depth = tile_depth         # tile selected false         self.selected = False         # matrix alignment from screen w.r.t x coordinate         self.position_x = mat_pos_x         # matrix alignment from screen w.r.t y coordinate         self.position_y = mat_pos_y         # tile movable false in its initial state         self.movable = False 

draw_tyle() method for drawing the tiles in the grid :

  • Draw rectangles using .rect(). Pass length, breadth, width & height to make the rectangle 
  • blit() will take that rectangular Surface and put it on top of the screen
Python3
# Draw tiles def draw_tyle(self):     pygame.draw.rect(self.screen,                       self.color,                       pygame.Rect(         self.start_pos_x, self.start_pos_y,                         self.width, self.depth))     numb = font.render(str(self.num), True,                         (125, 55, 100))     screen.blit(numb, (self.start_pos_x + 40,                         self.start_pos_y + 10)) 

mouse_hover() method for changing the color of a tile: 

  • mouse_hover() method for changing the color of a tile to white when the mouse hovers over the tile
Python3
# Mouse hover chnage the color of tiles def mouse_hover(self, x_m_motion, y_m_motion):     if x_m_motion > self.start_pos_x and x_m_motion < self.start_pos_x + self.width and y_m_motion > self.start_pos_y and y_m_motion < self.start_pos_y + self.depth:         self.color = (255, 255, 255)     else:         self.color = (255, 165, 0) 

mouse_click() method for selecting the tile: 

  • when the mouse clicks on a tile, the tile changes position with some depthless causing it to go below the main grid
Python3
# when  mouse  clicks check if a tile is selected or not def mouse_click(self, x_m_click, y_m_click):     if x_m_click > self.start_pos_x and x_m_click < self.start_pos_x + self.width and y_m_click > self.start_pos_y and y_m_click < self.start_pos_y + self.depth:         self.selected = True     else:         self.selected = False 

mouse_click_release() for checking whether the tile is released or not: 

  • when the mouse click is released unselect the tile by setting selected as  False 
Python3
# when mouse click released unselect the tile by setting False def mouse_click_release(self, x_m_click_rel, y_m_click_rel):     if x_m_click_rel > 0 and y_m_click_rel > 0:         self.selected = False 

move_tyle() method for moving the tiles with appropriate co-ords:

Python3
# Move the tile(i.e hower) def move_tyle(self, x_m_motion, y_m_motion):     self.start_pos_x = x_m_motion     self.start_pos_y = y_m_motion  # end of class 

create_tyles() method for creating tiles in the matrix:

  • Create tiles w.r.t to no of tiles available i.e in a 3x3 matrix the no of tiles will be 9(blank tile included) 
  • For puzzle-making, create tiles at random positions in the matrix. Once the position is fixed append the tile_no to that tile from the available tiles
  • Print the tiles in the grid 
Python3
# Create tiles w.r.t to no of tiles available def create_tyles():     i = 1     # create tiles at random positions     while i <= tile_count:         r = random.randint(1, tile_count)         if r not in tile_no:             tile_no.append(r)             i += 1     tile_no.append("")     k = 0     # print the tiles in the grid     for i in range(0, rows):         for j in range(0, cols):             if (i == rows - 1) and (j == cols - 1):                 pass             else:                 t = Tiles(screen, tile_print_position[(                     i, j)][0], tile_print_position[(i, j)][1],                            tile_no[k], i, j)                 tiles.append(t)             matrix[i][j] = tile_no[k]             k += 1     check_mobility() 

check_mobility() method for validating  positions: 

  • check if the tile can be placed in the required position where the player is trying to move the tile
Python3
# check if the tile can be placed # in the required position where # the player is trying to move the tile   def check_mobility():        for i in range(tile_count):         tile = tiles[i]         row_index = tile.position_x         col_index = tile.position_y         adjacent_cells = []         adjacent_cells.append([row_index-1, col_index, False])  # up         adjacent_cells.append([row_index+1, col_index, False])  # down         adjacent_cells.append([row_index, col_index-1, False])  # right         adjacent_cells.append([row_index, col_index+1, False])  # left                  for i in range(len(adjacent_cells)):             if (adjacent_cells[i][0] >= 0 and adjacent_cells[i][0] < rows)             and (adjacent_cells[i][1] >= 0 and adjacent_cells[i][1] < cols):                 adjacent_cells[i][2] = True          for j in range(len(adjacent_cells)):             if adjacent_cells[j][2]:                 adj_cell_row = adjacent_cells[j][0]                 adj_cell_col = adjacent_cells[j][1]                 for k in range(tile_count):                     if adj_cell_row == tiles[k].position_x                     and adj_cell_col == tiles[k].position_y:                         adjacent_cells[j][2] = False                  false_count = 0                  for m in range(len(adjacent_cells)):                     if adjacent_cells[m][2]:                         tile.movable = True                         break                     else:                         false_count += 1                  if false_count == 4:                     tile.movable = False 

isGameOver() method for checking whether the game is over or not:  

  • If after iterating the matrix the string we get is 12345678_ then the player has won("Game Over") and lock the tiles at that position
Python3
# if after iterating the matrix # the string we get is 12345678_ # then the player has won("Game Over")   def isGameOver():     global game_over, game_over_banner     allcelldata = ""     for i in range(rows):         for j in range(cols):             allcelldata = allcelldata + str(matrix[i][j])      if allcelldata == "12345678 ":         game_over = True         game_over_banner = "Game Over"          print("Game Over")         # lock the tiles at that position         for i in range(tile_count):             tiles[i].movable = False             tiles[i].selected = False 

Define the matrix with its size and some initial variables: 

  • Define the window screen dimension with the help of pyautogui.size() function.   
  • pyautogui.size() returns two integers in tuple(width, height) of the screen size, in pixels.
  • Define no of rows and columns of the matrix & print the tiles at appropriate positions
  • Then set the initial values for mouse_press , x_m_click, y_m_click, x_m_click_rel, y_m_click_rel, game_over, game_over_banner.
Python3
# Window dimension page_width, page_depth = pyautogui.size() page_width = int(page_width * .95) page_depth = int(page_depth * .95)  # tile dimensions tiles = [] tile_width = 200 tile_depth = 200  # no of rows & column i.e puzzle size rows, cols = (3, 3) tile_count = rows * cols - 1  # how many tiles should be created matrix = [["" for i in range(cols)] for j in range(rows)] tile_no = [] tile_print_position = {(0, 0): (100, 50),                        (0, 1): (305, 50),                        (0, 2): (510, 50),                        (1, 0): (100, 255),                        (1, 1): (305, 255),                        (1, 2): (510, 255),                        (2, 0): (100, 460),                        (2, 1): (305, 460),                        (2, 2): (510, 460)}  # initial values of variables mouse_press = False x_m_click, y_m_click = 0, 0 x_m_click_rel, y_m_click_rel = 0, 0 game_over = False game_over_banner = "" 

Initialize pygame module &  set the caption:

  • Initialize all the pygame modules with the help of pygame.init()
  • Now set the captions for texts and counter of counting the total number of moves.
Python3
# initialize pygame and set the caption pygame.init() game_over_font = pygame.font.Font('freesansbold.ttf', 70) move_count = 0 move_count_banner = "Moves : " move_count_font = pygame.font.Font('freesansbold.ttf', 40) screen = pygame.display.set_mode((page_width, page_depth)) pygame.display.set_caption("Slide Game") font = pygame.font.Font('freesansbold.ttf', 200)  # creation of tiles in the puzzle create_tyles() 

Making the puzzle by doing random moves: 

  • Set the running = True, it indicates that the player is playing the game 
  • Fill the window screen with black color then start drawing the GUI board and print the tiles at the GUI
  • Now render the total no of counts each time a new move is played
  • Now get the events triggered by the player with the help of pygame.event.get()
    • If the event is quit operation then terminate the program
    • If mouse clicks are detected then find (x,y) and then pass them to the mouse_hover method
    • If the tile is selected & mouse is pressed then pass the coords to the move_tyle method and it will move the tile to the desired location
      • If the desired location is down pass coords to mouse_click and settle the tile there if the conditions are satisfying. similarly for other conditions.
Python3
# main loop running = True  while running:      # fill with black color     screen.fill((0, 0, 0))          # start drawing the gui board of sliding puzzle     pygame.draw.rect(screen, (165, 42, 42),                      pygame.Rect(95, 45, 620, 620))     game_over_print = game_over_font.render(         game_over_banner, True, (255, 255, 0))          # blit() will take that rectangular     # Surface and put it on top of the screen.     screen.blit(game_over_print, (950, 100))      # render the move_count with the use of str     if move_count == 0:         move_count_render = move_count_font.render(             move_count_banner, True, (0, 255, 0))     else:         move_count_render = move_count_font.render(             move_count_banner + str(move_count), True, (0, 255, 0))     screen.blit(move_count_render, (1050, 200))      # Get events from the queue.     for event in pygame.event.get():         # if its quite operation then exit the while loop         if event.type == pygame.QUIT:             running = False                  # if mouse click are detected         # then find (x,y) and then pass         # them to mouse_hover method         if event.type == pygame.MOUSEMOTION:             x_m_motion, y_m_motion = pygame.mouse.get_pos()             for i in range(tile_count):                 tiles[i].mouse_hover(x_m_motion, y_m_motion)                          # if the tile is selected &             # mouse is pressed then pass             # the coords to move_tyle method             for i in range(tile_count):                 if tiles[i].selected and mouse_press:                     tiles[i].move_tyle(x_m_motion, y_m_motion)         # Moving tile downwards         if event.type == pygame.MOUSEBUTTONDOWN:             mouse_press = True             x_m_click, y_m_click = pygame.mouse.get_pos()             for i in range(tile_count):                 tiles[i].mouse_click(x_m_click, y_m_click)                  # Moving tile upwards         if event.type == pygame.MOUSEBUTTONUP:             mouse_press = False             x_m_click_rel, y_m_click_rel = pygame.mouse.get_pos()             x_m_click, y_m_click = 0, 0             cell_found = False             for i in range(0, rows):                 for j in range(0, cols):                     tile_start_pos_x = tile_print_position[(i, j)][0]                     tile_start_pos_y = tile_print_position[(i, j)][1]                      if (x_m_click_rel > tile_start_pos_x                         and x_m_click_rel < tile_start_pos_x + tile_width)                     and (y_m_click_rel > tile_start_pos_y                          and y_m_click_rel < tile_start_pos_y + tile_depth):                         if matrix[i][j] == "":                             for k in range(tile_count):                                 if game_over == False:                                     if tiles[k].selected:                                         if tiles[k].movable:                                             cell_found = True                                             dummy = matrix[tiles[k].position_x][tiles[k].position_y]                                             matrix[tiles[k].position_x][tiles[k].position_y] = matrix[i][j]                                             matrix[i][j] = dummy                                             tiles[k].position_x = i                                             tiles[k].position_y = j                                             tiles[k].start_pos_x = tile_print_position[(                                                 i, j)][0]                                             tiles[k].start_pos_y = tile_print_position[(                                                 i, j)][1]                                             move_count += 1                                             isGameOver()                                             check_mobility()                      if cell_found == False:                         for k in range(tile_count):                             if tiles[k].selected:                                 mat_pos_x = tiles[k].position_x                                 mat_pos_y = tiles[k].position_y                                 tiles[k].start_pos_x = tile_print_position[(                                     mat_pos_x, mat_pos_y)][0]                                 tiles[k].start_pos_y = tile_print_position[(                                     mat_pos_x, mat_pos_y)][1]                                 break 

Traversing & updating of tiles :

  • Traverse all the tiles and draw them
  • After drawing update them on the screen with the help of pygame.display.flip() 
  • pygame.display.flip(): Allows only a portion of the screen to update, instead of the entire area, 
Python3
for i in range(tile_count):   tiles[i].draw_tyle()   pygame.display.flip() 

Update the window of game: 

  • Now update the whole window of the game using pygame.display.update()
  • pygame.display.update(): If no argument is passed it updates the entire window area(This is the case of the below code).
Python3
# Update the whole screen pygame.display.update() 

Complete source code: 

Python3
import pygame import random import pyautogui from pygame.locals import *   class Tiles:     # main method for initializing different variables     def __init__(self, screen, start_position_x,                   start_position_y, num, mat_pos_x, mat_pos_y):         self.color = (0, 255, 0)         self.screen = screen         self.start_pos_x = start_position_x         self.start_pos_y = start_position_y         self.num = num         self.width = tile_width         self.depth = tile_depth         self.selected = False         self.position_x = mat_pos_x         self.position_y = mat_pos_y         self.movable = False          # Draw tiles     def draw_tyle(self):         pygame.draw.rect(self.screen, self.color, pygame.Rect(             self.start_pos_x, self.start_pos_y, self.width, self.depth))         numb = font.render(str(self.num), True, (125, 55, 100))         screen.blit(numb, (self.start_pos_x + 40, self.start_pos_y + 10))          # Mouse hover chnage the color of tiles     def mouse_hover(self, x_m_motion, y_m_motion):         if x_m_motion > self.start_pos_x and x_m_motion < self.start_pos_x + self.width and y_m_motion > self.start_pos_y and y_m_motion < self.start_pos_y + self.depth:             self.color = (255, 255, 255)         else:             self.color = (255, 165, 0)          # when  mouse  clicks check if a tile is selected or not     def mouse_click(self, x_m_click, y_m_click):         if x_m_click > self.start_pos_x and x_m_click < self.start_pos_x + self.width and y_m_click > self.start_pos_y and y_m_click < self.start_pos_y + self.depth:             self.selected = True         else:             self.selected = False          # when mouse click released unselect the tile by setting False     def mouse_click_release(self, x_m_click_rel, y_m_click_rel):         if x_m_click_rel > 0 and y_m_click_rel > 0:             self.selected = False          # Move the tile(i.e hower)     def move_tyle(self, x_m_motion, y_m_motion):         self.start_pos_x = x_m_motion         self.start_pos_y = y_m_motion  # Create tiles w.r.t to no of tiles available   def create_tyles():     i = 1     while i <= tile_count:         r = random.randint(1, tile_count)         if r not in tile_no:             tile_no.append(r)             i += 1     tile_no.append("")     k = 0     for i in range(0, rows):         for j in range(0, cols):             if (i == rows - 1) and (j == cols - 1):                 pass             else:                 t = Tiles(screen, tile_print_position[(                     i, j)][0], tile_print_position[(i, j)][1],                           tile_no[k], i, j)                 tiles.append(t)             matrix[i][j] = tile_no[k]             k += 1     check_mobility()  # check if the tile can be places on the # required position where the # player is trying to move the tile   def check_mobility():     for i in range(tile_count):         tile = tiles[i]         row_index = tile.position_x         col_index = tile.position_y         adjacent_cells = []         adjacent_cells.append([row_index-1, col_index, False])  # up         adjacent_cells.append([row_index+1, col_index, False])  # down         adjacent_cells.append([row_index, col_index-1, False])  # right         adjacent_cells.append([row_index, col_index+1, False])  # left         for i in range(len(adjacent_cells)):             if (adjacent_cells[i][0] >= 0 and adjacent_cells[i][0] < rows) and (adjacent_cells[i][1] >= 0 and adjacent_cells[i][1] < cols):                 adjacent_cells[i][2] = True          for j in range(len(adjacent_cells)):             if adjacent_cells[j][2]:                 adj_cell_row = adjacent_cells[j][0]                 adj_cell_col = adjacent_cells[j][1]                 for k in range(tile_count):                     if adj_cell_row == tiles[k].position_x and adj_cell_col == tiles[k].position_y:                         adjacent_cells[j][2] = False                  false_count = 0                  for m in range(len(adjacent_cells)):                     if adjacent_cells[m][2]:                         tile.movable = True                         break                     else:                         false_count += 1                  if false_count == 4:                     tile.movable = False  # if after iterating the matrix the # string we get is 12345678_ then # the player has won("Game Over")   def isGameOver():     global game_over, game_over_banner     allcelldata = ""     for i in range(rows):         for j in range(cols):             allcelldata = allcelldata + str(matrix[i][j])      if allcelldata == "12345678 ":         game_over = True         game_over_banner = "Game Over"          print("Game Over")          for i in range(tile_count):             tiles[i].movable = False             tiles[i].selected = False   # Window dimension page_width, page_depth = pyautogui.size() page_width = int(page_width * .95) page_depth = int(page_depth * .95)  # tile dimensions tiles = [] tile_width = 200 tile_depth = 200  # no of rows & column i.e puzzle size rows, cols = (3, 3) tile_count = rows * cols - 1  # how many tiles should be created matrix = [["" for i in range(cols)] for j in range(rows)] tile_no = [] tile_print_position = {(0, 0): (100, 50),                        (0, 1): (305, 50),                        (0, 2): (510, 50),                        (1, 0): (100, 255),                        (1, 1): (305, 255),                        (1, 2): (510, 255),                        (2, 0): (100, 460),                        (2, 1): (305, 460),                        (2, 2): (510, 460)}  # initial values of variables mouse_press = False x_m_click, y_m_click = 0, 0 x_m_click_rel, y_m_click_rel = 0, 0 game_over = False game_over_banner = ""  # initialize pygame and set the caption pygame.init() game_over_font = pygame.font.Font('freesansbold.ttf', 70) move_count = 0 move_count_banner = "Moves : " move_count_font = pygame.font.Font('freesansbold.ttf', 40) screen = pygame.display.set_mode((page_width, page_depth)) pygame.display.set_caption("Slide Game") font = pygame.font.Font('freesansbold.ttf', 200)  # creation of tiles in the puzzle create_tyles()  running = True while running:     screen.fill((0, 0, 0))  # fill with black color     # start drawing the gui board of sliding puzzle     pygame.draw.rect(screen, (165, 42, 42), pygame.Rect(95, 45, 620, 620))     game_over_print = game_over_font.render(         game_over_banner, True, (255, 255, 0))          # blit() will take that rectangular Surface     # and put it on top of the screen.     screen.blit(game_over_print, (950, 100))      # render the move_count with the use of str     if move_count == 0:         move_count_render = move_count_font.render(             move_count_banner, True, (0, 255, 0))     else:         move_count_render = move_count_font.render(             move_count_banner + str(move_count), True, (0, 255, 0))     screen.blit(move_count_render, (1050, 200))      # Get events from the queue.     for event in pygame.event.get():         # if its quite operation then exit the while loop         if event.type == pygame.QUIT:             running = False         # if mouse click are detected then find (x,y)         # and then pass them to mouse_hover method         if event.type == pygame.MOUSEMOTION:             x_m_motion, y_m_motion = pygame.mouse.get_pos()             for i in range(tile_count):                 tiles[i].mouse_hover(x_m_motion, y_m_motion)             # if the tile is selected & mouse is pressed             # then pass the coords to move_tyle method             for i in range(tile_count):                 if tiles[i].selected and mouse_press:                     tiles[i].move_tyle(x_m_motion, y_m_motion)         # Moving tile downwards         if event.type == pygame.MOUSEBUTTONDOWN:             mouse_press = True             x_m_click, y_m_click = pygame.mouse.get_pos()             for i in range(tile_count):                 tiles[i].mouse_click(x_m_click, y_m_click)         # Moving tile upwards         if event.type == pygame.MOUSEBUTTONUP:             mouse_press = False             x_m_click_rel, y_m_click_rel = pygame.mouse.get_pos()             x_m_click, y_m_click = 0, 0             cell_found = False             for i in range(0, rows):                 for j in range(0, cols):                     tile_start_pos_x = tile_print_position[(i, j)][0]                     tile_start_pos_y = tile_print_position[(i, j)][1]                      if (x_m_click_rel > tile_start_pos_x and x_m_click_rel < tile_start_pos_x + tile_width) and (y_m_click_rel > tile_start_pos_y and y_m_click_rel < tile_start_pos_y + tile_depth):                         if matrix[i][j] == "":                             for k in range(tile_count):                                 if game_over == False:                                     if tiles[k].selected:                                         if tiles[k].movable:                                             cell_found = True                                             dummy = matrix[tiles[k].position_x][tiles[k].position_y]                                             matrix[tiles[k].position_x][tiles[k].position_y] = matrix[i][j]                                             matrix[i][j] = dummy                                             tiles[k].position_x = i                                             tiles[k].position_y = j                                             tiles[k].start_pos_x = tile_print_position[(                                                 i, j)][0]                                             tiles[k].start_pos_y = tile_print_position[(                                                 i, j)][1]                                             move_count += 1                                             isGameOver()                                             check_mobility()                      if cell_found == False:                         for k in range(tile_count):                             if tiles[k].selected:                                 mat_pos_x = tiles[k].position_x                                 mat_pos_y = tiles[k].position_y                                 tiles[k].start_pos_x = tile_print_position[(                                     mat_pos_x, mat_pos_y)][0]                                 tiles[k].start_pos_y = tile_print_position[(                                     mat_pos_x, mat_pos_y)][1]                                 break      for i in range(tile_count):         tiles[i].draw_tyle()     # allows only a portion of the screen to updated,     # instead of the entire area,     # If no argument is passed it     # updates the entire Surface area like pygame.     pygame.display.flip() # Update the whole screen pygame.display.update() 

Output : 


Next Article
Brick Breaker Game In Python using Pygame
author
cosmic
Improve
Article Tags :
  • Technical Scripter
  • Python
  • Technical Scripter 2022
  • Python-PyGame
Practice Tags :
  • python

Similar Reads

  • PyGame Tutorial
    Pygame is a free and open-source library for making games and multimedia applications in Python. It helps us create 2D games by giving us tools to handle graphics, sounds and user input (like keyboard and mouse events) without needing to dig deep into complex stuff like graphics engines. Release dat
    7 min read
  • Introduction

    • Introduction to pygame
      Pygame is a set of Python modules designed for writing video games. It adds functionality on top of the excellent SDL library, enabling you to create fully-featured games and multimedia programs in the Python language. It's key benefits include: Beginner-Friendly: Simple Python syntax makes it ideal
      4 min read

    • Getting Started with Pygame
      Pygame is a free-to-use and open-source set of Python Modules.  And as the name suggests, it can be used to build games. You can code the games and then use specific commands to change it into an executable file that you can share with your friends to show them the work you have been doing.  It incl
      3 min read

    • How to Install Pygame on Windows ?
      In this article, we will learn how to Install PyGame module of Python on Windows. PyGame is a library of python language. It is used to develop 2-D games and is a platform where you can set python modules to develop a game. It is a user-friendly platform that helps to build games quickly and easily.
      2 min read

    • Install Pygame in MacOS
      PyGame is a collection of modules that break through the language of Python applications. These modules are designed to edit video games. PyGame, therefore, includes computer graphics and audio libraries created for the use and language of Python programs. At first, open the Terminal which is locate
      1 min read

    • Interesting Facts about PYGAME
      Pygame is a set of python module which is used in designing video games. In Pygame, there are computer graphics and sound libraries in order to develop high quality and user interactive games. Pygame was developed by Pete Shinners. Till 2000, it was a community project, later on it was released unde
      2 min read

    Getting Started

    • PyGame - Import and Initialize
      In this article, we will see how to import and initialize PyGame. Installation The best way to install pygame is with the pip tool, we can install pygame by using the below command: pip install pygameImporting the Pygame library To import the pygame library, make sure you have installed pygame alrea
      2 min read

    • How to initialize all the imported modules in PyGame?
      PyGame is Python library designed for game development. PyGame is built on the top of SDL library so it provides full functionality to develop game in Python. Pygame has many modules to perform it's operation, before these modules can be used, they must be initialized. All the modules can be initial
      2 min read

    • How to create an empty PyGame window?
      Pygame window is a simple window like any other window, in which we display our game screen. It is the first task we do so that we can display our output onto something. Our main goal here is to create a window and keep it running unless the user wants to quit. To perform these tasks first we need t
      2 min read

    • How to get the size of PyGame Window?
      In this article, we will learn How to get the size of a PyGame Window.  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
      2 min read

    • Allowing resizing window in PyGame
      In this article, we will learn How to allow resizing a PyGame Window.  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
      2 min read

    • How to change screen background color in Pygame?
      Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.init(): This function is used to initialize all the pygame
      1 min read

    • How to Change the Name of a Pygame window?
      PyGame window is a simple window that displays our game on the window screen. By default, pygame uses "Pygame window" as its title and pygame icon as its logo for pygame window. We can use set_caption() function to change the name and set_icon() to set icon of our window. To change the name of pygam
      2 min read

    • How to set up the Game Loop in PygGame ?
      In this article, we will see how to set up a game loop in PyGame. Game Loop is the loop that keeps the game running. It keeps running till the user wants to exit. While the game loop is running it mainly does the following tasks: Update our game window to show visual changesUpdate our game states ba
      3 min read

    • How to change the PyGame icon?
      While building a video game, do you wish to set your image or company's logo as the icon for a game? If yes, then you can do it easily by using set_icon() function after declaring the image you wish to set as an icon. Read the article given below to know more in detail.  Syntax: pygame_icon = pygame
      2 min read

    • Pygame - Surface
      When using Pygame, surfaces are generally used to represent the appearance of the object and its position on the screen. All the objects, text, images that we create in Pygame are created using surfaces. Creating a surface Creating surfaces in pygame is quite easy. We just have to pass the height an
      7 min read

    • Pygame - Time
      While using pygame we sometimes need to perform certain operations that include the usage of time. Like finding how much time our program has been running, pausing the program for an amount of time, etc. For operations of this kind, we need to use the time methods of pygame. In this article, we will
      4 min read

    Drawing Shapes

    • Pygame – Drawing Objects and Shapes
      In this article, we are going to see how to draw an object using Pygame. There can be two versions for drawing any shape, it can be a solid one or just an outline of it. Drawing Objects and Shapes in PyGame You can easily draw basic shapes in pygame using the draw method of pygame.  Drawing Rectangl
      10 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 th
      3 min read

    • How to draw rectangle in Pygame?
      Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. Functions Used: pygame.display.set_mode(): This function is used to initialize a s
      2 min read

    • How to draw a rectangle with rounded corner in PyGame?
      Pygame is a Python library designed to develop video games. Pygame adds functionality on top of the excellent SDL library. This allows you to create fully featured games and multimedia programs in the python language. In this article, we will see how can we draw a rectangle with rounded corners in P
      2 min read

    Event Handling

    • How to add Custom Events in Pygame?
      In this article, we will see how to add custom events in PyGame.  Installation PyGame library can be installed using the below command: pip install pygame Although PyGame comes with a set of events (Eg: KEYDOWN and KEYUP), it allows us to create our own additional custom events according to the requ
      4 min read

    • How to get keyboard input in PyGame ?
      While using pygame module of Python, we sometimes need to use the keyboard input for various operations such as moving a character in a certain direction. To achieve this, we have to see all the events happening. Pygame keeps track of events that occur, which we can see with the events.get() functio
      3 min read

    Working with Text

    • Pygame - Working with Text
      In this article, we will see how to play with texts using the Pygame module. We will be dealing here with initializing the font, rendering the text, editing the text using the keyboard, and adding a blinking cursor note.  Installation To install this module type the below command in the terminal. pi
      5 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 usin
      6 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 wri
      3 min read

    Working with images

    • 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 usin
      2 min read

    • Getting width and height of an image in Pygame
      Prerequisites: Pygame To use graphics in python programs we use a module called Pygame. Pygame provides high functionality for developing games and graphics in Python. Nowadays Pygame are very much popular to build simple 2D games. In order to run a program written in Python using Pygame module, a s
      3 min read

    • How to Rotate and Scale images using PyGame ?
      In this article, we are going to see how to Rotate and Scale the image. Image Scaling refers to the resizing of the original image and Image Rotation refers to turning off an image with some angle. Rotations in the coordinate plane are counterclockwise. Let's proceed with the methods used and the co
      3 min read

    • Pygame - Flip the image
      In this article, we are going to see how images can be flipped using Pygame. To flip the image we need to use pygame.transform.flip(Surface, xbool, ybool) method which is called to flip the image in vertical direction or horizontal direction according to our needs. Syntax: pygame.transform.flip(Surf
      2 min read

    • How to move an image with the mouse in PyGame?
      Pygame is a Python library that is used to create cross-platform video games. The games created by Pygame can be easily run through any of the input devices such as a mouse, keyboard, and joystick. Do you want to make a game that runs through mouse controls? Don't you know how to move the image with
      4 min read

    • How to use the mouse to scale and rotate an image in PyGame ?
      In this article, we will discuss how to transform the image i.e (scaling and rotating images) using the mouse in Pygame. Approach Step 1: First, import the libraries Pygame and math. import pygame import math from pygame.locals import * Step 2: Now, take the colors as input that we want to use in th
      5 min read

    PyGame Advance

    • How to create Buttons in a game using PyGame?
      Pygame is a Python library that can be used specifically to design and build games. Pygame only supports 2D games that are build using different shapes/images called sprites. Pygame is not particularly best for designing games as it is very complex to use and lacks a proper GUI like unity gaming eng
      3 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 th
      3 min read

    • Moving an object in PyGame - Python
      To make a game or animation in Python using PyGame, moving an object on the screen is one of the first things to learn. We will see 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
      2 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 th
      3 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 revers
      5 min read

    • Collision Detection in PyGame
      Prerequisite: Introduction to pygame Collision detection is a very often concept and used in almost games such as ping pong games, space invaders, etc. The simple and straight forward concept is to match up the coordinates of the two objects and set a condition for the happening of collision. In thi
      7 min read

    • Pygame - Creating Sprites
      Sprites are objects, with different properties like height, width, color, etc., and methods like moving right, left, up and down, jump, etc. In this article, we are looking to create an object in which users can control that object and move it forward, backward, up, and down using arrow keys. Let fi
      2 min read

    • Pygame - Control Sprites
      In this article, we will discuss how to control the sprite, like moving forward, backward, slow, or accelerate, and some of the properties that sprite should have. We will be adding event handlers to our program to respond to keystroke events, when the player uses the arrow keys on the keyboard we w
      4 min read

    • How to add color breezing effect using pygame?
      Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use and doesn’t have a proper GUI like unity but it definitely builds
      2 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 doin
      2 min read

    Exercise, Applications, and Projects

    • 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. Importin
      3 min read

    • Rhodonea Curves and Maurer Rose in Python
      In this article, we will create a Rhodonea Curve and Maurer Rose pattern in Python! Before we proceed to look at what exactly is a rhodonea curve or maurer rose we need to get the basic structure of our program ready! Basic Structure of the Program - Before we move on to learn anything about Rhodone
      7 min read

    • Creating start Menu in Pygame
      Pygame is a Python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different shapes or sprites. Pygame doesn't have an in-built layout design or any in-built UI system this means there is no easy way to make UI or levels for a game.
      3 min read

    • Tic Tac Toe GUI In Python using PyGame
      This article will guide you and give you a basic idea of designing a game Tic Tac Toe using pygame library of Python. 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 l
      15+ 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 beginne
      15+ min read

    • 8-bit game using pygame
      Pygame is a python library that can be used specifically to design and build games. Pygame supports only 2d games that are built using different sprites. Pygame is not particularly best for designing games as it is very complex to use doesn’t have a proper GUI like unity but it definitely builds log
      9 min read

    • Bubble sort visualizer using PyGame
      In this article we will see how we can visualize the bubble sort algorithm using PyGame i.e when the pygame application get started we can see the unsorted bars with different heights and when we click space bar key it started getting arranging in bubble sort manner i.e after every iteration maximum
      3 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 s
      5 min read

    • Sorting algorithm visualization : Heap Sort
      An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
      4 min read

    • Sorting algorithm visualization : Insertion Sort
      An algorithm like Insertion Sort can be understood easily by visualizing. In this article, a program that visualizes the Insertion Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in python using pygame library. Approach: Generate random array and fill the pygame
      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 sor
      4 min read

    • Building and visualizing Sudoku Game Using Pygame
      Sudoku is a logic-based, combinatorial number-placement puzzle. The objective is to fill a 9×9 grid with digits so that each column, each row, and each of the nine 3×3 subgrids that compose the grid contain all of the digits from 1 to 9. We will be building the Sudoku Game in python using pygame lib
      7 min read

    • Create Bingo Game Using Python
      A card with a grid of numbers on it is used to play the popular dice game of bingo. Players check off numbers on their cards when they are selected at random by a caller, competing to be the first to mark off all of their numbers in a particular order. We'll examine how to utilise Python to create a
      9 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
      9 min read

    • Car Race Game In PyGame
      In this article, we will see how to create a racing car game in Python using Pygame. In this game, we will have functionality like driving, obstacle crashing, speed increment when levels are passed, pause, countdown, scoreboard, and Instruction manual screen.  Required Modules: Before going any furt
      15+ min read

    • Spiral Sprint Game in Python Using Pygame
      In this article, we will see how to create a spiral sprint game in Python using Pygame. In this game, we will have functionality like difficulty modes, obstacle crashing, speed increment when points are increased, scoreboard, Particle animation, color-changing orbits, coins, and game sounds. Spiral
      15+ min read

    • Selection sort visualizer using PyGame
      In this article, we will see how to visualize Selection sort using a Python library PyGame. It is easy for the human brain to understand algorithms with the help of visualization. Selection sort is a simple and easy-to-understand algorithm that is used to sort elements of an array by dividing the ar
      4 min read

    • Mouse Clicks on Sprites in PyGame
      The interactiveness of your game can be significantly increased by using Pygame to respond to mouse clicks on sprites. You may develop unique sprite classes that manage mouse events and react to mouse clicks with the aid of Pygame's sprite module. This article will teach you how to use Pygame to mak
      3 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 n
      15 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 th
      14 min read

    • Hover Button in Pygame
      Here, we will talk about while hovering over the button different actions will perform like background color, text size, font color, etc. will change. In this article we are going to create a button using the sprites Pygame module of Python then, when hovering over that button we will perform an eve
      6 min read

    • Create a Pong Game in Python - Pygame
      Pong is a table tennis-themed 2-player 2D arcade video game developed in the early 1970s. The game consists of two paddles/strikers, located at the left and right edges of the screen, and a ball. Create a Pong Game in PythonThe basic theme of this game is to make sure that the ball doesn't hit the w
      10 min read

    • Save/load game Function in Pygame
      Pygame is a free-to-use and open-source set of Python Modules.  And as the name suggests, it can be used to build games, and to save game data or the last position of the player you need to store the position of the player in a file so when a user resumes the game its game resumes when he left. In t
      4 min read

geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences