Click here to Skip to main content
13,289,626 members (57,377 online)
Click here to Skip to main content
Add your own
alternative version


17 bookmarked
Posted 25 Mar 2011

Dynamic Sliding Puzzle Generator

Rate this:
Please Sign up or sign in to vote.
A dynamic sliding puzzle generator involving LINQ and photo scaling functionalities.


As per Wiki, a sliding puzzle, sliding block puzzle, or sliding tile puzzle challenges a player to slide usually flat pieces along certain routes (usually on a board) to establish a certain end-configuration. But here I would go for a simple (programmatically complex) prototype of sliding puzzle where the players have the flexibility to generate a puzzle from an image of their choice.


Of late, I have been going through various ways of implementing the sliding puzzle (in fact, there are numerous ways even). This version of game here is pretty simple and very dynamic in nature. Each and every line here is written in such a way that the user has complete flexibility to set the size of the individual pieces of a picture as well as the number of cells per row.

The key features in implementing the game are:

  1. Extremely dynamic with respect to the number of rows and the size of each individual cell.
  2. Loads image pieces dynamically.
  3. Scales images to the length of the puzzle.
  4. Uses events to implement the logic.

Using the code

The logic here is to construct and add images dynamically to the Windows form. The function AssignEventsToButtons() does the core functionality of this.

private void AssignEventsToButtons()
    PictureBox temp = null;
    int x = -1;
    for (int i = 0; i <= MaxSeed; i++)
         temp = new PictureBox
                   TabIndex = ++x,
                   SizeMode = System.Windows.Forms.PictureBoxSizeMode.CenterImage,
                   Size = new System.Drawing.Size(SideLength, SideLength),
                   Name = string.Concat("pictureBox", x.ToString()),
                   AllowDrop = true,
                   Location = new Point(0, 0)
        temp.MouseDown += new MouseEventHandler(button_MouseDown);
        temp.DragDrop += new DragEventHandler(button_DragDrop);
        temp.DragEnter += new DragEventHandler(button_DragEnter);

Handling mouse events is crucial here. Every piece of block has to be handling all the three events, namely MouseDown, DragDrop, and DragEnter. Initially consider a piece to be moved to white space, the mouse down event of the current piece is handled to send the picture forward.

private void button_MouseDown(object sender, MouseEventArgs e)
    Cursor = Cursors.Hand;
    _dragSource = (PictureBox)sender;
                DragDropEffects.Copy | DragDropEffects.Move);

The event DragEnter is basically to handle the desired effect of moving the picture.

private void button_DragEnter(object sender, DragEventArgs e)
    e.Effect = e.Data.GetDataPresent(DataFormats.Bitmap) ? 
                         DragDropEffects.Move : DragDropEffects.None;

The logic part of the game is to check for a valid move. The dragging piece's information is stored and is compared with the destination piece's, with the following steps:

  1. Destination place should be a valid position to move (no cross movements).
  2. An image should not allow drag and drop on itself.
  3. Once checks are done, the images are swapped.
private void button_DragDrop(object sender , DragEventArgs e)
    var dest = (PictureBox) sender;


    if( !new List<int>
                 _dragSource.TabIndex + 1,
                 _dragSource.TabIndex - 1,
                 _dragSource.TabIndex + RowCount,
                 _dragSource.TabIndex - RowCount
    if (!ImageCompareArray(dest.Image as Bitmap,Resources._17))

    _dragSource.Image = dest.Image;
    dest.Image = e.Data.GetData(DataFormats.Bitmap) as Image;

    //checks state
    CheckState(_dragSource.TabIndex, dest.TabIndex);

Here the function CheckState checks for the state of the game on every step, and is checked with _successState so as to confirm the game's completion. Another interesting feature in this game can be seen when you press F3. Yes, you can load an image of your choice. The image is scaled down to the size the player configured, without distortion. The ResizeImage function does this for you.

Note: Check for the settings SideLength and RowCount in DynSlidingPuzzle.exe.config. Please assign valid values for the same.


This concludes the making of a simple yet dynamic game application that demonstrates the ease of using .NET. Please go through the code and let me know your comments. Thanks in advance.


This article, along with any associated source code and files, is licensed under The Creative Commons Attribution 3.0 Unported License


About the Author

Krishnachytanya Ayyagari
Software Developer (Junior) Thomson Reuters
India India
Currently, I am Software Engineer in ThomsonReuters. I am a man who believes in a fact that -"Technology is best available now-a-days but what matter is "How you use it?" and "What you solved using it?" ....." My site, my work and everything about me demonstrates this basic idea. I do what I love and I love what I do.....
U can find all about me @ Smile | :)

You may also be interested in...

Comments and Discussions

Questionsource code Pin
Member 126694998-Aug-16 8:28
memberMember 126694998-Aug-16 8:28 
GeneralMy vote of 4 Pin
Amol Rawke Pune30-Mar-11 21:26
memberAmol Rawke Pune30-Mar-11 21:26 
GeneralRe: My vote of 4 Pin
Krishnachytanya Ayyagari2-Apr-11 9:42
memberKrishnachytanya Ayyagari2-Apr-11 9:42 
Generalpuzzling Pin
Luc Pattyn25-Mar-11 1:07
mvpLuc Pattyn25-Mar-11 1:07 
Please compare Jigsaw[^] and Sliding[^] puzzles.

D'Oh! | :doh:
Luc Pattyn [Forum Guidelines] [My Articles] Nil Volentibus Arduum
Please use <PRE> tags for code snippets, they preserve indentation, improve readability, and make me actually look at the code.

GeneralRe: puzzling Pin
Krishnachytanya Ayyagari25-Mar-11 3:12
memberKrishnachytanya Ayyagari25-Mar-11 3:12 
AnswerRe: puzzling Pin
Luc Pattyn25-Mar-11 3:26
mvpLuc Pattyn25-Mar-11 3:26 
GeneralRe: puzzling Pin
Krishnachytanya Ayyagari25-Mar-11 4:32
memberKrishnachytanya Ayyagari25-Mar-11 4:32 
AnswerRe: puzzling Pin
Luc Pattyn25-Mar-11 4:43
mvpLuc Pattyn25-Mar-11 4:43 
GeneralThat's not a jigsaw puzzle... Pin
Dave Kreskowiak24-Mar-11 18:40
mvpDave Kreskowiak24-Mar-11 18:40 
GeneralRe: That's not a jigsaw puzzle... Pin
Krishnachytanya Ayyagari25-Mar-11 5:35
memberKrishnachytanya Ayyagari25-Mar-11 5:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.171207.1 | Last Updated 28 Mar 2011
Article Copyright 2011 by Krishnachytanya Ayyagari
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid