1+ import { useState } from "react" ;
2+ import Square from "../Square" ;
3+ import { nextTick } from "process" ;
4+
5+ export default function Board ( ) {
6+ const [ squares , setSquares ] = useState < Array < String | null > > ( Array ( 9 ) . fill ( null ) ) ;
7+ const [ isXNext , setIsXNext ] = useState ( true ) ;
8+
9+ const calculateWinner = ( ) => {
10+ const lines = [
11+ [ 0 , 1 , 2 ] ,
12+ [ 3 , 4 , 5 ] ,
13+ [ 6 , 7 , 8 ] ,
14+ [ 0 , 3 , 6 ] ,
15+ [ 1 , 4 , 7 ] ,
16+ [ 2 , 5 , 8 ] ,
17+ [ 0 , 4 , 8 ] ,
18+ [ 2 , 4 , 6 ]
19+ ] ;
20+
21+ for ( let i = 0 ; i < lines . length ; i ++ ) {
22+ console . log ( "called" ) ;
23+ const [ a , b , c ] = lines [ i ] ;
24+
25+ if ( squares [ a ] && squares [ a ] == squares [ b ] && squares [ a ] == squares [ c ] ) {
26+ return squares [ a ] ;
27+ }
28+
29+ }
30+ return null ;
31+
32+ }
33+
34+ const handleClick = ( i : number ) => {
35+ const squaresCopy = squares . slice ( ) ;
36+ if ( squaresCopy [ i ] || calculateWinner ( ) ) {
37+ return ;
38+ }
39+ squaresCopy [ i ] = isXNext ? 'X' : 'O' ;
40+ setSquares ( squaresCopy ) ;
41+ setIsXNext ( ! isXNext ) ;
42+ }
43+
44+ const status = ( ) => {
45+ const winner = calculateWinner ( ) ;
46+ if ( winner ) {
47+ return `Winner is ${ winner } ` ;
48+ }
49+ }
50+
51+ return (
52+ < >
53+ < div className = 'board-row' >
54+ < Square value = { squares [ 0 ] } OnSquareClicked = { ( ) => handleClick ( 0 ) } />
55+ < Square value = { squares [ 1 ] } OnSquareClicked = { ( ) => handleClick ( 1 ) } />
56+ < Square value = { squares [ 2 ] } OnSquareClicked = { ( ) => handleClick ( 2 ) } />
57+ </ div >
58+ < div className = 'board-row' >
59+ < Square value = { squares [ 3 ] } OnSquareClicked = { ( ) => handleClick ( 3 ) } />
60+ < Square value = { squares [ 4 ] } OnSquareClicked = { ( ) => handleClick ( 4 ) } />
61+ < Square value = { squares [ 5 ] } OnSquareClicked = { ( ) => handleClick ( 5 ) } />
62+ </ div >
63+ < div className = 'board-row' >
64+ < Square value = { squares [ 6 ] } OnSquareClicked = { ( ) => handleClick ( 6 ) } />
65+ < Square value = { squares [ 7 ] } OnSquareClicked = { ( ) => handleClick ( 7 ) } />
66+ < Square value = { squares [ 8 ] } OnSquareClicked = { ( ) => handleClick ( 8 ) } />
67+ </ div >
68+ < div > { status ( ) } </ div >
69+ </ >
70+ )
71+ }
0 commit comments