import React from 'react' import { useState } from 'react' function…
- User
import React from 'react' import { useState } from 'react'
function Square({value,handleClick}){// prop is the value
return ( {value} )
}
export default function Board() { const [square,setSquare]= useState(Array(9).fill(null)) const [turn,setTurn]= useState("player 1")
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
if (turn=="player 1"){ nextSquares[squareNumber]= 'X'// set the data in the copy as x setTurn("player 2") } else{ nextSquares[squareNumber]= 'O' setTurn("player 1") } setSquare(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; } 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)}/>
<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> </>)
}
where is the error
- Assistant
- User
if i put the winner outside of either of the functions then when will it run
- Assistant
- User
setHistory([...history, nextSquares]); what does this line of syntax do
- Assistant
- User
how can i extend the above projects and let people create user accounts and game rooms , will this need backend node.js
- Assistant