-
Notifications
You must be signed in to change notification settings - Fork 1
/
connect4.js
45 lines (41 loc) · 1.46 KB
/
connect4.js
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
const PLAYER1 = "red";
const PLAYER2 = "yellow";
function createBoard(board) {
// Inject stylesheet.
const linkElement = document.createElement("link");
linkElement.href = import.meta.url.replace(".js", ".css");
linkElement.rel = "stylesheet";
document.head.append(linkElement);
// Generate board.
for (let column = 0; column < 7; column++) {
const columnElement = document.createElement("div");
columnElement.className = "column";
columnElement.dataset.column = column;
for (let row = 0; row < 6; row++) {
const cellElement = document.createElement("div");
cellElement.className = "cell empty";
cellElement.dataset.column = column;
columnElement.append(cellElement);
}
board.append(columnElement);
}
}
function playMove(board, player, column, row) {
// Check values of arguments.
if (player !== PLAYER1 && player !== PLAYER2) {
throw new Error(`player must be ${PLAYER1} or ${PLAYER2}.`);
}
const columnElement = board.querySelectorAll(".column")[column];
if (columnElement === undefined) {
throw new RangeError("column must be between 0 and 6.");
}
const cellElement = columnElement.querySelectorAll(".cell")[row];
if (cellElement === undefined) {
throw new RangeError("row must be between 0 and 5.");
}
// Place checker in cell.
if (!cellElement.classList.replace("empty", player)) {
throw new Error("cell must be empty.");
}
}
export { PLAYER1, PLAYER2, createBoard, playMove };