我正在研究N-Puzzle遊戲(也稱爲15-謎題...),您可以在一個方形網格上拆分圖像,移除一個部分並隨機播放。我對這個難題的解決方案不太感興趣,因爲這取決於用戶。但我想僞隨機洗牌。N-Puzzle僞隨機洗牌?
我知道1/2所有可能的洗牌都會讓董事會無法解決。假設我有一些rand() - esc函數,並且我知道棋盤大小,是否有一種簡單的方法可以隨意地生成混洗狀態?
我在內存中有一個遊戲板,一個整數的多維數組。 我的方法只是將圖像按照相反的順序放置,在偶數板上將第二張圖像切換爲最後一張圖像。 我目前的功能在下面,我正在使用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;
// N id even when the remainder of N/2 is 0
if ((difficulty % 2) == 0)
{
// swap 2nd to last and 3rd to last element
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;
}
}
}
可能的重複[如何確保當我洗牌我的謎題時,我仍然以偶數排列?](http://stackoverflow.com/questions/2653694/how-can-i-ensure-that-當我洗牌我的謎題我仍然結束與一個偶數permut) – 2011-05-24 02:01:19