-
Notifications
You must be signed in to change notification settings - Fork 0
/
logic.js
115 lines (101 loc) · 2.16 KB
/
logic.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
let players = ['x', 'o'];
let activePlayer = 0;
let board, emptyBoard = [
['', '', ''],
['', '', ''],
['', '', '']
];
function startGame() {
let randomNumber = Math.random();
board = emptyBoard;
if (randomNumber < 0.5) {
activePlayer = 0;
} else {
activePlayer = 1;
} // Установить активного игрока
renderBoard(board); // функция для отрисовки игрового поля
}
function switchPlayer() {
if (activePlayer) {
activePlayer = 0;
} else {
activePlayer = 1;
}
isTie();
}
function click(row, col) {
if (board[row][col] === '') {
board[row][col] = players[activePlayer];
}
renderBoard(board);
calculateVictory(row, col, players[activePlayer]);
switchPlayer();
isTie();
}
function calculateVictory(row, col, symbol) {
//проверка столбца
let victoryCondition = true;
for (i = 0; i < board.length; i++) {
if (board[i][col] !== symbol) {
victoryCondition = false;
break;
}
}
if (victoryCondition) {
showWinner(symbol);
return;
}
//проверка строки
victoryCondition = true;
for (i = 0; i < board.length; i++) {
if (board[row][i] != symbol) {
victoryCondition = false;
break;
}
}
if (victoryCondition) {
showWinner(symbol);
return;
}
//проверка диагонали
victoryCondition = true;
for (i = 0; i < board.length; i++) {
if (board[i][i] !== symbol) {
victoryCondition = false;
break;
}
}
if (victoryCondition) {
showWinner(symbol);
return;
}
//проверка обратной диагонали
victoryCondition = true;
for (i = 0; i < board.length; i++) {
if (board[i][board.length - 1 - i] !== symbol) {
victoryCondition = false;
break;
}
}
if (victoryCondition) {
showWinner(symbol);
return;
}
}
function isTie() {
let isTie = true;
for (i = 0; i < board.length; i++) {
for (j = 0; j < board[i].length; j++) {
if (board[i][j] == "") {
isTie = false;
break;
}
}
if (!isTie) {
break;
}
}
if (isTie) {
itsDraw();
}
}