Slide Puzzle Using Python PyGame


In this article, we will guide you through the process of creating a slide puzzle game using Python and the PyGame library. As passionate Python programmers, we have always enjoyed developing interactive games, and slide puzzles are no exception. With the power of PyGame, we can bring this classic puzzle to life on our screens. Throughout this tutorial, we will embark on an exciting coding adventure together. We will explore how to set up the game window, create the puzzle tiles, shuffle them randomly, and handle user input for an interactive experience. Each step will give us a deeper understanding of Python's capabilities and how PyGame simplifies game development.

By the end of this article, we will have a fully functional slide puzzle game that we can play and share with others. So let's dive in and unleash our creativity as we embark on this thrilling journey of building a slide puzzle game using Python and PyGame.

Getting Started

Let's take the first steps together by getting started with Python and PyGame. Setting up Python and PyGame is a simple and exciting process for Python enthusiasts like us. So, without wasting any more time, let's jump right in and lay the groundwork for our thrilling game.

Once PyGame is successfully installed, we will create a new Python script and import the necessary modules:

import pygame
import random

Setting up the Game Window

With the modules imported, we can now move on to setting up the game window. We will define the dimensions of the window, choose appealing colors, and make other necessary configurations:

# Initialize PyGame
pygame.init()

# Set up the window
window_width, window_height = 400, 400
window = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption("Slide Puzzle")

# Define colors
background_color = (255, 255, 255)
tile_color = (0, 0, 0)

Creating the Tiles

Let's proceed by making the tiles for our slide puzzle. A rectangular surface with a number will be present on each tile. To begin, the tiles will be shuffled at random to form the basic puzzle arrangement.

Here’s an example code:

# Define tile properties
tile_size = 100
tile_margin = 5
rows, cols = 4, 4

# Create the tiles
tiles = []
for row in range(rows):
    for col in range(cols):
        tile_number = row * cols + col
        if tile_number != rows * cols - 1:
            tile = pygame.Surface((tile_size, tile_size))
            tile.fill(tile_color)
            tile_rect = tile.get_rect()
            tile_rect.topleft = (col * (tile_size + tile_margin), row * (tile_size + tile_margin))
            tiles.append((tile, tile_rect, tile_number))

Shuffling the Tiles

We want to make sure that the puzzle has a random configuration when the game starts. Players will be surprised and faced with a task as a result since they won't be aware of the exact starting arrangement of the tiles.

To achieve this, we need to shuffle the tiles randomly. This step is crucial to create a solvable puzzle that can be solved by moving the tiles around.Here’s an input code:

random.shuffle(tiles)

The random.shuffle() function is crucial here. It rearranges the tiles randomly, giving us a unique puzzle arrangement every time the game begins. This randomness adds excitement and makes the slide puzzle more challenging and engaging for players.

Handling User Input

Now, let's focus on how we can handle user input in our slide puzzle game. As the player interacts with the game, we need to respond to their actions and move the puzzle tiles accordingly.

To achieve this, we will implement the logic to detect mouse clicks on the tiles and move them based on the user's input. Here's an example code:

# Game loop
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONUP:
            mouse_pos = pygame.mouse.get_pos()
            for tile, tile_rect, tile_number in tiles:
                if tile_rect.collidepoint(mouse_pos):
                    # Check if the clicked tile can move
                    if (
                        (tile_rect.left - tile_size, tile_rect.top) in [rect.topleft for _, rect, _ in tiles]
                        or (tile_rect.left + tile_size, tile_rect.top) in [rect.topleft for _, rect, _ in tiles]
                        or (tile_rect.left, tile_rect.top - tile_size) in [rect.topleft for _, rect, _ in tiles]
                        or (tile_rect.left, tile_rect.top + tile_size) in [rect.topleft for _, rect, _ in tiles]
                    ):
                        # Move the clicked tile
                        empty_tile_index = [index for index, (_, _, number) in enumerate(tiles) if number == rows * cols - 1][0]
                        empty_tile_rect = tiles[empty_tile_index][1]
                        empty_tile_rect.topleft = tile_rect.topleft
                        tile_rect.topleft = (empty_tile_rect.left, empty_tile_rect.top)
                        tiles[empty_tile_index], tiles[tile_number] = tiles[tile_number], tiles[empty_tile_index]

In this code, we handle two types of events: quitting the game and detecting mouse button−up events. When the user clicks on a tile, we check if the clicked tile can move by verifying if there is an empty space adjacent to it. If it can move, we swap the positions of the clicked tile and the empty tile.

Drawing the Game

Now let's implement the code to draw the game on the window. We will clear the window, draw the tiles, and update the display. To do this write this code:

 # Clear the window
    window.fill(background_color)

# Draw the tiles
  for tile, tile_rect, _ in tiles:
     window.blit(tile, tile_rect)

# Update the display
    pygame.display.flip()

Game Over Condition

Finally, we must determine whether the puzzle has been solved. When the tiles are arranged from 0 to n−1 in the proper order, the puzzle is finished. After designing the game, add the following code inside the game loop:

 # Check if the puzzle is solved
    if [number for _, _, number in tiles] == list(range(rows * cols - 1)):
        running = False

Cleaning Up

After the game loop ends, we need to clean up and quit PyGame. Here’s an example code to clear:

pygame.quit()

Conclusion

In conclusion, creating a slide puzzle game using Python and PyGame has been a rewarding experience. Throughout this journey, we learned how to set up the game window, shuffle the tiles, handle user input, and draw the game on the screen. Figuring out the game over the condition and making the tiles move has improved our problem−solving skills. We can further customize the game by adding images or a timer to make it more personalized. Overall, this project introduced us to the exciting world of game development and provided a fun and engaging way to challenge our minds.

Updated on: 26-Jul-2023

226 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements