Created
July 23, 2019 15:49
-
-
Save navio/7de47c669ff2d7c438a61e6dd4277d87 to your computer and use it in GitHub Desktop.
8 Puzzle Game Class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
1 2 3 | |
8 _ 5 | |
4 7 6 | |
1 2 3 | |
8 6 5 | |
4 7 _ | |
*/ | |
const input = [[1,2,3],[8,"_",5],[4,7,6]]; | |
const EMPTY = "_"; | |
class Game { | |
constructor(matrix, empty){ | |
this.matrix = matrix; | |
this.empty = empty; // {x , y} | |
} | |
equals(position1, position2) { | |
if(position1.x === position2.x && position1.y === position2.y){ | |
return false; | |
} | |
return true | |
} | |
changePosition(x,y){ | |
const emptyX = this.empty.x; | |
const emptyY = this.empty.y; | |
let possible = false; | |
this.possibleMoves().forEach( position => { | |
if(this.equals(position, {x,y} )){ | |
possible = true; | |
} | |
}); | |
if(!possible){ | |
console.log("impossible move"); | |
return; | |
} | |
const value = this.matrix[x][y]; | |
this.matrix[x][y] = EMPTY; | |
this.empty = {x, y}; | |
this.matrix[emptyX][emptyY] = value; | |
} | |
possibleMoves() { | |
const {x, y} = this.empty; | |
const moves = []; | |
// Down Value | |
if(this.matrix[x][y-1]){ | |
moves.push({ x , y: y-1, value: this.matrix[x][y-1] }); | |
} | |
// UP Value | |
if(this.matrix[x][y+1]){ | |
moves.push({ x , y: y+1, value: this.matrix[x][y+1] }); | |
} | |
// Left Value | |
if(this.matrix[x+1][y]){ | |
moves.push({ x: x+1 , y, value: this.matrix[x+1][y] }); | |
} | |
// Right Value | |
if(this.matrix[x-1][y]){ | |
moves.push({ x:x-1 , y, value: this.matrix[x-1][y] }); | |
} | |
return moves; | |
} | |
} | |
const game = new Game(input,{x:1,y:1}); | |
game.changePosition(1,2); | |
console.log(game.matrix); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment