-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscripts.js
More file actions
58 lines (48 loc) · 2.01 KB
/
scripts.js
File metadata and controls
58 lines (48 loc) · 2.01 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
let nextPlayer = 'X'; // takes a value of either 'X' or 'O' according to the game turns
//initalize the game by setting the value inside next-lbl to nextPlayer
//hint: you could use innerText for this
document.getElementById('next-lbl').innerText = nextPlayer;
//This call will create the buttons needed for the gameboard.
createGameBoard()
function createGameBoard()
{
// Programatically add a button with square brackets enclosing an empty space to each cell in the gameboard
for (let i = 1; i <= 9; i++) {
let cell = document.getElementById('c' + i);
cell.innerHTML = '<button>[ ]</button>';
}
let buttons = document.querySelectorAll('button');
for (let i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', takeCell);
}
}
// This function will be used to respond to a click event on any of the board buttons.
function takeCell(event)
{
/*
When the button is clicked, the space inside its square brackets is replaced by the value in the nextPlayer before switching it
*/
let button = event.target;
button.innerText = '[' + nextPlayer + ']';
// Make sure the button is clickable only once (I didn't mention how to do that, look it up :) )
button.disabled = true;
nextPlayer = nextPlayer === 'X' ? 'O' : 'X';
document.getElementById('next-lbl').innerText = nextPlayer;
// Check if the game is over
if (isGameOver())
{
// let the label with the id 'game-over-lbl' display the words 'Game Over' inside <h1> element
document.getElementById('game-over-lbl').innerHTML = '<h1>Game Over</h1>';
}
// I'll leave declaring the winner for your intrinsic motivation, it's not required for this assignment
}
function isGameOver() {
// This function returns true if all the buttons are disabled and false otherwise
let buttons = document.querySelectorAll('button');
for (let i = 0; i < buttons.length; i++) {
if (!buttons[i].disabled) {
return false;
}
}
return true;
}