搜尋
首頁web前端js教程了解如何使用 React 建立多人國際象棋遊戲

Learn how to build a multiplayer chess game with React

您好,歡迎光臨! ??

今天我帶來了一個教程,指導您使用 SuperViz 建立多人國際象棋遊戲。多人遊戲需要玩家之間的即時同步和互動,這使其成為 SuperViz 功能的理想應用。

本教學將向您展示如何創建一個國際象棋遊戲,讓兩個玩家可以即時對戰,並看到對方的走法。

我們將示範如何使用react-chessboard庫設定棋盤,使用chess.js管理遊戲狀態,以及如何使用SuperViz同步玩家移動。這種設置允許多個參與者加入國際象棋遊戲、走棋並體驗無縫且互動的國際象棋遊戲環境。 讓我們開始吧!


先決條件

要學習本教學課程,您將需要一個 SuperViz 帳戶和一個開發者代幣。如果您已經擁有帳戶和開發者令牌,則可以繼續下一步。

建立一個帳戶

要建立帳戶,請前往 SuperViz 註冊並使用 Google 或電子郵件/密碼建立帳戶。請務必注意,使用電子郵件/密碼時,您將收到一個確認鏈接,您需要點擊該鏈接來驗證您的帳戶。

檢索開發者令牌

要使用 SDK,您需要提供開發者令牌,因為此令牌對於將 SDK 請求與您的帳戶關聯起來至關重要。您可以從儀表板檢索開發和生產 SuperViz 令牌。複製並保存開發者令牌,因為您在本教學的後續步驟中將需要它。


第 1 步:設定您的 React 應用程式

首先,您需要建立一個新的 React 項目,我們將在其中整合 SuperViz。

1. 建立一個新的React項目

首先,使用 Create React App with TypeScript 建立一個新的 React 應用程式。

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

2.安裝所需的庫

接下來,為我們的專案安裝必要的函式庫:

npm install @superviz/sdk react-chessboard chess.js uuid
  • @superviz/sdk: 用於整合即時協作功能(包括同步)的 SDK。
  • react-chessboard: 用於在 React 應用程式中渲染棋盤的程式庫。
  • chess.js: 用於管理西洋棋遊戲邏輯和規則的函式庫。
  • uuid: 用於產生唯一識別碼的函式庫,可用於建立唯一的參與者 ID。

3. 配置順風

在本教程中,我們將使用 Tailwind css 框架。首先,安裝 tailwind 軟體套件。

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

然後我們需要配置模板路徑。在專案根目錄中開啟 tailwind.config.js 並插入以下程式碼。

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

}

然後我們需要將 tailwind 指令新增到全域 CSS 檔案中。 (src/index.css)

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

4. 設定環境變數

在專案根目錄中建立一個 .env 檔案並新增 SuperViz 開發人員金鑰。此金鑰將用於透過 SuperViz 服務驗證您的應用程式。

VITE_SUPERVIZ_API_KEY=YOUR_SUPERVIZ_DEVELOPER_KEY


第 2 步:實現主應用程式

在這一步驟中,我們將實作主要應用程式邏輯來初始化 SuperViz 並處理即時國際象棋走棋。

1. 實作App元件

開啟 src/App.tsx 並使用 SuperViz 設定主應用程式元件來管理協作環境。

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';

說明:

  • 導入: 從 React、SuperViz SDK、react-chessboard、chess.js 和 UUID 導入必要的元件,用於管理狀態、初始化 SuperViz、渲染棋盤並產生唯一識別碼。

2. 定義常數

定義 API 金鑰、房間 ID 和玩家 ID 的常數。

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

說明:

  • apiKey: 從環境變數中檢索 SuperViz API 金鑰。
  • ROOM_ID: 定義 SuperViz 會話的房間 ID。
  • PLAYER_ID: 使用 uuid 函式庫產生唯一的玩家 ID。

3. 定義西洋棋訊息類型

建立一個用於處理國際象棋走棋訊息的類型。

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

說明:

  • ChessMessageUpdate: 擴展 RealtimeMessage 以包含國際象棋移動的來源方格和目標方格。

4. 建立應用程式元件

設定主 App 元件並初始化狀態變數。

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

    const channel =  useRef<any null>(null);

</any></string></chess>

說明:

  • 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 ( 
    <div classname="w-full h-full bg-gray-200 flex items-center justify-center flex-col">
        <header classname="w-full p-5 bg-purple-400 flex items-center justify-between"> 
            <h1 id="SuperViz-Chess-Game">SuperViz Chess Game</h1> 
        </header> 
        <main classname="w-full h-full flex items-center justify-center"> 
            <div classname="w-[500px] h-[500px] shadow-sm border-2 border-gray-300 rounded-md">
                <chessboard position="{gameFen}" onpiecedrop="{onPieceDrop}"></chessboard> 
                <div classname="w-[500px] h-[50px] bg-gray-300 flex items-center justify-center"> 
                    <p classname="text-gray-800 text-2xl font-bold">Turn: {gameState.turn() === 'b' ? 'Black' : 'White'}</p> 
                </div> 
            </div> 
        </main> 
    </div>
);

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. 測試應用程式

  • 即時國際象棋走棋: 在多個瀏覽器視窗或標籤中開啟應用程式以模擬多個參與者,並驗證一名玩家的走棋是否即時反映給其他玩家。
  • 協作互動: 透過移動並觀察所有參與者的遊戲狀態如何更新來測試應用程式的回應能力。

