如何使用 React Hooks 构建井字棋游戏?

要使用 React Hooks 构建一个井字棋游戏,我们需要包含几个关键的交互组件:代表棋盘的组件、代表棋子的标记,以及最终显示游戏获胜者的提示。

最终输出预览: 在开始编码之前,让我们先来看一下最终的应用程序是什么样子的。

!Screenshot-from-2023-11-06-11-28-45

井字棋游戏的先决条件:

实现思路:

为了在 React JS 中创建井字棋游戏,我们将结合使用 React 函数式组件和 React Hooks(Hooks)来实现交互逻辑和存储棋步。每走一步,组件都会在玩家之间切换,并在棋盘选定的区域标记“X”或“O”。我们还将使用 CSS 对游戏棋盘进行美化,以获得更好的视觉效果。

创建 React 应用程序并安装所需模块的步骤:

步骤 1: 在终端中使用以下命令来初始化 React 项目。

npx create-react-app tic-tac-toe-react

步骤 2: 使用以下命令切换到 tic-tac-toe-react 目录。

cd tic-tac-toe-react

项目结构:

!image

示例: 本示例将演示如何通过实现 React 组件和 CSS,利用 React Hooks 构建一个井字棋游戏。

JavaScript


CODEBLOCK_ac4683ea

JavaScript


// Filename – Board.js

// Importing the CSS for the board

import "./css/board.css";

// Importing the useState hook, useEffect hook and useRef hook

import { useState, useEffect, useRef } from "react";

const Board = ({ reset, setReset, winner, setWinner }) => {

// Creating a turn state, which indicates the current turn

const [turn, setTurn] = useState(0);

// Creating a data state, which contains the

// current picture of the board

const [data, setData] = useState([

"",

"",

"",

"",

"",

"",

"",

"",

"",

]);

// Creating a reference for the board

const boardRef = useRef(null);

// Function to draw on the board

const draw = (event, index) => {

// Draws only if the position is not taken

// and winner is not decided yet

if (data[index – 1] === "" && winner === "") {

// Draws X if it‘s player 1‘s turn else draws O

const current = turn === 0 ? "X" : "O";

// Updating the data state

data[index – 1] = current;

//Drawing on the board

event.target.innerText = current;

// Switching the turn

setTurn(turn === 0 ? 1 : 0);

}

};

// UseEffect hook used to reset the board whenever

// a winner is decided

useEffect(() => {

// Clearing the data state

setData(["", "", "", "", "", "", "", "", ""]);

// Getting all the children(cells) of the board

const cells = boardRef.current.children;

// Clearing out the board

for (let i = 0; i < 9; i++) {

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。如需转载,请注明文章出处豆丁博客和来源网址。https://shluqu.cn/21962.html
点赞
0.00 平均评分 (0% 分数) - 0