-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
88 lines (69 loc) · 2.05 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
import { useState } from "react";
import { Text, TouchableOpacity, Button } from "react-native";
import { VStack, HStack, Flex } from "react-native-flex-layout";
import checkWinner from "./checkWinner";
function Box({ value, onPress, disabled, highlighted }) {
return (
<TouchableOpacity disabled={disabled} onPress={onPress}>
<Flex w={90} h={90} center style={{ backgroundColor: highlighted ? "lightgreen" : "lightgray" }}>
<Text style={{ fontSize: 50 }}>{value}</Text>
</Flex>
</TouchableOpacity>
);
}
function App() {
const [currentPlayer, setCurrentPlayer] = useState("X");
const [board, setBoard] = useState(Array(9).fill(null));
const [highlighted, setHighlighted] = useState([]);
const [winner, setWinner] = useState(null);
const handlePress = (index) => {
const newBoard = [...board];
newBoard[index] = currentPlayer;
setBoard(newBoard);
const winnerLine = checkWinner(newBoard);
if (winnerLine) {
setHighlighted(winnerLine)
setWinner(currentPlayer)
alert(`${currentPlayer} won!`)
}
else {
setCurrentPlayer((prev) => (prev === "X" ? "O" : "X"));
}
};
const handleReset = () => {
setCurrentPlayer("X")
setBoard(Array(9).fill(null));
setHighlighted([]);
setWinner(null);
}
const getBox = (index) => (
<Box
value={board[index]}
onPress={() => handlePress(index)}
highlighted={highlighted.includes(index)}
disabled={winner || board[index]}
/>
);
return (
<VStack fill center spacing={5}>
<Text style={{ fontSize: 40 }}>{currentPlayer} to Play</Text>
<HStack spacing={5} shouldWrapChildren>
{getBox(0)}
{getBox(1)}
{getBox(2)}
</HStack>
<HStack spacing={5} shouldWrapChildren>
{getBox(3)}
{getBox(4)}
{getBox(5)}
</HStack>
<HStack spacing={5} shouldWrapChildren>
{getBox(6)}
{getBox(7)}
{getBox(8)}
</HStack>
<Button title="Reset" onPress={handleReset} />
</VStack>
)
}
export default App;