」工欲善其事,必先利其器。「—孔子《論語.錄靈公》
首頁 > 程式設計 > 了解如何使用 React 建立多人國際象棋遊戲

了解如何使用 React 建立多人國際象棋遊戲

發佈於2024-11-06
瀏覽:439

Learn how to build a multiplayer chess game with React

Hello and welcome! ??

Today I bring a tutorial to guide you through building a multiplayer chess game using SuperViz. Multiplayer games require real-time synchronization and interaction between players, making them ideal applications for SuperViz's capabilities.

This tutorial will show you how to create a chess game where two players can play against each other in real-time, seeing each other's moves as they happen.

We'll demonstrate how to set up a chessboard using the react-chessboard library, manage the game state with chess.js, and synchronize player moves with SuperViz. This setup allows multiple participants to join a chess game, make moves, and experience a seamless and interactive chess game environment. Let's get started!


Prerequisite

To follow this tutorial, you will need a SuperViz account and a developer token. If you already have an account and a developer token, you can move on to the next step.

Create an Account

To create an account, go to SuperViz Registration and create an account using either Google or an email/password. It's important to note that when using an email/password, you will receive a confirmation link that you'll need to click to verify your account.

Retrieving a Developer Token

To use the SDK, you’ll need to provide a developer token, as this token is essential for associating SDK requests with your account. You can retrieve both development and production SuperViz tokens from the dashboard. Copy and save the developer token, as you will need it in the next steps of this tutorial.


Step 1: Set Up Your React Application

To begin, you'll need to set up a new React project where we will integrate SuperViz.

1. Create a New React Project

First, create a new React application using Create React App with TypeScript.

npm create vite@latest chess-game -- --template react-ts
cd chess-game

2. Install Required Libraries

Next, install the necessary libraries for our project:

npm install @superviz/sdk react-chessboard chess.js uuid
  • @superviz/sdk: SDK for integrating real-time collaboration features, including synchronization.
  • react-chessboard: A library for rendering a chessboard in React applications.
  • chess.js: A library for managing chess game logic and rules.
  • uuid: A library for generating unique identifiers, useful for creating unique participant IDs.

3. Configure tailwind

In this tutorial, we'll use the Tailwind css framework. First, install the tailwind package.

npm install -D tailwindcss postcss autoprefixer
npx tailwindcss init -p

We then need to configure the template path. Open tailwind.config.js in the root of the project and insert the following code.

/** @type  {import('tailwindcss').Config} */
export  default  {
content:  [
"./index.html",
"./src/**/*.{js,ts,jsx,tsx}",
],
theme:  {
extend:  {},
},
plugins:  [],

}

Then we need to add the tailwind directives to the global CSS file. (src/index.css)

@tailwind base;
@tailwind components;
@tailwind utilities;

4. Set Up Environment Variables

Create a .env file in your project root and add your SuperViz developer key. This key will be used to authenticate your application with SuperViz services.

VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_DEVELOPER_KEY


Step 2: Implement the Main Application

In this step, we'll implement the main application logic to initialize SuperViz and handle real-time chess moves.

1. Implement the App Component

Open src/App.tsx and set up the main application component using SuperViz to manage the collaborative environment.

import  { v4 as generateId }  from  'uuid';
import  { useCallback, useEffect, useRef, useState }  from  "react";
import SuperVizRoom,  { Realtime, RealtimeComponentEvent, RealtimeMessage, WhoIsOnline }  from  '@superviz/sdk';
import  { Chessboard }  from  "react-chessboard";
import  { Chess, Square }  from  'chess.js';

Explanation:

  • Imports: Import necessary components from React, SuperViz SDK, react-chessboard, chess.js, and UUID for managing state, initializing SuperViz, rendering the chessboard, and generating unique identifiers.

2. Define Constants

Define constants for the API key, room ID, and player ID.

const apiKey =  import.meta.env.VITE_SUPERVIZ_API_KEY  as  string;
const  ROOM_ID  =  'chess-game';
const  PLAYER_ID  =  generateId();

Explanation:

  • apiKey: Retrieves the SuperViz API key from environment variables.
  • ROOM_ID: Defines the room ID for the SuperViz session.
  • PLAYER_ID: Generates a unique player ID using the uuid library.

3. Define Chess Message Type

Create a type for handling chess move messages.

type  ChessMessageUpdate  = RealtimeMessage &  {
 data:  {
     sourceSquare: Square;
     targetSquare: Square;
  };
};

Explanation:

  • ChessMessageUpdate: Extends the RealtimeMessage to include the source and target squares for a chess move.

