So basically I have a class called Board (this is all for a sudoku website + solver) and it has a constructor that assigns into the property board
as you see below
class Board {
constructor(board) {
this.board = board;
}
// some other properties
}
function makeBoard(boardlength) {
// returns a 2d boardLength x boardLength array of zeros
}
then I have two instances of this class
var mainBoard = new Board(makeBoard(9));
var generatedBoard = new Board(makeBoard(9));
in the Board
class there is a property generateBoard()
that generates a random sudoku puzzle into the 9x9 2d array stored in generatedBoard.board
upon pressing a button on the screen as follow:
document.getElementById('generate').addEventListener('click', function() {
generatedBoard.generateBoard();
mainBoard.board = generatedBoard.board;
generatedBoard.updateBoardHTML();
})
This is the only line where generatedBoard.board
is stored into mainBoard.board
The main problem is:
there is an event listener for key presses (specifically digits 1 to 9) so that the user can solve the board themselves and this part is supposed to take the number input from the user, and store it in the generatedBoard.board
2d array. But, when this happens, for some reason the number ALSO gets stored into the mainBoard.board
2d array and that is the bug I am trying to solve.
Here is the code for the eventListener for the key press but there are some unexplained bits in it:
document.addEventListener('keydown', function(event) {
if (keyCodes.includes(event.keyCode)) {
for (let j = 0; j < generatedBoard.board.length; j++) {
for (let i = 0; i < generatedBoard.board[j].length; i++) {
if (document.getElementById(j + '-' + i).style.background === 'rgb(197, 197, 197)') {
const solution = event.keyCode - 48;
debugger;
generatedBoard.board[j][i] = solution;
if (solution === 0) {
document.getElementById(j + '-' + i).innerHTML = '';
} else {
document.getElementById(j + '-' + i).innerHTML = solution
}
}
}
}
}
})
As you can see the code should only assign the key pressed by the user into generatedBoard.board
as i wrote generatedBoard.board[j][i] = solution
but for some reason when this specific line executes, it does the same for mainBoard.board