I'm developing 8 puzzle game using javascript, I shuffle the tiles by shuffling the puzzle tiles array
var shuffleArray = (array) => {
var currentIndex = array.length, temporaryValue, randomIndex;
while (0 !== currentIndex) {
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
};
I want to give the user the option to choose difficulty: easy, medium, hard, How can I implment this?
I will explain a little bit my implmentation. (this is typescript)
The puzzle array is an array of class PuzzleNode
export class PuzzleNode {
goal: Node;
current: Node;
}
When I shuffle I don't touch the puzzleArray but I shuffle the current
property like so
shuffle() {
this.shuffledNodes = shuffleArray(this.shuffledNodes);
for (let i = 0; i < this.shuffledNodes.length; i++) {
this.puzzleNodes[i].current = this.shuffledNodes[i];
}
/** Keep shuffling until getting a solvable puzzle */
if (!this.isSolvable()) {
this.shuffle();
}
}
This way I can reach any node using the index, because the index doesn't change even after shuffling, for instance the blank tile is always puzzleNodes[8]
The way to vary the difficulty would be to reduce or increase the number of moves required to solve it.
I think the best way to go about this is to implement the shuffling algorithm as a reverse of the way it will be solved: while shuffling, only pick legal moves (move a piece into an adjacent gap), and repeat this randomly for a certain number of moves until it's sufficiently shuffled.
For easy mode, only do about 5 moves. For hard, do 30 moves. A puzzle that requires 5 moves to solve will be a lot easier.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With