4. Create the App Component

Set up the main App component and initialize state variables.

export  default  function  App()  {
    const  [initialized, setInitialized]  =  useState(false);
    const  [gameState, setGameState]  =  useState(new  Chess());
    const  [gameFen, setGameFen]  =  useState(gameState.fen());

    const channel =  useRef(null);

Explanation:

  • initialized: A state variable to track whether the SuperViz environment has been set up.
  • gameState: A state variable to manage the chess game state using the chess.js library.
  • gameFen: A state variable to store the FEN (Forsyth-Edwards Notation) string representing the current game position.
  • channel: A ref to store the real-time communication channel.

5. Initialize SuperViz and Real-Time Components

Create an initialize function to set up the SuperViz environment and configure real-time synchronization.

const initialize = useCallback(async () => {
    if (initialized) return; 
    const superviz = await SuperVizRoom(apiKey, { 
    roomId: ROOM_ID, 
    participant: { 
        id: PLAYER_ID, 
        name: 'player-name', 
    }, 
    group: { 
        id: 'chess-game', 
        name: 'chess-game', 
    } 
}); 

const realtime = new Realtime(); 
const whoIsOnline = new WhoIsOnline(); 

superviz.addComponent(realtime); 
superviz.addComponent(whoIsOnline); 

setInitialized(true); 

realtime.subscribe(RealtimeComponentEvent.REALTIME_STATE_CHANGED, () => { 
    channel.current = realtime.connect('move-topic'); 
    channel.current.subscribe('new-move', handleRealtimeMessage); 
    }); 
}, [handleRealtimeMessage, initialized]);

Explanation:

  • initialize: An asynchronous function that initializes the SuperViz room and checks if it's already initialized to prevent duplicate setups.
  • SuperVizRoom: Configures the room, participant, and group details for the session.
  • Realtime Subscription: Connects to the move-topic channel and listens for new moves, updating the local state accordingly.

6. Handle Chess Moves

Create a function to handle chess moves and update the game state.

const makeMove = useCallback((sourceSquare: Square, targetSquare: Square) => { 
    try { 
        const gameCopy = gameState; 
        gameCopy.move({ from: sourceSquare, to: targetSquare, promotion: 'q' }); 

        setGameState(gameCopy); 
        setGameFen(gameCopy.fen()); 

        return true; 
    } catch (error) { 
        console.log('Invalid Move', error); 
        return false; 
    }
}, [gameState]);

Explanation:

  • makeMove: Attempts to make a move on the chessboard, updating the game state and FEN string if the move is valid.
  • Promotion: Automatically promotes a pawn to a queen if it reaches the last rank.

7. Handle Piece Drop

Create a function to handle piece drop events on the chessboard.

const onPieceDrop = (sourceSquare: Square, targetSquare: Square) => { 
    const result = makeMove(sourceSquare, targetSquare); 

    if (result) { 
        channel.current.publish('new-move', { 
            sourceSquare, 
            targetSquare, 
        });
    } 
     return result; 
};

Explanation:

  • onPieceDrop: Handles the logic for when a piece is dropped on a new square, making the move and publishing it to the SuperViz channel if valid.

8. Handle Real-Time Messages

Create a function to handle incoming real-time messages for moves made by other players.

const handleRealtimeMessage =  useCallback((message: ChessMessageUpdate)  =>  {
  if  (message.participantId ===  PLAYER_ID)  return;

  const  { sourceSquare, targetSquare }  = message.data;
  makeMove(sourceSquare, targetSquare);
},  [makeMove]);

Explanation:

  • handleRealtimeMessage: Listens for incoming move messages and updates the game state if the move was made by another participant.

9. Use Effect Hook for Initialization

Use the useEffect hook to trigger the initialize function on component mount.

useEffect(()  =>  {
  initialize();
},  [initialize]);

Explanation:

  • useEffect: Calls the initialize function once when the component mounts, setting up the SuperViz environment and real-time synchronization.

10. Render the Application

Return the JSX structure for rendering the application, including the chessboard and collaboration features.

return ( 
    

SuperViz Chess Game

Turn: {gameState.turn() === 'b' ? 'Black' : 'White'}

);

Explanation:

  • Header: Displays the title of the application.
  • Chessboard: Renders the chessboard using the Chessboard component, with gameFen as the position and onPieceDrop as the event handler for piece drops.
  • Turn Indicator: Displays the current player's turn (Black or White).

Step 3: Understanding the Project Structure

Here's a quick overview of how the project structure supports a multiplayer chess game:

  1. App.tsx
    • Initializes the SuperViz environment.
    • Sets up participant information and room details.
    • Handles real-time synchronization for chess moves.
  2. Chessboard
    • Displays the chessboard and manages piece movements.
    • Integrates real-time communication to synchronize moves between players.
  3. Chess Logic
    • Uses chess.js to manage game rules and validate moves.
    • Updates the game state and FEN string to reflect the current board position.

Step 4: Running the Application

1. Start the React Application

To run your application, use the following command in your project directory:

npm run dev

This command will start the development server and open your application in the default web browser. You can interact with the chessboard and see moves in real-time as other participants join the session.

2. Test the Application

  • Real-Time Chess Moves: Open the application in multiple browser windows or tabs to simulate multiple participants and verify that moves made by one player are reflected in real-time for others.
  • Collaborative Interaction: Test the responsiveness of the application by making moves and observing how the game state updates for all participants.

Summary

In this tutorial, we built a multiplayer chess game using SuperViz for real-time synchronization. We configured a React application to handle chess moves, enabling multiple players to collaborate seamlessly on a shared chessboard. This setup can be extended and customized to fit various scenarios where game interaction is required.

Feel free to explore the full code and further examples in the GitHub repository for more details.

版本聲明 本文轉載於:https://dev.to/superviz/learn-how-to-build-a-multiplayer-chess-game-with-react-2pln?1如有侵犯,請聯絡[email protected]刪除
最新教學 更多>
  • VLONE Clothing:重新定義都市時尚的街頭服飾品牌
    VLONE Clothing:重新定義都市時尚的街頭服飾品牌
    VLONE 是少数几个在快速变化的市场中取得超越街头服饰行业所能想象的成就的品牌之一。 VLONE 由 A$AP Mob 集体的电影制片人之一 A$AP Bari 创立,现已发展成为一个小众项目,有时甚至成为都市时尚界的国际知名品牌。 VLONE 凭借大胆的图案、深厚的文化联系和限量版发售,在时尚界...
    程式設計 發佈於2024-11-07
  • 如何使用PDO查詢單行中的單列?
    如何使用PDO查詢單行中的單列?
    使用 PDO 查詢單行中的單列處理針對單行中特定列的 SQL 查詢時,通常需要檢索直接取值,無需循環。要使用 PDO 完成此操作,fetchColumn() 方法就派上用場了。 fetchColumn() 的語法為:$col_value = $stmt->fetchColumn([column...
    程式設計 發佈於2024-11-07
  • 我如何建立 PeerSplit:一個免費的點對點費用分攤應用程式 — 從構思到發布僅需數週時間
    我如何建立 PeerSplit:一個免費的點對點費用分攤應用程式 — 從構思到發布僅需數週時間
    我构建了 PeerSplit——一个免费的、点对点的 Splitwise 替代品——从想法到发布仅用了两周时间! PeerSplit 是一款本地优先的应用程序,用于分配团体费用。它可以离线工作,100% 免费且私密,不需要注册或任何个人数据。 以下是我如何构建它以及我在此过程中学到的一切。 ...
    程式設計 發佈於2024-11-07
  • 如何在 PHP 中解析子網域的根網域?
    如何在 PHP 中解析子網域的根網域?
    在 PHP 中從子域解析網域名稱在 PHP 中,從子域中提取根網域是一項常見任務。當您需要識別與子網域關聯的主網站時,這非常有用。為了實現這一目標,讓我們探索一個解決方案。 提供的程式碼片段利用 parse_url 函數將 URL 分解為其元件,包括網域名稱。隨後,它使用正規表示式來隔離根域,而忽略...
    程式設計 發佈於2024-11-07
  • 使用 Socket.io 建立即時應用程式
    使用 Socket.io 建立即時應用程式
    介紹 Socket.io 是一個 JavaScript 函式庫,可讓 Web 用戶端和伺服器之間進行即時通訊。它支援創建互動式動態應用程序,例如聊天室、多人遊戲和直播。憑藉其易於使用的 API 和跨平台相容性,Socket.io 已成為建立即時應用程式的熱門選擇。在本文中,我們將探...
    程式設計 發佈於2024-11-07
  • 重寫 `hashCode()` 和 `equals()` 如何影響 HashMap 效能?
    重寫 `hashCode()` 和 `equals()` 如何影響 HashMap 效能?
    了解equals 和hashCode 在HashMap 中的工作原理Java 中的HashMap 使用hashCode() 和equals() 方法的組合來有效地儲存和檢索鍵值對。當新增新的鍵值對時,首先計算鍵的hashCode()方法,以確定該條目將放置在哪個雜湊桶中。然後使用 equals() ...
    程式設計 發佈於2024-11-07
  • 使用 Google Apps 腳本和 Leaflet.js 建立互動式 XY 圖像圖
    使用 Google Apps 腳本和 Leaflet.js 建立互動式 XY 圖像圖
    Google Maps has a ton of features for plotting points on a map, but what if you want to plot points on an image? These XY Image Plot maps are commonly...
    程式設計 發佈於2024-11-07
  • 理解 React 中的狀態變數:原因和方法
    理解 React 中的狀態變數:原因和方法
    在深入研究狀態變數之前,讓我們先來分析一下 React 元件的工作原理吧! 什麼是 React 元件? 在 React 中,元件是一段可重複使用的程式碼,代表使用者介面 (UI) 的一部分。它可以像 HTML 按鈕一樣簡單,也可以像完整的頁面一樣複雜。 React...
    程式設計 發佈於2024-11-07
  • Miva 的日子:第 4 天
    Miva 的日子:第 4 天
    這是 100 天 Miva 編碼挑戰的第四天。我跳過了第三天的報告,因為我被困在我的網頁設計專案中,需要改變節奏。這就是為什麼我今天決定深入研究 JavaScript。 JavaScript JavaScript 就像是系統和網站的行為元件。它為網站增加了互動性和回應能力,使其成為網頁設計和開發...
    程式設計 發佈於2024-11-07
  • TailGrids React:+ Tailwind CSS React UI 元件
    TailGrids React:+ Tailwind CSS React UI 元件
    我們很高興推出 TailGrids React,這是您的新首選工具包,可用於輕鬆建立令人驚嘆的響應式 Web 介面。 TailGrids React 提供了超過 600 免費和高級 React UI 元件、區塊、部分和模板的大量集合 - 所有這些都是用 Tailwind CSS 精心製作的。 無論...
    程式設計 發佈於2024-11-07
  • 如何用列表值反轉字典?
    如何用列表值反轉字典?
    使用列表值反轉字典:解決方案在本文中,我們探討了使用列表值反轉字典的挑戰。給定一個索引字典,其中鍵是檔案名,值是這些檔案中出現的單字列表,我們的目標是建立一個倒排字典,其中單字是鍵,值是檔案名稱列表。 提供的反轉函數 invert_dict,不適用於以列表值作為鍵的字典,因為它會失敗並顯示“Type...
    程式設計 發佈於2024-11-07
  • 現代 Web 開發框架:比較流行的框架及其用例
    現代 Web 開發框架:比較流行的框架及其用例
    在快速發展的 Web 開發領域,選擇正確的框架可以顯著影響專案的成功。本文深入研究了一些最受歡迎的 Web 開發框架,比較了它們的優勢和理想用例,以幫助開發人員做出明智的決策。 反應 概述 React 由 Facebook 開發和維護,是一個用於建立使用者介面的 J...
    程式設計 發佈於2024-11-07
  • 如何在 Go 1.18 中安全地使用泛型類型解組 JSON?
    如何在 Go 1.18 中安全地使用泛型類型解組 JSON?
    Unmarshal 中的泛型使用(Go 1.18)在Go 1.18 中使用泛型時,例如創建一個容器來保存各種報告類型,可能會出現類型限制。考慮以下設定:由結構表示的多種報告類型具有通用類型參數的ReportContainer 包裝器可報告,約束為實作可報告介面鑑別器ReportType 在解組過程中...
    程式設計 發佈於2024-11-07
  • 了解 Effect-TS 中的選項排序
    了解 Effect-TS 中的選項排序
    範例 1:使用 O.andThen 忽略第一個值 概念 O.andThen 函數可讓您執行兩個選項的序列,其中結果僅由第二個選項決定。當第一個選項達到目的,但後續操作中不需要它的值時,這很有用。 程式碼 function sequencing_ex...
    程式設計 發佈於2024-11-07
  • React 初學者指南:基礎知識入門
    React 初學者指南:基礎知識入門
    React 已成为现代 Web 开发的基石,以其高效、灵活性和强大的生态系统而闻名。 React 由 Facebook 开发,允许开发人员创建可重用的 UI 组件,从而简化了构建交互式用户界面的过程。 无论您是想构建复杂的单页应用程序还是只是想提高您的 Web 开发技能,掌握 React 都是一笔...
    程式設計 發佈於2024-11-07

免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。

Copyright© 2022 湘ICP备2022001581号-3