찾다
웹 프론트엔드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 애플리케이션 설정

시작하려면 SuperViz를 통합할 새 React 프로젝트를 설정해야 합니다.

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. 앱 구성 요소 구현

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

설명:

  • 가져오기: 상태 관리, SuperViz 초기화, 체스판 렌더링 및 고유 식별자 생성을 위해 React, SuperViz SDK, React-chessboard, chess.js 및 UUID에서 필요한 구성 요소를 가져옵니다.

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. Testez l'application

  • Mouvements d'échecs en temps réel : Ouvrez l'application dans plusieurs fenêtres ou onglets du navigateur pour simuler plusieurs participants et vérifiez que les mouvements effectués par un joueur sont reflétés en temps réel pour les autres.
  • Interaction collaborative : Testez la réactivité de l'application en effectuant des mouvements et en observant comment l'état du jeu se met à jour pour tous les participants.

Résumé

Dans ce tutoriel, nous avons construit un jeu d'échecs multijoueur en utilisant SuperViz pour la synchronisation en temps réel. Nous avons configuré une application React pour gérer les mouvements d'échecs, permettant à plusieurs joueurs de collaborer de manière transparente sur un échiquier partagé. Cette configuration peut être étendue et personnalisée pour s'adapter à divers scénarios où une interaction de jeu est requise.

N'hésitez pas à explorer le code complet et d'autres exemples dans le référentiel GitHub pour plus de détails.

위 내용은 React를 사용하여 멀티플레이어 체스 게임을 구축하는 방법 알아보기의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Python vs. JavaScript : 개발자를위한 비교 분석Python vs. JavaScript : 개발자를위한 비교 분석May 09, 2025 am 12:22 AM

Python과 JavaScript의 주요 차이점은 유형 시스템 및 응용 프로그램 시나리오입니다. 1. Python은 과학 컴퓨팅 및 데이터 분석에 적합한 동적 유형을 사용합니다. 2. JavaScript는 약한 유형을 채택하며 프론트 엔드 및 풀 스택 개발에 널리 사용됩니다. 두 사람은 비동기 프로그래밍 및 성능 최적화에서 고유 한 장점을 가지고 있으며 선택할 때 프로젝트 요구 사항에 따라 결정해야합니다.

Python vs. JavaScript : 작업에 적합한 도구 선택Python vs. JavaScript : 작업에 적합한 도구 선택May 08, 2025 am 12:10 AM

Python 또는 JavaScript를 선택할지 여부는 프로젝트 유형에 따라 다릅니다. 1) 데이터 과학 및 자동화 작업을 위해 Python을 선택하십시오. 2) 프론트 엔드 및 풀 스택 개발을 위해 JavaScript를 선택하십시오. Python은 데이터 처리 및 자동화 분야에서 강력한 라이브러리에 선호되는 반면 JavaScript는 웹 상호 작용 및 전체 스택 개발의 장점에 없어서는 안될 필수입니다.

파이썬 및 자바 스크립트 : 각각의 강점을 이해합니다파이썬 및 자바 스크립트 : 각각의 강점을 이해합니다May 06, 2025 am 12:15 AM

파이썬과 자바 스크립트는 각각 고유 한 장점이 있으며 선택은 프로젝트 요구와 개인 선호도에 따라 다릅니다. 1. Python은 간결한 구문으로 데이터 과학 및 백엔드 개발에 적합하지만 실행 속도가 느립니다. 2. JavaScript는 프론트 엔드 개발의 모든 곳에 있으며 강력한 비동기 프로그래밍 기능을 가지고 있습니다. node.js는 풀 스택 개발에 적합하지만 구문은 복잡하고 오류가 발생할 수 있습니다.

JavaScript의 핵심 : C 또는 C에 구축 되었습니까?JavaScript의 핵심 : C 또는 C에 구축 되었습니까?May 05, 2025 am 12:07 AM

javaScriptisNotBuiltoncorc; it'SangretedLanguageThatrunsonOngineStenWrittenInc .1) javaScriptWasDesignEdasAlightweight, 해석 hanguageforwebbrowsers.2) Endinesevolvedfromsimpleplemporectreterstoccilpilers, 전기적으로 개선된다.

JavaScript 응용 프로그램 : 프론트 엔드에서 백엔드까지JavaScript 응용 프로그램 : 프론트 엔드에서 백엔드까지May 04, 2025 am 12:12 AM

JavaScript는 프론트 엔드 및 백엔드 개발에 사용할 수 있습니다. 프론트 엔드는 DOM 작업을 통해 사용자 경험을 향상시키고 백엔드는 Node.js를 통해 서버 작업을 처리합니다. 1. 프론트 엔드 예 : 웹 페이지 텍스트의 내용을 변경하십시오. 2. 백엔드 예제 : node.js 서버를 만듭니다.

Python vs. JavaScript : 어떤 언어를 배워야합니까?Python vs. JavaScript : 어떤 언어를 배워야합니까?May 03, 2025 am 12:10 AM

Python 또는 JavaScript는 경력 개발, 학습 곡선 및 생태계를 기반으로해야합니다. 1) 경력 개발 : Python은 데이터 과학 및 백엔드 개발에 적합한 반면 JavaScript는 프론트 엔드 및 풀 스택 개발에 적합합니다. 2) 학습 곡선 : Python 구문은 간결하며 초보자에게 적합합니다. JavaScript Syntax는 유연합니다. 3) 생태계 : Python에는 풍부한 과학 컴퓨팅 라이브러리가 있으며 JavaScript는 강력한 프론트 엔드 프레임 워크를 가지고 있습니다.

JavaScript 프레임 워크 : 현대적인 웹 개발 파워JavaScript 프레임 워크 : 현대적인 웹 개발 파워May 02, 2025 am 12:04 AM

JavaScript 프레임 워크의 힘은 개발 단순화, 사용자 경험 및 응용 프로그램 성능을 향상시키는 데 있습니다. 프레임 워크를 선택할 때 : 1. 프로젝트 규모와 복잡성, 2. 팀 경험, 3. 생태계 및 커뮤니티 지원.

JavaScript, C 및 브라우저의 관계JavaScript, C 및 브라우저의 관계May 01, 2025 am 12:06 AM

서론 나는 당신이 이상하다는 것을 알고 있습니다. JavaScript, C 및 Browser는 정확히 무엇을해야합니까? 그들은 관련이없는 것처럼 보이지만 실제로는 현대 웹 개발에서 매우 중요한 역할을합니다. 오늘 우리는이 세 가지 사이의 밀접한 관계에 대해 논의 할 것입니다. 이 기사를 통해 브라우저에서 JavaScript가 어떻게 실행되는지, 브라우저 엔진의 C 역할 및 웹 페이지의 렌더링 및 상호 작용을 유도하기 위해 함께 작동하는 방법을 알게됩니다. 우리는 모두 JavaScript와 브라우저의 관계를 알고 있습니다. JavaScript는 프론트 엔드 개발의 핵심 언어입니다. 브라우저에서 직접 실행되므로 웹 페이지를 생생하고 흥미롭게 만듭니다. 왜 Javascr

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse용 SAP NetWeaver 서버 어댑터

Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

SublimeText3 Linux 새 버전

SublimeText3 Linux 새 버전

SublimeText3 Linux 최신 버전

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구