Create Jigsaw Puzzle Game Using C# WinForms

Faraz

By Faraz - August 09, 2024

Learn how to create a jigsaw puzzle game in C# WinForms. Follow this step-by-step guide with code examples to build your own interactive jigsaw puzzle game.


create-jigsaw-puzzle-game-using-csharp-winforms.webp

Jigsaw puzzles are a fun and challenging way to pass the time, and creating a digital version of this classic game can be a great way to sharpen your programming skills. In this tutorial, we will guide you through the process of building a Jigsaw Puzzle game using C# and Windows Forms (WinForms). The game will involve taking an image, splitting it into multiple pieces, shuffling those pieces, and allowing the player to arrange them back into the correct order. Whether you’re new to C# or game development, this detailed guide will help you create your very own jigsaw puzzle game.

Step-by-Step Guide to Creating a Jigsaw Puzzle Game

1. Setting Up Your Project

Before we dive into the code, let's start by setting up the project in Visual Studio.

Step 1: Open Visual Studio

  • Launch Visual Studio on your computer. If you don’t have it installed, you can download the Community Edition for free from Microsoft's website.

Step 2: Create a New Project

  • Click on "Create a new project" from the start window.
  • In the search bar, type "Windows Forms App" and select it from the list.
  • Click "Next", give your project a name (e.g., "Jigsaw_Puzzle"), choose a location, and then click "Create".

You now have a blank Windows Forms project ready for development.

2. Designing the Game Interface

The next step is to design the interface of our jigsaw puzzle game. This involves adding controls like buttons and panels to the form.

Step 1: Add a Panel to Hold the Puzzle Pieces

  • Open Form1 in the designer view.
  • Drag and drop a Panel control from the Toolbox onto the form.
  • Set the Size of the Panel to 270x270 pixels. This will be the area where the puzzle pieces will be displayed.

Step 2: Add Buttons for Puzzle Pieces

  • Inside the Panel, add eight Button controls. Each button will represent a piece of the jigsaw puzzle.
  • Set each button's Size to 90x90 pixels, so they fit perfectly within the panel (3x3 grid).
  • Name the buttons sequentially (e.g., button1, button2, …, button8).

Step 3: Add a Start Button

  • Below the panel, add another Button control. This button will start the game by loading and shuffling the puzzle pieces.
  • Set its Text property to "Start".

3. Loading and Cropping the Image

The core of our jigsaw puzzle game involves loading an image, cropping it into pieces, and then displaying those pieces on the buttons. Let’s write the code for this.

Step 1: Import Necessary Namespaces

  • Open Form1.cs.
  • Ensure you have the following namespaces imported at the top of your file:
using System;
using System.Collections;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

Step 2: Initialize Variables

Add the following variables to the Form1 class:

Point EmptyPoint;
ArrayList images = new ArrayList();

The EmptyPoint will track the empty space in the puzzle, and images will hold the cropped pieces of the image.

Step 3: Load and Crop the Image

  • In the Form1_Load method (or in the Start button click event), add the following code to load and crop the image:
private void button9_Click(object sender, EventArgs e)
{
    foreach (Button b in panel1.Controls)
        b.Enabled = true;

    Image original = Image.FromFile(@"img\img.jpg");
    cropImageToPieces(original, 270, 270);
    AddImagesToButtons(images);
}

private void cropImageToPieces(Image original, int w, int h)
{
    Bitmap bmp = new Bitmap(w, h);
    Graphics graphic = Graphics.FromImage(bmp);
    graphic.DrawImage(original, 0, 0, w, h);
    graphic.Dispose();

    int moveRight = 0, moveDown = 0;
    for (int x = 0; x < 8; x++)
    {
        Bitmap piece = new Bitmap(90, 90);
        for (int i = 0; i < 90; i++)
            for (int j = 0; j < 90; j++)
                piece.SetPixel(i, j, bmp.GetPixel(i + moveRight, j + moveDown));
        images.Add(piece);
        moveRight += 90;
        if (moveRight == 270)
        {
            moveRight = 0;
            moveDown += 90;
        }
    }
}

This code loads an image from the img folder and divides it into 90x90 pixel pieces.

4. Shuffling and Displaying Puzzle Pieces

After cropping the image, the pieces should be shuffled to create the jigsaw puzzle effect.

Step 1: Shuffle the Puzzle Pieces

  • Add the following method to shuffle the pieces:
private int[] Shuffle(int[] arr)
{
    Random rand = new Random();
    arr = arr.OrderBy(x => rand.Next()).ToArray();
    return arr;
}

This method randomizes the order of the array, which represents the positions of the puzzle pieces.

Step 2: Assign Shuffled Pieces to Buttons

  • Add this method to assign the shuffled images to the buttons:
private void AddImagesToButtons(ArrayList images)
{
    int i = 0;
    int[] arr = { 0, 1, 2, 3, 4, 5, 6, 7 };
    arr = Shuffle(arr);
    foreach (Button b in panel1.Controls)
    {
        if (i < arr.Length)
        {
            b.Image = (Image)images[arr[i]];
            i++;
        }
    }
}

This method shuffles the pieces and assigns them to the buttons within the panel.

5. Implementing Puzzle Piece Movement

To complete the jigsaw puzzle, the player must be able to move the pieces into the correct positions.

Step 1: Detect Button Click and Move Pieces

  • Add the following method to handle button clicks and move the pieces:
private void button1_Click(object sender, EventArgs e)
{
    MoveButton((Button)sender);
}

private void MoveButton(Button btn)
{
    if (((btn.Location.X == EmptyPoint.X - 90 || btn.Location.X == EmptyPoint.X + 90)
        && btn.Location.Y == EmptyPoint.Y)
        || (btn.Location.Y == EmptyPoint.Y - 90 || btn.Location.Y == EmptyPoint.Y + 90)
        && btn.Location.X == EmptyPoint.X)
    {
        Point swap = btn.Location;
        btn.Location = EmptyPoint;
        EmptyPoint = swap;
    }

    if (EmptyPoint.X == 180 && EmptyPoint.Y == 180)
        CheckValid();
}

This code allows buttons adjacent to the empty space to swap positions with it when clicked.

6. Checking for a Win Condition

Finally, we need to check if the puzzle is solved. If all the pieces are in the correct position, the player wins.

Step 1: Validate the Puzzle Completion

  • Add the following method to check if the puzzle is solved:
private void CheckValid()
{
    int count = 0, index;
    foreach (Button btn in panel1.Controls)
    {
        index = (btn.Location.Y / 90) * 3 + btn.Location.X / 90;
        if (images[index] == btn.Image)
            count++;
    }
    if (count == 8)
        MessageBox.Show("Well done! You win!");
}

This method checks if all the buttons are in the correct position and displays a message if the puzzle is solved.

Conclusion

You've successfully created an Jigsaw puzzle game using C# and WinForms. This project not only helps you understand the basics of C# and WinForms but also gives you a hands-on experience with game development. You can further enhance this game by adding features like different difficulty levels, a timer, or even sound effects to make it more engaging.

By following this step-by-step guide, you've learned how to load images, manipulate them, and create a fun interactive game. Keep experimenting with new ideas, and who knows? You might end up creating the next big hit in the gaming world!

Download Code

That’s a wrap!

I hope you enjoyed this article

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post