5,427,303 members and growing! (19,774 online)
Email Password   helpLost your password?
Platforms, Frameworks & Libraries » Windows Presentation Foundation » General     Intermediate License: The Code Project Open License (CPOL)

Simple slide game using Viewbox

By Sacha Barber

A simple 9 peice puzzle using ImageBrush.ViewBox
C# (C# 3.0, C#), .NET (.NET, .NET 3.5), WPF, Design, Architect, Dev

Posted: 28 Apr 2008
Updated: 9 Aug 2008
Views: 7,559
Bookmarked: 14 times
Announcements
Want a new Job?



Search    
Advanced Search
Sitemap
20 votes for this Article.
Popularity: 6.10 Rating: 4.69 out of 5
1 vote, 5.0%
1
0 votes, 0.0%
2
0 votes, 0.0%
3
4 votes, 20.0%
4
15 votes, 75.0%
5
Note: This is an unedited contribution. If this article is inappropriate, needs attention or copies someone else's work without reference then please Report This Article

Introduction

This is a very simple article that really just demonstrates the various capabilities of the WPF ImageBrush. The basic idea is that the attached demo emulated one of those 9 square puzzles you used to get in XMAS stockings.

Where 1 square was blank, and the image portions in the other 8 squares were randomly scattered, and you had to try and recreate the whole image, by sliding the image portion squares into the blank space, and repeating this until you had the whole image again.

In a nutshell thats all this article does.

So How Does It Work

Well its based in WPF land, so we can use a convienient layout manager called a Grid which has Rows/Columns. So we can imagine that each Row/Column of the Grid will either hold a square which holds a section of the original image, or will be the single blank square.

And that's exactly what we do.

The basic steps are as follows:

  1. Load an image
  2. Split the image into equals portions
  3. Randomly place the 8 sequentially obtained image portions
  4. Allow the user to click one of the image portion squares

Thats all there is to it.

So let's look at each of these steps in a bit more detail

Step1 : Load An Image

Loading an image is done by the button click event that allows the user to grab a new image, the code is as follows:

Microsoft.Win32.OpenFileDialog ofd = new Microsoft.Win32.OpenFileDialog();
ofd.Filter = "Image Files(*.BMP;*.JPG;*.GIF;*.PNG)|*.BMP;*.JPG;*.GIF;*.PNG" +
            "|All Files (*.*)|*.*";
ofd.Multiselect = false;
if (ofd.ShowDialog() == true)
{
    try
    {
        image = new BitmapImage(new Uri(ofd.FileName, UriKind.RelativeOrAbsolute));
        img = new Image { Source = image };
        CreatePuzzleForImage();
    }
    catch
    {
        MessageBox.Show("Couldnt load the image file " + ofd.FileName);
    }
}

Step2 : Split The Image Into Equals Portions

We need to grab sequential portions of the original image, but only grab 8, as we need the 9th square to be a blank. So this is done using the following code:

//row0
CreateImagePart(0, 0, 0.33333, 0.33333);
CreateImagePart(0.33333, 0, 0.33333, 0.33333);
CreateImagePart(0.66666, 0, 0.33333, 0.33333);
//row1
CreateImagePart(0, 0.33333, 0.33333, 0.33333);
CreateImagePart(0.33333, 0.33333, 0.33333, 0.33333);
CreateImagePart(0.66666, 0.33333, 0.33333, 0.33333);
//row2
CreateImagePart(0, 0.66666, 0.33333, 0.33333);
CreateImagePart(0.33333, 0.66666, 0.33333, 0.33333);

Where the CreateImagePart() method looks like the following:

private void CreateImagePart(double x, double y, double width, double height)
{
    ImageBrush ib = new ImageBrush();
    ib.Stretch = Stretch.UniformToFill;
    ib.ImageSource = image;
    ib.Viewport = new Rect(0, 0, 1.0, 1.0);
    //grab image portion
    ib.Viewbox = new Rect(x, y, width, height); 
    ib.ViewboxUnits = BrushMappingMode.RelativeToBoundingBox;
    ib.TileMode = TileMode.None;

    Rectangle rectPart = new Rectangle();
    rectPart.Fill = ib;
    rectPart.Margin = new Thickness(0);
    rectPart.HorizontalAlignment = HorizontalAlignment.Stretch;
    rectPart.VerticalAlignment = VerticalAlignment.Stretch;
    rectPart.MouseDown += new MouseButtonEventHandler(rectPart_MouseDown);
    initialUnallocatedParts.Add(rectPart);
}

The most important parts of this is the line that sets the ImageBrush ViewPort, ib.Viewport = new Rect(0, 0, 1.0, 1.0). This means start at 0,0 and end at the end of the image. In WPF 0,0 means top left, which 1.0,1.0 means bottom right.

The other important part is where we grab the ImageBrush Viewbox, which is where we grab only the portion of the image we want for the ImageBrush. This simply uses the input parameters to grab the relevant section of the original image. Neat I think.

Step3 : Randomly Place The 1st 8 Sequentially Obtained Image Portions

Now it wouldn't be much of a puzzle if we laid the squares out in the order that they were obtained, so we need to shake things up a bit. We need some randomness. This is achieved by the following method, where we randomly grab the 8 sequentially obtained unallocated image portions and allocate them to a allocated List<Rectangle>

private void RandomizeTiles()
{
    Random rand = new Random();
    int allocated = 0;
    while (allocated != 8)
    {
        int index = 0;
        if (initialUnallocatedParts.Count > 1)
        {
            index = (int)(rand.NextDouble() * initialUnallocatedParts.Count);
        }
        allocatedParts.Add(initialUnallocatedParts[index]);
        initialUnallocatedParts.RemoveAt(index);
        allocated++;
    }
}

