-
Notifications
You must be signed in to change notification settings - Fork 0
/
script_bot.js
92 lines (73 loc) · 2.06 KB
/
script_bot.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
console.log("new file");
const board = document.getElementById('board');
const cells = [];
let currentPlayer = 'X';
let xMoves = [];
let oMoves = [];
const winningCombinations = [ // Alle möglichen Gewinnkombinationen
// Reihen
[0, 1, 2], // Erste Reihe
[3, 4, 5], // Zweite Reihe
[6, 7, 8], // Dritte Reihe
// Spalten
[0, 3, 6], // Erste Spalte
[1, 4, 7], // Zweite Spalte
[2, 5, 8], // Dritte Spalte
// Diagonalen
[0, 4, 8], // Erste Diagonale
[2, 4, 6] // Zweite Diagonale
];
function createBoard() {
for (let i = 0; i < 9; i++) {
const cell = document.createElement('div');
cell.classList.add('cell');
board.appendChild(cell);
cells.push(cell);
cell.addEventListener('click', () => makeMove(i));
}
}
function makeMove(i) {
if (cells[i].textContent === '') {
cells[i].textContent = currentPlayer;
if (currentPlayer === 'X') {
currentPlayer = 'O';
cells[i].style.backgroundColor = 'lightblue';
xMoves.push(i);
} else {
currentPlayer = 'X';
cells[i].style.backgroundColor = 'lightcoral';
oMoves.push(i);
}
gameFinished();
};
}
function gameFinished() {
for (let i = 0; i < winningCombinations.length; i++) {
const combination = winningCombinations[i];
if (combination.every((value) => xMoves.includes(value))) {
finishGame("Player X wins");
return;
}
if (combination.every((value) => oMoves.includes(value))) {
finishGame("Player O wins");
return;
}
}
const totalMoves = xMoves.length + oMoves.length;
if (totalMoves === 9) {
finishGame("Draw!")
return;
}
}
function botMove() {
const index = 5;
cells[index].textContent = "O";
cells[index].style.backgroundColor = 'lightcoral';
oMoves.push(index);
}
function finishGame(text) {
setTimeout(() => {
if (!alert(text)) { window.location.reload(); }
}, 100)
}
createBoard();