概括

在本教程中,我們使用 SuperViz 建立了一個即時同步的多人國際象棋遊戲。我們配置了一個 React 應用程式來處理國際象棋的走棋,使多個玩家能夠在共享棋盤上無縫協作。此設置可以擴展和定制,以適應需要遊戲互動的各種場景。

請隨意探索 GitHub 儲存庫中的完整程式碼和更多範例以了解更多詳細資訊。

以上是了解如何使用 React 建立多人國際象棋遊戲的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
JavaScript引擎:比較實施JavaScript引擎:比較實施Apr 13, 2025 am 12:05 AM

不同JavaScript引擎在解析和執行JavaScript代碼時,效果會有所不同,因為每個引擎的實現原理和優化策略各有差異。 1.詞法分析:將源碼轉換為詞法單元。 2.語法分析:生成抽象語法樹。 3.優化和編譯:通過JIT編譯器生成機器碼。 4.執行:運行機器碼。 V8引擎通過即時編譯和隱藏類優化,SpiderMonkey使用類型推斷系統,導致在相同代碼上的性能表現不同。

超越瀏覽器:現實世界中的JavaScript超越瀏覽器:現實世界中的JavaScriptApr 12, 2025 am 12:06 AM

JavaScript在現實世界中的應用包括服務器端編程、移動應用開發和物聯網控制:1.通過Node.js實現服務器端編程,適用於高並發請求處理。 2.通過ReactNative進行移動應用開發,支持跨平台部署。 3.通過Johnny-Five庫用於物聯網設備控制,適用於硬件交互。

使用Next.js(後端集成)構建多租戶SaaS應用程序使用Next.js(後端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:23 AM

我使用您的日常技術工具構建了功能性的多租戶SaaS應用程序(一個Edtech應用程序),您可以做同樣的事情。 首先,什麼是多租戶SaaS應用程序? 多租戶SaaS應用程序可讓您從唱歌中為多個客戶提供服務

如何使用Next.js(前端集成)構建多租戶SaaS應用程序如何使用Next.js(前端集成)構建多租戶SaaS應用程序Apr 11, 2025 am 08:22 AM

本文展示了與許可證確保的後端的前端集成,並使用Next.js構建功能性Edtech SaaS應用程序。 前端獲取用戶權限以控制UI的可見性並確保API要求遵守角色庫

JavaScript:探索網絡語言的多功能性JavaScript:探索網絡語言的多功能性Apr 11, 2025 am 12:01 AM

JavaScript是現代Web開發的核心語言,因其多樣性和靈活性而廣泛應用。 1)前端開發:通過DOM操作和現代框架(如React、Vue.js、Angular)構建動態網頁和單頁面應用。 2)服務器端開發:Node.js利用非阻塞I/O模型處理高並發和實時應用。 3)移動和桌面應用開發:通過ReactNative和Electron實現跨平台開發,提高開發效率。

JavaScript的演變:當前的趨勢和未來前景JavaScript的演變:當前的趨勢和未來前景Apr 10, 2025 am 09:33 AM

JavaScript的最新趨勢包括TypeScript的崛起、現代框架和庫的流行以及WebAssembly的應用。未來前景涵蓋更強大的類型系統、服務器端JavaScript的發展、人工智能和機器學習的擴展以及物聯網和邊緣計算的潛力。

神秘的JavaScript:它的作用以及為什麼重要神秘的JavaScript:它的作用以及為什麼重要Apr 09, 2025 am 12:07 AM

JavaScript是現代Web開發的基石,它的主要功能包括事件驅動編程、動態內容生成和異步編程。 1)事件驅動編程允許網頁根據用戶操作動態變化。 2)動態內容生成使得頁面內容可以根據條件調整。 3)異步編程確保用戶界面不被阻塞。 JavaScript廣泛應用於網頁交互、單頁面應用和服務器端開發,極大地提升了用戶體驗和跨平台開發的靈活性。

Python還是JavaScript更好?Python還是JavaScript更好?Apr 06, 2025 am 12:14 AM

Python更适合数据科学和机器学习,JavaScript更适合前端和全栈开发。1.Python以简洁语法和丰富库生态著称,适用于数据分析和Web开发。2.JavaScript是前端开发核心,Node.js支持服务器端编程,适用于全栈开发。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱門文章

R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
3 週前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.如果您聽不到任何人,如何修復音頻
3 週前By尊渡假赌尊渡假赌尊渡假赌
WWE 2K25:如何解鎖Myrise中的所有內容
4 週前By尊渡假赌尊渡假赌尊渡假赌

熱工具

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。