I'm new to JavaScript and working on programming a 2048 game. I have a matrix that is modified every time an arrow key is pressed. I want to save a version of the matrix in the variable originalBoard before it is modified so that it can be compared to the modified matrix later. The following is the function I use when the up arrow is pressed and it works successfully:
function slideUp() {
originalBoard = board
board = board[0].map((val, index) => board.map(row => row[row.length-1-index]));
for (let r = 0; r < rows; r++) {
let row = board[r]
row = slide(row)
board[r] = row
}
board = board[0].map((val, index) => board.map(row => row[index]).reverse())
if (notEqual(board, originalBoard)) {
addNewNum()
}
tileUI()
}
However I have the following function which I use for the left key:
function slideLeft() {
originalBoard = board
for (let r = 0; r < rows; r++) {
let row = board[r]
row = slide(row)
board[r] = row
}
if (notEqual(board, originalBoard)) {
addNewNum()
}
tileUI()
}
Whenever the left key is pressed, the matrix that is saved to the variable originalBoard is identical to modified matrix, even though originalBoard is saved before the matrix is modified. The following is the slide function which is used to update the matrix:
function slide(row) {
row = filterZero(row)
for (let i = 0; i < row.length - 1; i ++) {
if (row[i] == row[i + 1]) {
row[i] = row[i] + row[i + 1]
row[i + 1] = 0
score += row[i]
}
}
row = filterZero(row)
while(row.length < 4) {
row.push(0)
}
return row
}
How come the originalBoard variable is saved as the matrix after it is modified even though it is declared before the slide() function is called? The originalBoard variable is saved correctly for the slideUp() and slideDown() functions. It is only the slideLeft() and slideRight() functions where this occurs.
I've tried logging the board variable right when I log the keystrokes:
document.addEventListener('keyup', (e) => {
if (e.code == 'ArrowLeft') {
console.log(board)
slideLeft()
}
if(e.code == 'ArrowRight') {
console.log(board)
slideRight()
}
if(e.code == 'ArrowUp') {
console.log(board)
slideUp()
}
if(e.code == 'ArrowDown') {
console.log(board)
slideDown()
}
})
On left and right keystrokes, board is still logged as the matrix after the slideLeft() and slideRight() functions are applied, even though they're being logged before those functions are called. On the down and up keystrokes, however, the board variable is logged correctly and the console shows the matrix before the slide function is applied.