作为一名应届毕业生,我在面试时经常遇到井字棋问题,尤其是在前端职位。这是一道多功能题,有效考验考生的前端开发能力、逻辑思维以及利用数据结构和算法解决问题的能力。
我决定自己实现 Tic-Tac-Toe 来巩固我的理解。虽然它看起来像是一个简单的游戏,但打造一个强大的解决方案需要仔细考虑几个因素。
我很乐意分享我的代码并解释我的方法。我相信分享知识对于成长至关重要,讨论解决方案可以带来宝贵的见解和改进。
import "./App.css" import TicTacToe from "./components/TicTacToe" const App = () => { return ( <div > <TicTacToe /> </div> ) } export default App
import useTicTacToe from "../hooks/useTicTacToe" const TicTacToe = () => { const {board, handleClick, getStatusMessage, resetGame} = useTicTacToe(); return ( <div className="main"> <div className="heading"> <h1> { getStatusMessage() } </h1> <button onClick={resetGame}>Reset Game</button> </div> <div className="board"> { board.map((player, i) => { return <button key={i} onClick={() => handleClick(i)} disabled = {player !== null}>{player}</button> }) } </div> </div> ) } export default TicTacToe
import { useState } from "react"; const intialGame = () => Array(9).fill(null); const useTicTacToe = () => { const [board, setBoard] = useState(intialGame()) const [isXNext, setIsXNext] = useState(true); const winning_patterns = [ [0,1,2], [3,4,5], [6,7,8], [0,4,8], [2,4,6], [0,3,6], [1,4,7], [2,5,8], ]; const calculateWinner = (currentBoard) => { for(let i = 0 ; i < winning_patterns.length ; i++) { const [a, b, c] = winning_patterns[i]; if(currentBoard[a] && currentBoard[a] === currentBoard[b] && currentBoard[a] === currentBoard[c]) { return currentBoard[a]; } } return null; } const resetGame = () => { setBoard(intialGame()); } const getStatusMessage = () => { const winner = calculateWinner(board); if(winner) return `Player ${winner} Won ?` if(!board.includes(null)) return `It's a Draw` return `Player ${isXNext === true ? "X" : "O"} Turn` } const handleClick = (index) => { const winner = calculateWinner(board); if(winner) return null; const newBoard = [...board]; newBoard[index] = isXNext ? "X" : "O"; setBoard(newBoard); setIsXNext(!isXNext); } return {board, calculateWinner, resetGame, getStatusMessage, handleClick} } export default useTicTacToe;
.board { width: 300px; height: 300px; display: grid; grid-template-columns: repeat(3, 1fr); justify-content: center; } .main { display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 10px; } .heading { display: flex; justify-content: center; align-items: center; gap: 10px; } .board button { font-size: 35px; }
以上是Tic Tac Toe 很简单,但在前端回合中被问得最多!为什么 ?的详细内容。更多信息请关注PHP中文网其他相关文章!