Python Sliding Puzzle Game — Crack the Code, Solve the Slide

Rahul Patodi
DataFlair
Published in
4 min readJan 24, 2024

About Python Sliding Puzzle Game

In this Python Project, we are going to build the Sliding puzzle game, which is a classic game that challenges players to rearrange a grid of numbered tiles by sliding them into an empty space. The goal is to arrange the tiles in numerical order, usually starting from the top-left corner and ending in the bottom-right corner.

Prerequisites For Python Sliding Puzzle Game :

  • First, you need to install the required libraries and modules in your system using the pip installer.
  • To develop this sliding puzzle game successfully, you should have a good understanding of Python and the necessary libraries.
pip install pygame
pip install os-sys
pip install random2
Python Sliding Puzzle game
Python Sliding Puzzle game

Importing the libraries and modules in the program-

Now we will import the required library and modules in the system.

import pygame
import sys
from pygame.locals import *
import random

pygame- This library is used to create the game.
sys- It is used for system-level operations.
random- It is used for shuffling the initial puzzle layout.

Creating a class ‘puzzle_box’- We will create a class to represent the tiles inside the game window.

class puzzle_box:
def __init__(self, num, x, y):
self.position = (x, y)
self.num = num
self.animate = False

def display(self):
pygame.draw.rect(SURFACE, TILECOLOR, (self.position[0]*100, self.position[1]*100, 100, 100))
textSurf = FONT.render(str(self.num), True, (255, 255, 255))
textRect = textSurf.get_rect()
textRect.center = self.position[0]*100 +50, self.position[1]*100 + 50
SURFACE.blit(textSurf, textRect)

def pos_update(self, last):
if self.position == (blankx, blanky):
self.position = last

The class ‘puzzle_box’ represents a single puzzle piece.

The ‘def __init__(self, num, x, y)’ method initialises the puzzle box with a number, position and animation flag.

The ‘def display(self)’ method is used to draw the puzzle box on screen.
The ‘def pos_update(self, last)’ method is used to update the position of the puzzle box.

Code for main game function- Now, let’s create different functions to ensure the smooth execution of the game.

def main():
global SURFACE, FONT, TILECOLOR, BGCOLOR, blankx, blanky, last


pygame.init()
FPSCLOCK = pygame.time.Clock()
SURFACE = pygame.display.set_mode((600, 600))
pygame.display.set_caption("Slide Puzzle")
FONT = pygame.font.Font('DkHandRegular-orna.ttf', 20)
num = 1
BGCOLOR = (3, 54, 73)
TILECOLOR = (0, 204, 0)
list_of_boxes = []
list_of_position = []
for i in range(1, 5):
for j in range(1, 5):
list_of_position.append((j, i))
if num == 16:
break
new_Box = puzzle_box(num, j, i)
list_of_boxes.append(new_Box)
num += 1
random.shuffle(list_of_position)
blankx, blanky = list_of_position[0]
last = blankx, blanky


for box in list_of_boxes:
box.position = list_of_position[num-1]
num -= 1


while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()


if event.type == KEYUP:
if event.key in (K_LEFT, K_a) and isValidMove(blankx, blanky, "Left"):
blankx += 1
if event.key in (K_RIGHT, K_d) and isValidMove(blankx, blanky, "Right"):
blankx -= 1
if event.key in (K_UP, K_w) and isValidMove(blankx, blanky, "Up"):
blanky += 1
if event.key in (K_DOWN, K_s) and isValidMove(blankx, blanky, "Down"):
blanky -= 1


SURFACE.fill(BGCOLOR)
for new_Box in list_of_boxes:
new_Box.pos_update(last)
new_Box.display()
win = gamewin(list_of_boxes)
gamewinAnimation(win)


pygame.display.update()

last = (blankx, blanky)
FPSCLOCK.tick(15)

def isValidMove(blankx, blanky, dire):
if blankx == 4 and dire == 'Left':
return False
elif blankx == 1 and dire == 'Right':
return False
if blanky == 4 and dire == 'Up':
return False
elif blanky == 1 and dire == 'Down':
return False
else:
return True

def gamewin(list_of_boxes):
game_state = [ boxes.position for boxes in list_of_boxes]
game_state.append((4,4))

wingame = []
for i in range(1,5):
for j in range(1,5):
wingame.append((j,i))
if game_state == wingame:
return True
return False

def gamewinAnimation(win):
if win == True:
FONT2 = pygame.font.Font('DkHandRegular-orna.ttf', 20)
textwin = FONT2.render(str("You won the Game"), True, (255, 200, 100))
textwinRect = textwin.get_rect()
textwinRect.center = 300, 300
SURFACE.blit(textwin, textwinRect)

if __name__ == '__main__':
main()

The ‘def main()’ is the main function which runs the game.

It initialises the pygame using ‘pygame.init()’ method to set up the game window, fonts, colours and creates a list of puzzle boxes.

We used a ‘for’ loop to assign the initial positions and shuffle the puzzle boxes.

A ‘While’ loop is used for the game loop that listens for user input to move the puzzle pieces.

The ‘def isValidMove()’ function checks if a move in a given direction (Left, Right, Up, Down) is valid. It considers the boundary of the puzzle board.

The ‘def gamewin()’ function checks if the current state of the puzzle matches the winning state. It compares the positions of the puzzle boxes with the positions of the winning state.

The ‘def gamewinAnimation(win)’ function displays a winning message when the game is won. It uses a different font and color for the message.

Python Sliding Puzzle Game Output

Sliding Puzzle game Output
Sliding Puzzle Game Output

Conclusion

In conclusion, we have successfully developed the Slide Puzzle game using the Pygame library. This Python Sliding Puzzle Game project showcases the implementation of a classic puzzle game, offering an engaging and interactive gaming experience. You can further modify and enhance the game to add your own unique features or design elements.

We hope you’ve enjoyed exploring and learning from this Python Sliding Puzzle Game project, and we encourage you to continue experimenting with Python and game development. Have fun puzzling and coding!

--

--