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. Because of this 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. I would appreciate any help.
Thanks
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);
}
}
If I were you I would separate out your model from your UI.
Create a class called
Puzzle. This class will hold the state of puzzle and perform all operations on the state.It’s likely that you might implement
MoveLeft,MoveRight,MoveUp&MoveDownmethods. To shuffle your board you could just perform a (fairly long) series of moves by calling these four methods randomly.Your
Puzzleclass would need to expose enough state for the UI to render itself.Doing it this way you can simplify your code and make unit testing much simpler.