How can I guarantee a solvable Fifteen Puzzle shuffle?

Posted by Codemiester on Game Development See other posts from Game Development or by Codemiester
Published on 2012-10-16T01:17:19Z Indexed on 2012/10/16 17:22 UTC
Read the original article Hit count: 154

Filed under:
|
|

I am making a 15 Puzzle game in C# that allows the user to enter a custom row and column value up to a maximum of a 10 x 10 puzzle. I am having problems with the shuffle method.

I want to make it so the puzzle is always solvable by first creating a winning puzzle then shuffling the empty space. The problem is it is too inefficient to call every click event each time. I need a way to invoke the click event of a button adjacent to the empty space but not diagonal. I also use an invisible static button for the empty spot. The PuzzlePiece class inherits from Button. I am not too sure how to do this.

Here is what I have:

private void shuffleBoard()
    {
        //5 is just for test purposes
        for (int i = 0; i < 5; i++)
        {
            foreach (Control item in this.Controls)
            {
                if (item is PuzzlePiece)
                {
                    ((PuzzlePiece)item).PerformClick();
                }
            }
        }
    }

 void PuzzlePiece_Click(object sender, EventArgs e)
    {
        PuzzlePiece piece = (PuzzlePiece)sender;

        if (piece.Right == puzzleForm.emptyPiece.Left && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Left == puzzleForm.emptyPiece.Right && piece.Top == puzzleForm.emptyPiece.Top)
        {
            movePiece(piece);
        }
        else if (piece.Top == puzzleForm.emptyPiece.Bottom && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
        else if (piece.Bottom == puzzleForm.emptyPiece.Top && piece.Left == puzzleForm.emptyPiece.Left)
        {
            movePiece(piece);
        }
    }

© Game Development or respective owner

Related posts about c#

Related posts about .NET