-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
74 lines (56 loc) · 1.97 KB
/
main.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
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
import init, { getState, takePlayerCell, nextTurn, checkPlayerWin, getTurn, clearGame } from './pkg/tictactoe_wasm.js';
init().then(() => {
const root = document.body;
function render() {
root.innerHTML = '';
root.classList.add('game_main', 'game_size');
const state = getState();
state.split('\n').map(function (row, rowIndex) {
row
.trim()
.split(/\s+/)
.map(function (cell, celIndex) {
const cellElement = document.createElement('a');
cellElement.classList.add('game_cell');
cellElement.href = '#';
cellElement.innerText = cell.toString();
function handler(e) {
e.preventDefault();
// console.log(`Taking: (${rowIndex}, ${celIndex})`);
if (!takePlayerCell(rowIndex, celIndex)) {
alert('This cell is taken');
return;
}
if (checkPlayerWin()) {
root.innerHTML = '';
root.classList.remove('game_main');
const main = document.createElement('div');
main.innerText = getTurn() == 0 ? '🟥 won' : '🟪 won';
const newGame = document.createElement('div');
newGame.style.cursor = 'pointer';
newGame.style.color = 'blue';
newGame.style.backgroundColor = '#e7e7e785';
newGame.style.borderRadius = '3px';
newGame.innerText = 'Start new game';
newGame.addEventListener(
'click',
function () {
clearGame();
render();
},
{ once: true }
);
root.appendChild(main);
root.appendChild(newGame);
return;
}
nextTurn();
render();
}
cellElement.addEventListener('click', handler);
root.appendChild(cellElement);
});
});
}
render();
});