I am working on an N-Puzzle game (also known as a 15-puzzle ...) where you split an image into a square grid, delete one part and mix it up. I'm not interested in solving the puzzle, as it depends on the user. But I would like to shuffle the board in a pseudo-random way.
I know that 1/2 of all possible tasses will make the board unsolvable. Is there an easy way psuedo-randomly generate a shuffled state, assuming I have a rand () function - esc, and I know the size of the board?
I have a game board in memory, a multidimensional array of integers. My method simply puts the images in the opposite order, switching the last from the second to the last image on even boards. My current function is below and I am working in Java.
private void shuffle()
{
gameState = new int[difficulty][difficulty];
int i = 0, N = (difficulty * difficulty) -1;
while (i < N)
gameState[(int)(i / difficulty)][i % difficulty] = N - ++i;
gameState[difficulty-1][difficulty-1] = N;
if ((difficulty % 2) == 0)
{
int tmpEl = gameState[difficulty-1][difficulty-2];
if (difficulty == 2)
{
gameState[1][0] = gameState[0][1];
gameState[0][1] = tmpEl;
}
else
{
gameState[difficulty-1][difficulty-2] = gameState[difficulty-1][difficulty-3];
gameState[difficulty-1][difficulty-3] = tmpEl;
}
}
}