Python Puzzle Game

This code implements a simple puzzle game using the Pygame library. It loads a background image and puzzle piece images, creates a 3x3 grid of puzzle pieces, and allows the player to click and drag pieces to swap them. The game checks if the puzzle is solved after each move, and displays a congratulatory message if the puzzle is solved.

Here's a brief summary of the code:

  • The Pygame library is imported and initialized.
  • The game window is set up with a width of 483 pixels and a height of 480 pixels, and a caption of "Make Abdur - Puzzle Game".
  • The background music and sound effects are loaded from sound files.
  • The puzzle piece images are loaded from files and stored in a list called pieces.
  • The game loop starts, which repeatedly draws the background image and puzzle pieces on the screen and waits for user input.
  • User input is handled using Pygame's event handling system. Specifically, the game listens for QUIT, MOUSEBUTTONDOWN, MOUSEBUTTONUP, and MOUSEMOTION events.
  • When the player clicks on a puzzle piece, the game stores the selected piece and its position.
  • When the player drags the selected piece, the game swaps the selected piece with the piece under the mouse cursor and plays a sound effect.
  • After each move, the game checks if the puzzle is solved by comparing the pixel arrays of the puzzle pieces to the pixel arrays of the original arrangement of the pieces.
  • If the puzzle is solved, the game stops the background music and displays a congratulatory message on the screen. It also plays a winning sound and waits for a delay before closing the game window. 

import pygame
import numpy as np

pygame.init()

# Set up the game window
screen_width = 483
screen_height = 480
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Make Abdur - Puzzle Game")

# Load the background music
pygame.mixer.music.load("gameplay.wav")

# Load the sound files
click_sound = pygame.mixer.Sound("click.wav")
drag_sound = pygame.mixer.Sound("drag.wav")
win_sound = pygame.mixer.Sound("win.wav")

# Load the images for the puzzle pieces and the background
background_image = pygame.image.load("bg.png")
# puzzle image is split into 9 pieces and loaded
piece1_image = pygame.image.load("1.jpg").convert(32)
piece2_image = pygame.image.load("2.jpg").convert(32)
piece3_image = pygame.image.load("3.jpg").convert(32)
piece4_image = pygame.image.load("4.jpg").convert(32)
piece5_image = pygame.image.load("5.jpg").convert(32)
piece6_image = pygame.image.load("6.jpg").convert(32)
piece7_image = pygame.image.load("7.jpg").convert(32)
piece8_image = pygame.image.load("8.jpg").convert(32)
piece9_image = pygame.image.load("9.jpg").convert(32)
# print((piece1_image))

# Create the puzzle pieces: creates a 3x3 grid of puzzle pieces and stores them in a 2D list called "pieces"
piece_size = 164
pieces = []

for i in range(3):
    row = []
    for j in range(3):
        piece_name = f"{(i*3)+j+1}.jpg"
        # print(piece_name)
        piece = pygame.image.load(piece_name).convert_alpha()
        piece = pygame.transform.scale(piece, (piece_size, piece_size))
        row.append(piece)
    pieces.append(row)


# Draw the game screen
selected_piece = None

# Define the original arrangement of the pieces
original_pieces = [[piece8_image, piece3_image, piece5_image],
                   [piece1_image, piece7_image, piece4_image],
                   [piece9_image, piece2_image, piece6_image]]

# Start playing the background music
pygame.mixer.music.play(-1)  # "-1" means the music will loop forever

# Define the font for the congratulatory message
font = pygame.font.Font(None, 30)

while True:
    # This code draws the background image and the puzzle pieces on the screen
    screen.blit(background_image, (0, 0))
    for i, row in enumerate(pieces):
        # print(i, row)
        for j, piece in enumerate(row):
            # print(j, piece)
            x = j * piece_size
            y = i * piece_size
            screen.blit(piece, (x, y))
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            exit()
        # Add mouse input to allow the player to move the puzzle pieces
        # This code allows the player to click and drag a puzzle piece to swap it with another piece
        elif event.type == pygame.MOUSEBUTTONDOWN:
            x, y = pygame.mouse.get_pos()
            j = x // piece_size
            i = y // piece_size
            selected_piece = pieces[i][j]
            selected_i, selected_j = i, j
            # Play the "click" sound effect when the player clicks on a puzzle piece
            click_sound.play()
        elif event.type == pygame.MOUSEBUTTONUP:
            selected_piece = None
        elif event.type == pygame.MOUSEMOTION and selected_piece is not None:
            x, y = pygame.mouse.get_pos()
            j = x // piece_size
            i = y // piece_size
            try: 
                pieces[selected_i][selected_j], pieces[i][j] = pieces[i][j], pieces[selected_i][selected_j]
            except:
                pass
            selected_i, selected_j = i, j
            drag_sound.play()
            

    # Check if the puzzle is solved
    puzzle_solved = True
    for i in range(3):
        for j in range(3):
            if not np.array_equal(pygame.surfarray.pixels3d(pieces[i][j]), pygame.surfarray.pixels3d(original_pieces[i][j])):
                puzzle_solved = False
                break
        if not puzzle_solved:
            break
        
    if puzzle_solved:
        pygame.mixer.music.stop()
        print("Congratulations! You solved the puzzle!")
        # Create a text surface for the congratulatory message
        text_surface = font.render("Congratulations! You solved the puzzle!", True, (0, 0, 0))
        text_rect = text_surface.get_rect()
        text_rect.center = (screen_width // 2, screen_height // 2)
        screen.blit(text_surface, text_rect)
        # play winning sound
        win_sound.play()
        
        # Add a delay before closing the game window
        # pygame.time.delay(6000)
        # pygame.quit()
        # exit()
        
    pygame.display.update()

    

Comments

Popular posts from this blog

Quotation marks to wrap an element in HTML

The Basic Structure of a Full-Stack Web App

Unlocking Web Design: A Guide to Mastering CSS Layout Modes