import React, { useCallback } from 'react' import { useState } from 'react' function…
- User
import React, { useCallback } from 'react' import { useState } from 'react'
function Square({value,handleClick}){// prop is the value
return ( {value} )
}
function Board({square,turn,onPlay}) {// board rerenders whenever a change of state occurs , the square and turn in this case
function calculateWinner(square){ const lines = [ [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 < lines.length; i++) { const [a, b, c] = lines[i]; if (square[a] && square[a] === square[b] && square[a] === square[c]) { return square[a]; } } return null; }
function clickProcess(squareNumber){ // when the square is clicked we need to update the state of theat square , this can be done using set square if (square[squareNumber]|| calculateWinner(square)){ return }// please there is something in the square const nextSquares= square.slice()// create a copy of the square array , avoid direct data manipulation
codeif (turn=="player 1"){ nextSquares[squareNumber]= 'X'// set the data in the copy as x } else{ nextSquares[squareNumber]= 'O' } onPlay(nextSquares) // after the user click on the interface we need to check whether they have won // plan is to go thru the array using a for loop}
const winner = calculateWinner(square); var status; if (winner){ status = "Winner : "+ winner;
code} else{ status = "Next turn :"+ turn }return ( <> {status} <Square value= {square[0]} handleClick={()=>clickProcess(0)}/> <Square value= {square[1]} handleClick={()=>clickProcess(1)}/> <Square value= {square[2]} handleClick={()=>clickProcess(2)}/>
code<div className='board-row'> <Square value= {square[3]} handleClick={()=>clickProcess(3)}/> <Square value= {square[4]} handleClick={()=>clickProcess(4)}/> <Square value= {square[5]} handleClick={()=>clickProcess(5)}/> </div> <div className='board-row'> <Square value= {square[6]} handleClick={()=>clickProcess(6)}/> <Square value= {square[7]} handleClick={()=>clickProcess(7)}/> <Square value= {square[8]} handleClick={()=>clickProcess(8)}/> </div> </> - Assistant