-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathField.jsx
61 lines (51 loc) · 1.34 KB
/
Field.jsx
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
import { useDispatch, useSelector } from "react-redux"
import {
setCurrentPlayer,
setField,
setIsDraw,
setIsGameEnded,
} from "../../actions"
import FieldLayout from "./FieldLayout"
export default function Field() {
const dispatch = useDispatch()
const { field, isGameEnded, currentPlayer } = useSelector((state) => state)
const handleSquareClick = (index) => {
if (field[index] || isGameEnded) {
return
}
const newField = [...field]
newField[index] = currentPlayer
dispatch(setField(newField))
const winner = calculateWinner(newField)
if (winner) {
dispatch(setIsGameEnded(true))
return
}
if (newField.every((cell) => cell)) {
dispatch(setIsDraw(true))
dispatch(setIsGameEnded(true))
return
}
dispatch(setCurrentPlayer(currentPlayer === "X" ? "O" : "X"))
}
const calculateWinner = (field) => {
const WIN_PATTERNS = [
[0, 1, 2],
[3, 4, 5],
[6, 7, 8],
[0, 3, 6],
[1, 4, 7],
[2, 5, 8],
[0, 4, 8],
[2, 4, 6],
]
for (let i = 0; i < WIN_PATTERNS.length; i++) {
const [a, b, c] = WIN_PATTERNS[i]
if (field[a] && field[a] === field[b] && field[a] === field[c]) {
return field[a]
}
}
return null
}
return <FieldLayout handleSquareClick={handleSquareClick} field={field} />
}