-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgame.js
More file actions
84 lines (77 loc) · 2.77 KB
/
game.js
File metadata and controls
84 lines (77 loc) · 2.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
alert("are you human")
document.addEventListener("DOMContentLoaded", () => {
const columns = 7;
const rows = 6;
const board = [];
let currentPlayer = "red";
const statusDisplay = document.getElementById("status");
const createBoard = () => {
const gameBoard = document.getElementById("game-board");
for (let row = 0; row < rows; row++) {
board[row] = [];
for (let col = 0; col < columns; col++) {
const cell = document.createElement("div");
cell.classList.add("cell");
cell.dataset.row = row;
cell.dataset.col = col;
cell.addEventListener("click", handleClick);
gameBoard.appendChild(cell);
board[row][col] = "";
}
}
};
const handleClick = (e) => {
const col = e.target.dataset.col;
for (let row = rows - 1; row >= 0; row--) {
if (board[row][col] === "") {
board[row][col] = currentPlayer;
const cell = document.querySelector(`[data-row='${row}'][data-col='${col}']`);
cell.classList.add(currentPlayer);
if (checkWin(row, col)) {
statusDisplay.textContent = `${currentPlayer.toUpperCase()} wins!`;
disableBoard();
} else if (isBoardFull()) {
statusDisplay.textContent = "It's a draw!";
} else {
currentPlayer = currentPlayer === "red" ? "yellow" : "red";
}
break;
}
}
};
const checkWin = (row, col) => {
return (
checkDirection(row, col, 1, 0) ||
checkDirection(row, col, 0, 1) ||
checkDirection(row, col, 1, 1) ||
checkDirection(row, col, 1, -1)
);
};
const checkDirection = (row, col, rowInc, colInc) => {
let count = 0;
let r = row;
let c = col;
while (r >= 0 && r < rows && c >= 0 && c < columns && board[r][c] === currentPlayer) {
count++;
r += rowInc;
c += colInc;
}
r = row - rowInc;
c = col - colInc;
while (r >= 0 && r < rows && c >= 0 && c < columns && board[r][c] === currentPlayer) {
count++;
r -= rowInc;
c -= colInc;
}
return count >= 4;
};
const isBoardFull = () => {
return board.flat().every(cell => cell !== "");
};
const disableBoard = () => {
document.querySelectorAll(".cell").forEach(cell => {
cell.removeEventListener("click", handleClick);
});
};
createBoard();
});