forked from Savinvadim1312/TicTacToe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
320 lines (286 loc) · 7.34 KB
/
App.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
import { StatusBar } from "expo-status-bar";
import React, { useState, useEffect } from "react";
import {
StyleSheet,
Text,
View,
ImageBackground,
Pressable,
Alert,
} from "react-native";
import bg from "./assets/bg.jpeg";
import Cell from "./src/components/Cell";
const emptyMap = [
["", "", ""], // 1st row
["", "", ""], // 2nd row
["", "", ""], // 3rd row
];
const copyArray = (original) => {
console.log("ghe");
console.log(original);
const copy = original.map((arr) => {
return arr.slice();
});
console.log(copy);
return copy;
};
export default function App() {
const [map, setMap] = useState(emptyMap);
const [currentTurn, setCurrentTurn] = useState("x");
const [gameMode, setGameMode] = useState("BOT_MEDIUM"); // LOCAL, BOT_EASY, BOT_MEDIUM;
useEffect(() => {
if (currentTurn === "o" && gameMode !== "LOCAL") {
botTurn();
}
}, [currentTurn, gameMode]);
useEffect(() => {
const winner = getWinner(map);
if (winner) {
gameWon(winner);
} else {
checkTieState();
}
}, [map]);
const onPress = (rowIndex, columnIndex) => {
if (map[rowIndex][columnIndex] !== "") {
Alert.alert("Position already occupied");
return;
}
setMap((existingMap) => {
const updatedMap = [...existingMap];
updatedMap[rowIndex][columnIndex] = currentTurn;
return updatedMap;
});
setCurrentTurn(currentTurn === "x" ? "o" : "x");
};
const getWinner = (winnerMap) => {
// Check rows
for (let i = 0; i < 3; i++) {
const isRowXWinning = winnerMap[i].every((cell) => cell === "x");
const isRowOWinning = winnerMap[i].every((cell) => cell === "o");
if (isRowXWinning) {
return "x";
}
if (isRowOWinning) {
return "o";
}
}
// Check columns
for (let col = 0; col < 3; col++) {
let isColumnXWinner = true;
let isColumnOWinner = true;
for (let row = 0; row < 3; row++) {
if (winnerMap[row][col] !== "x") {
isColumnXWinner = false;
}
if (winnerMap[row][col] !== "o") {
isColumnOWinner = false;
}
}
if (isColumnXWinner) {
return "x";
}
if (isColumnOWinner) {
return "o";
}
}
// check diagonals
let isDiagonal1OWinning = true;
let isDiagonal1XWinning = true;
let isDiagonal2OWinning = true;
let isDiagonal2XWinning = true;
for (let i = 0; i < 3; i++) {
if (winnerMap[i][i] !== "o") {
isDiagonal1OWinning = false;
}
if (winnerMap[i][i] !== "x") {
isDiagonal1XWinning = false;
}
if (winnerMap[i][2 - i] !== "o") {
isDiagonal2OWinning = false;
}
if (winnerMap[i][2 - i] !== "x") {
isDiagonal2XWinning = false;
}
}
if (isDiagonal1OWinning || isDiagonal2OWinning) {
return "o";
}
if (isDiagonal1XWinning || isDiagonal2XWinning) {
return "x";
}
};
const checkTieState = () => {
if (!map.some((row) => row.some((cell) => cell === ""))) {
Alert.alert(`It's a tie`, `tie`, [
{
text: "Restart",
onPress: resetGame,
},
]);
}
};
const gameWon = (player) => {
Alert.alert(`Huraaay`, `Player ${player} won`, [
{
text: "Restart",
onPress: resetGame,
},
]);
};
const resetGame = () => {
setMap([
["", "", ""], // 1st row
["", "", ""], // 2nd row
["", "", ""], // 3rd row
]);
setCurrentTurn("x");
};
const botTurn = () => {
// collect all possible options
const possiblePositions = [];
map.forEach((row, rowIndex) => {
row.forEach((cell, columnIndex) => {
if (cell === "") {
possiblePositions.push({ row: rowIndex, col: columnIndex });
}
});
});
let chosenOption;
if (gameMode === "BOT_MEDIUM") {
// Attack
possiblePositions.forEach((possiblePosition) => {
const mapCopy = copyArray(map);
mapCopy[possiblePosition.row][possiblePosition.col] = "o";
const winner = getWinner(mapCopy);
if (winner === "o") {
// Attack that position
chosenOption = possiblePosition;
}
});
if (!chosenOption) {
// Defend
// Check if the opponent WINS if it takes one of the possible Positions
possiblePositions.forEach((possiblePosition) => {
const mapCopy = copyArray(map);
mapCopy[possiblePosition.row][possiblePosition.col] = "x";
const winner = getWinner(mapCopy);
if (winner === "x") {
// Defend that position
chosenOption = possiblePosition;
}
});
}
}
// choose random
if (!chosenOption) {
chosenOption =
possiblePositions[Math.floor(Math.random() * possiblePositions.length)];
}
if (chosenOption) {
onPress(chosenOption.row, chosenOption.col);
}
};
return (
<View style={styles.container}>
<ImageBackground source={bg} style={styles.bg} resizeMode="contain">
<Text
style={{
fontSize: 24,
color: "white",
position: "absolute",
top: 50,
}}
>
Current Turn: {currentTurn.toUpperCase()}
</Text>
<View style={styles.map}>
{map.map((row, rowIndex) => (
<View key={`row-${rowIndex}`} style={styles.row}>
{row.map((cell, columnIndex) => (
<Cell
key={`row-${rowIndex}-col-${columnIndex}`}
cell={cell}
onPress={() => onPress(rowIndex, columnIndex)}
/>
))}
</View>
))}
</View>
<View style={styles.buttons}>
<Text
onPress={() => setGameMode("LOCAL")}
style={[
styles.button,
{ backgroundColor: gameMode === "LOCAL" ? "#4F5686" : "#191F24" },
]}
>
Local
</Text>
<Text
onPress={() => setGameMode("BOT_EASY")}
style={[
styles.button,
{
backgroundColor:
gameMode === "BOT_EASY" ? "#4F5686" : "#191F24",
},
]}
>
Easy Bot
</Text>
<Text
onPress={() => setGameMode("BOT_MEDIUM")}
style={[
styles.button,
{
backgroundColor:
gameMode === "BOT_MEDIUM" ? "#4F5686" : "#191F24",
},
]}
>
Medium Bot
</Text>
</View>
</ImageBackground>
<StatusBar style="auto" />
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#fff",
alignItems: "center",
justifyContent: "center",
backgroundColor: "#242D34",
},
bg: {
width: "100%",
height: "100%",
alignItems: "center",
justifyContent: "center",
paddingTop: 15,
},
map: {
width: "80%",
aspectRatio: 1,
},
row: {
flex: 1,
flexDirection: "row",
},
buttons: {
position: "absolute",
bottom: 50,
flexDirection: "row",
},
button: {
color: "white",
margin: 10,
fontSize: 16,
backgroundColor: "#191F24",
padding: 10,
paddingHorizontal: 15,
},
});