We then need to fill the Grid with these random image portions and a single blank Rectangle which was added to the end of the allocated List<Rectangle>.

int index = 0;
for (int i = 0; i < 3; i++)
{
    for (int j = 0; j < 3; j++)
    {
        allocatedParts[index].SetValue(Grid.RowProperty, i);
        allocatedParts[index].SetValue(Grid.ColumnProperty, j);
        gridMain.Children.Add(allocatedParts[index]);
        index++;
    }
}

Step4 : Allow The User To Click One Of The Image Portion Squares

As we cunningly used Rectangle objects to put into the Grid, we are able to use RoutedEvents. This is because Rectangle is a full blown WPF element, so has routed events. We simply hook into the MouseDown RoutedEvent for each Rectangle. And then see if the Rectangle clicked is allowed to be swapped with the current Blank Rectangle. If it can be swapped, the 2 Rectangles are swapped (reallocated to different Grid Row/Column).

This is done as follows:

private void rectPart_MouseDown(object sender, MouseButtonEventArgs e)
{
    //get the source Rectangle, and the blank Rectangle
    //NOTE : Blank Rectangle never moves, its always the last Rectangle
    //in the allocatedParts List, but it gets re-allocated to 
    //different Gri Row/Column
    Rectangle rectCurrent = sender as Rectangle;
    Rectangle rectBlank = allocatedParts[allocatedParts.Count - 1];


    //get current grid row/col for clicked Rectangle and Blank one
    int currentTileRow = (int)rectCurrent.GetValue(Grid.RowProperty);
    int currentTileCol = (int)rectCurrent.GetValue(Grid.ColumnProperty);
    int currentBlankRow = (int)rectBlank.GetValue(Grid.RowProperty);
    int currentBlankCol = (int)rectBlank.GetValue(Grid.ColumnProperty);


    //create possible valid move positions
    List<PossiblePositions> posibilities = new List<PossiblePositions>();
    posibilities.Add(new PossiblePositions 
        { Row = currentBlankRow - 1, Col = currentBlankCol });
    posibilities.Add(new PossiblePositions 
        { Row = currentBlankRow + 1, Col = currentBlankCol });
    posibilities.Add(new PossiblePositions 
        { Row = currentBlankRow, Col = currentBlankCol-1 });
    posibilities.Add(new PossiblePositions 
        { Row = currentBlankRow, Col = currentBlankCol + 1 });

    //check for valid move
    bool validMove = false;
    foreach (PossiblePositions position in posibilities)
        if (currentTileRow == position.Row && currentTileCol == position.Col)
            validMove = true;

    //only allow valid move
    if (validMove)
    {
        rectCurrent.SetValue(Grid.RowProperty, currentBlankRow);
        rectCurrent.SetValue(Grid.ColumnProperty, currentBlankCol);

        rectBlank.SetValue(Grid.RowProperty, currentTileRow);
        rectBlank.SetValue(Grid.ColumnProperty, currentTileCol);
    }
    else
        return;
}

And that's it. Really simply, as I said in the intro, but you never know you may have just learnt a bit about the WPF ImageBrush. If you have ever seen the Blendables zoom box this is based on the ImageBrush concepts covered in this article.

Anyway why not try your luck. Have a go.

Though I must say I have not been able to complete 1 puzzle at all as yet. I never was much good at these damn puzzles. Grrrrr

History

v1.0 25/04/08

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Sacha Barber


Mvp
I currently hold the following qualifications (amongst others, I also studied Music Technology and Electronics, for my sins)

- MSc (Passed with distinctions), in Information Technology for E-Commerce
- BSc Hons (1st class) in Computer Science & Artificial Intelligence

Both of these at Sussex University UK.

Award(s)

Occupation: Software Developer (Senior)
Location: United Kingdom United Kingdom

Other popular Windows Presentation Foundation articles:

Article Top
Sign Up to vote for this article
You must Sign In to use this message board.
FAQ FAQ Noise ToleranceSearch Search Messages 
 Layout  Per page   
 Msgs 1 to 16 of 16 (Total in Forum: 16) (Refresh)FirstPrevNext
Subject  Author Date 
GeneralAgain ThanksmemberAbhijit Jana19:01 11 Aug '08  
GeneralRe: Again ThanksmvpSacha Barber22:51 11 Aug '08  
GeneralPuzzle SolutionmemberCal Schrotenboer11:02 30 Jul '08  
GeneralRe: Puzzle SolutionmvpSacha Barber23:04 30 Jul '08  
GeneralSimple and neat, very nice!memberravinamballa7:15 7 May '08  
GeneralRe: Simple and neat, very nice!mvpSacha Barber22:10 7 May '08  
GeneralWindows Puzzle FoundationmvpDaniel Vaughan2:31 5 May '08  
GeneralRe: Windows Puzzle FoundationmvpSacha Barber5:15 5 May '08  
GeneralExpression Blend CapabilitiesmemberBlitzPackage3:24 3 May '08  
GeneralRe: Expression Blend CapabilitiesmvpSacha Barber21:29 4 May '08  
GeneralFifteen puzzlememberBert delaVega7:46 29 Apr '08  
GeneralRe: Fifteen puzzlemvpSacha Barber3:57 30 Apr '08  
GeneralWhy didn't you use Web 2.0 AJAX?mvpJosh Smith3:34 29 Apr '08  
GeneralRe: Why didn't you use Web 2.0 AJAX?mvpSacha Barber3:39 29 Apr '08  
GeneralNicemvpKarl Shifflett2:13 29 Apr '08  
GeneralRe: NicemvpSacha Barber2:36 29 Apr '08  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 9 Aug 2008
Editor:
Copyright 2008 by Sacha Barber
Everything else Copyright © CodeProject, 1999-2008
Web15 | Advertise on the Code Project