Making a connect 4 using vanilla JavaScript. Using an event listener "click" to insert a colored disk into a column. The disks keep stacking infinitely. I need it to stop after 6. And then 42 total.
I have it divided into 7 columns. Each having their own event handler for the "click". How do I get it to insert each click into an array?
https://youtu.be/Jqm5m75pq6A
Here is an example of what I have
let gameBoard = [
[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null],
[null, null, null, null, null, null, null],
];
let column0 = document.querySelector("#column0");
let column1 = document.querySelector("#column1");
let column2 = document.querySelector("#column2");
let column3 = document.querySelector("#column3");
let column4 = document.querySelector("#column4");
let column5 = document.querySelector("#column5");
let column6 = document.querySelector("#column6");
column0.addEventListener("click", function () {
// console.log("column 1");
if (currentPlayer === 1) {
// column1.innerHTML =
let black = document.createElement("span");
black.className = "blackDisc";
column0.append(black);
currentPlayer += 1;
console.log("Current player:" + currentPlayer);
discCount++;
gameBoard[5][0] = 1;
console.log(currentPlayer);
} else if (currentPlayer === 2) {
let red = document.createElement("span");
red.className = "redDisc";
column0.append(red);
currentPlayer -= 1;
console.log("current player:" + currentPlayer);
discCount += 1;
gameBoard[5][0] = 2;
}
});
>Solution :
You could just count how many child elements are in the column.
let column0 = document.querySelector("#column0");
column0.addEventListener("click", function () {
if ( column0.querySelectorAll( 'span' ).length < 7 ) {
// do game logic here only if there aren't 6 spans in the column
You can do similar for all spans on the entire board if you have reference to an outer container to do the querySelectorAll() from.
The other option would be to store your data in your gameBoard array and check the values. This way would probably be faster, but a little more complicated.