I hate the current algorithm for checking if user can move in the game just because I am using 4 for loops and 3 functions.
Current Approach:
The current approach is to use this.canMove which calls upon this.canHorMove and this.canVerMove to determine if you can move.
this.canHorMove
First checks if there is a 0 in the sub array, return true because there is space for a new block to render. Then it loops through another level to check if there is an adj block to the right with a matching pair. It uses a helper function getValue() that gets the value of the block.
this.canVerMove
Loops through 2 levels to check if there is an adj block to the bottom with a matching pair. It uses a helper function getValue() that gets the value of the block.
Pros:
- it works
- readable
- easy to understand
Cons:
- too many lines of code
- 4 for loops (not a problem for going through a small scale data structure like this, but would be a problem for a more complex data structure with more entities.
this.map = [
[ 0,0,0,0],
[ 0,0,0,0],
[ 0,0,0,0],
[ 0,0,0,0]
]
This.map contains the id of the block.
const getValue = function (board, id) {
if (id) {
return id !== 0 ? board.blocks[id].value : 0
} else {
return 0
}
}
GameObj.prototype.canMove = function () {
return this.canHorMove() || this.canVerMove()
}
// check if there are 0 in the row , if (y) return true
// check if there is a adj horizontal matchable block, (Y) return true
GameObj.prototype.canHorMove = function () {
let board = this.map
for (let r = 0; r < board.length; r++) {
if (board[r].includes(0)) {
return true
}
for (let c = 0; c < board.length - 1; c++) {
if (getValue(this, board[r][c]) === getValue(this, board[r][c + 1])) {
return true
}
}
}
return false
}
// check if there is a adj vertical matchable block, (Y) return true
GameObj.prototype.canVerMove = function () {
let board = this.map
for (let r = 0; r < board.length - 1; r++) {
for (let c = 0; c < board.length; c++) {
if (getValue(this, board[r][c]) === getValue(this, board[r + 1][c])) {
return true
}
}
}
return false
}
I hate the current algorithm for checking if user can move in the game just because I am using 4 for loops and 3 functions.
Current Approach:
The current approach is to use
this.canMovewhich calls uponthis.canHorMoveandthis.canVerMoveto determine if you can move.this.canHorMoveFirst checks if there is a 0 in the sub array, return true because there is space for a new block to render. Then it loops through another level to check if there is an adj block to the right with a matching pair. It uses a helper function
getValue()that gets the value of the block.this.canVerMoveLoops through 2 levels to check if there is an adj block to the bottom with a matching pair. It uses a helper function
getValue()that gets the value of the block.Pros:
Cons:
This.map contains the id of the block.