Click here to Skip to main content
Click here to Skip to main content

Build Puzzle 15 - Walkthrough

By , 23 Feb 2012
Rate this:
Please Sign up or sign in to vote.


In one of my articles I wrote about My First Windows 8 Application – Metro Puzzle there I talked about Windows 8 Metro application and demonstrate how to build app for Win 8, the application I built was Puzzle 15. later I started to get requests to explain the steps for building that game.

So I'm writing the steps for building a Puzzle 15 Game.




Step 1: The Puzzle Base

There are several ways to build the puzzle layer, In my demo I chose a simple way of a Canvas with 16 children's type of StackPanel.

Basically I have a lower canvas with the Board image, on top of it I put another canvas with 16 Stack Panels, each panel spread to 100X100


Now, when I have the main puzzle structure I added an image of size 95x95 to each Stack Panel. (the reason it’s not 100X100 – is to leave a space between each), for each image I set the Tag property with the value of the image – 1.png Tag = 1


I’ve also add a timer for counting the time took to solve this puzzle and another int property to count the moves the user made.

Step 2: Find

One of the most common things we’ll use in our code, is FIND:

  • Find Stack Panel by Image Id
  • Find the Empty Panel
  • Find the Value by position

Find the parent of image with a specific Tag value

StackPanel FindStackPanelByTagId(int tag)
  if (tag == 16)
     return (from stackPanel in ContentPanel.Children.OfType<StackPanel>() 
          where stackPanel.Children.Count == 0 select stackPanel).First();
     return (from stackPanel in ContentPanel.Children.OfType<StackPanel>()
             from img in stackPanel.Children.OfType<Image>()
             where Convert.ToInt32(img.Tag) == tag
             select stackPanel).First();

Find the position of StackPanel without children

int FindEmptyItemPosition()
    int index = 15;
        if (((StackPanel)ContentPanel.Children[i]).Children.Count == 0)
            return index;
    return 0;

Get the Tag value by StackPanel position

int FindItemValueByPosition(int position)
  return ((StackPanel)ContentPanel.Children[position]).Children.Count > 0 
          ? Convert.ToInt32(((Image)((StackPanel)ContentPanel.Children
            [position]).Children[0]).Tag) : 16;

Step 3: Scrambles

Now we have are puzzle structure and Find method helpers, the first thing is to Scramble or puzzle.

So I wrote a method that runs n times and generate random numbers from 1 to 16, for each number find the current StackPanel that hold him. (FindStackPanelByTagId) .

If First and Second number are smaller then 16 then - swipe the images and tag values.

If One of the values is 16 the swipe - One Stackpanel will be cleared of Items

 void Scrambles()
    var count = 0;
    while (count < 25)
        var a = _rnd.Next(1, 17);
        var b = _rnd.Next(1, 17);
        if (a == b) continue;
        var stack1 = FindStackPanelByTagId(a);
        var stack2 = FindStackPanelByTagId(b);
        if (a == 16)
            var image2 = stack2.Children[0];
        else if (b == 16)
            var image1 = stack1.Children[0];
            var image1 = stack1.Children[0];
            var image2 = stack2.Children[0];

Step 4: Check Board

Each move the user do, perform a loop and checks values from 1 to 16. if the numbers are not in the correct order than nothing happen.

Else You stop the game timer and display a win message.

 void CheckBoard()
    var index = 1;
    for (var i = 15; i > 0; i--)
        if (FindItemValueByPosition(i) != index) return;
    WinGrid.Visibility = System.Windows.Visibility.Visible;

Step 5: Move Items

Before we can apply move of items we need to check several things, the first thing is:

Check if the Item Can move, Checking all panels around the specific item with -1 +1 -4 +4, if one of them is empty then he can move.

 StackPanel CanMove(UIElement itemToMove)
    var count = ContentPanel.Children.Count;
        if (!(ContentPanel.Children[i] is StackPanel)) continue;
        var stackPanel = (StackPanel)ContentPanel.Children[i];
        if (!stackPanel.Children.Contains(itemToMove)) continue;
        if (!IsBorderSwich(i, i + 1) && i + 1 <= 15 && ContentPanel.
            Children[i + 1] != null && 
           ((StackPanel)ContentPanel.Children[i + 1]).Children.Count == 0)
            return ((StackPanel)ContentPanel.Children[i + 1]);
        if (!IsBorderSwich(i, i - 1) && i - 1 > -1 && ContentPanel.
            Children[i - 1] != null && 
           ((StackPanel)ContentPanel.Children[i - 1]).Children.Count == 0)
            return ((StackPanel)ContentPanel.Children[i - 1]);
        if (i + 4 <= 15 && ContentPanel.Children[i + 4] != null && 
           ((StackPanel)ContentPanel.Children[i + 4]).Children.Count == 0)
            return ((StackPanel)ContentPanel.Children[i + 4]);
        if (i - 4 > -1 && ContentPanel.Children[i - 4] != null && 
           ((StackPanel)ContentPanel.Children[i - 4]).Children.Count == 0)
            return ((StackPanel)ContentPanel.Children[i - 4]);
    return null;

The Second - if both of the items you want to swipe are in the Board borders do nothing.

private readonly int[] _bordersNums = { 0, 4, 8, 12, 3, 7, 11, 15 };

bool IsBorderSwich(int a, int b)
    return _bordersNums.Contains(a) && _bordersNums.Contains(b);


Now after we have those safety methods we can move the items based on user clicks: Just register to ItemManipulationStarted on the entire windows, for each event check if the item isn’t image do nothing,

if it does, call the CanMove method to verify that this item can move around.

 private void ItemManipulationStarted(object sender, 
                                          ManipulationStartedEventArgs e)
    var item = (UIElement)e.OriginalSource;
    if (!(item is Image)) return;
    var to = CanMove(item);
    if (to != null)
        txtMoves.Text = _moves.ToString();
        MoveItem(item, to);
    e.Handled = true;

MoveItem - Move Item From One StackPanel to Another.

 void MoveItem(UIElement item, StackPanel targetPanel)
    foreach (var stackPanel in
        ContentPanel.Children.OfType<StackPanel>().Where(stackPanel => 
    stackPanel.Children.Count > 0 && stackPanel.Children.Contains(item)))

Step 6: Check If Puzzle Solvable

This part of very important, because half of the starting positions for the n-puzzle are impossible to resolve.


The Puzzle 15 (n-puzzle) is a classical problem for modeling algorithms involving heuristics. Commonly used heuristics for this problem include counting the number of misplaced tiles and finding the sum of the Manhattan distances between each block and its position in the goal configuration. Note that both are admissible, i.e., they never overestimate the number of moves left, which ensures optimality for certain search algorithms such as A*.

bool CheckIfSolvable()
    var n = 0;
    for (var i = 1; i <= 16; i++)
        var num1 = FindItemValueByPosition(i);
        var num2 = FindItemValueByPosition(i - 1);
        if (num1 > num2)
    var emptyPos = FindEmptyItemPosition();
    return n % 2 == (emptyPos + emptyPos / 4) % 2 ? true : false;

Step 7: Setup a New Game

Now, when we defined everything we need, let’s write the New Game method, reset all timer and moves number back to 0, call the Scrambles method, and while the game is unsolvable continue scramble the game, once it’s solvable start the timer.

public void NewGame()
    _moves = 0;
    txtMoves.Text = "0";
    txtTime.Text = Const.DefaultTimeValue;
    while (!CheckIfSolvable())
    _startTime = DateTime.Now.AddSeconds(1);
    GridScrambling.Visibility = System.Windows.Visibility.Collapsed;





About the Author

Shai Raiten
Architect Sela
Israel Israel
My Blog:
Follow on   Twitter

Comments and Discussions

GeneralMy vote of 5 PinmvpMichael Haephrati1-Mar-13 2:28 
QuestionQuestion??? Pinmembermr.pakapun16-Jan-13 15:28 
AnswerRe: Question??? Pinmembermr.pakapun17-Jan-13 4:31 
QuestionWhat about puzzle 8 and 24 ?? Pinmembermr.pakapun16-Jan-13 2:54 
AnswerRe: What about puzzle 8 and 24 ?? Pinmembermr.pakapun16-Jan-13 15:20 
QuestionAsk! PinmemberPramana Adi Putra10-Jan-13 13:01 
AnswerRe: Ask! PinmvpShai Raiten20-Jan-13 1:52 
GeneralMy vote of 5 PinmvpKanasz Robert21-Sep-12 1:27 
GeneralRe: My vote of 5 PinmvpShai Raiten29-Sep-12 20:38 
QuestionA few improvements PinmemberGrimlock10-Aug-12 2:21 
I have a few remarks on how you scramble the board when you start a new game. You can do things a lot easier.
First, a small remark on CheckIfSolvable()
Instead of an int, you can use a boolean:
instead of
if (num > num2)
you can do:
if (num > num2)
    parity = !parity;
if ((emptyPos / 4) % 2 == 0) parity = !parity;
return parity;
(You don't need to know how many, just whether it's even or odd.)
Second remark:
It is not necessary to keep scrambling if a grid is unsolvable.
You can make it solvable by swapping any 2 blocks.
if (!CheckIfSolvable()) // if, not while!
    // Swap position of block x with position of block y
And then scrambling itself.
This is how you randomize an array in one go:
int[] array = Enumerable.Range(0, 16).ToArray();
for (int i = 15; i > 0; i--)
    int r = _rnd.Next(0, i);
    int temp = array[r];
    array[r] = array[i];
    array[i] = temp;
You can then assign these positions to the blocks.
otherwise, nice work
SuggestionCool! WPF version of this game PinmemberMember 471378513-Jun-12 2:32 
GeneralMy vote of 5 PinmemberAnurag Gandhi12-Mar-12 9:50 
AnswerGreat game PinmemberMarsh Joseph19-Feb-12 22:49 
GeneralRe: Great game PinmvpShai Raiten19-Feb-12 23:05 



| Advertise | Privacy | Mobile
Web01 | 2.8.140315.1 | Last Updated 24 Feb 2012
Article Copyright 2012 by Shai Raiten
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid