Murhaf Sousli Murhaf Sousli - 1 month ago 22
Javascript Question

How to adjust randomization level javascript

I'm developing 8 puzzle game using javascript, I shuffle the tiles by shuffling the puzzle tiles array

enter image description here

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?

Update:



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.prepNodes = shuffleArray(this.prepNodes);
for (let i = 0; i < this.prepNodes.length; i++) {
this.nodes[i].current = this.prepNodes[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]

Answer

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.