찾다
웹 프론트엔드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으로 문의하세요.
JavaScript로 문자열 문자를 교체하십시오JavaScript로 문자열 문자를 교체하십시오Mar 11, 2025 am 12:07 AM

JavaScript 문자열 교체 방법 및 FAQ에 대한 자세한 설명 이 기사는 JavaScript에서 문자열 문자를 대체하는 두 가지 방법 인 내부 JavaScript 코드와 웹 페이지의 내부 HTML을 탐색합니다. JavaScript 코드 내부의 문자열을 교체하십시오 가장 직접적인 방법은 대체 () 메소드를 사용하는 것입니다. str = str.replace ( "find", "replace"); 이 메소드는 첫 번째 일치 만 대체합니다. 모든 경기를 교체하려면 정규 표현식을 사용하고 전역 플래그 g를 추가하십시오. str = str.replace (/fi

자신의 Ajax 웹 응용 프로그램을 구축하십시오자신의 Ajax 웹 응용 프로그램을 구축하십시오Mar 09, 2025 am 12:11 AM

그래서 여기 당신은 Ajax라는이 일에 대해 배울 준비가되어 있습니다. 그러나 정확히 무엇입니까? Ajax라는 용어는 역동적이고 대화식 웹 컨텐츠를 만드는 데 사용되는 느슨한 기술 그룹을 나타냅니다. 원래 Jesse J에 의해 만들어진 Ajax라는 용어

10 JQuery Fun 및 Games 플러그인10 JQuery Fun 및 Games 플러그인Mar 08, 2025 am 12:42 AM

10 재미있는 jQuery 게임 플러그인 웹 사이트를보다 매력적으로 만들고 사용자 끈적함을 향상시킵니다! Flash는 여전히 캐주얼 웹 게임을 개발하기위한 최고의 소프트웨어이지만 JQuery는 놀라운 효과를 만들 수 있으며 Pure Action Flash 게임과 비교할 수는 없지만 경우에 따라 브라우저에서 예기치 않은 재미를 가질 수 있습니다. jQuery tic 발가락 게임 게임 프로그래밍의 "Hello World"에는 이제 jQuery 버전이 있습니다. 소스 코드 jQuery Crazy Word Composition 게임 이것은 반은 반은 게임이며, 단어의 맥락을 알지 못해 이상한 결과를 얻을 수 있습니다. 소스 코드 jQuery 광산 청소 게임

jQuery 시차 자습서 - 애니메이션 헤더 배경jQuery 시차 자습서 - 애니메이션 헤더 배경Mar 08, 2025 am 12:39 AM

이 튜토리얼은 jQuery를 사용하여 매혹적인 시차 배경 효과를 만드는 방법을 보여줍니다. 우리는 멋진 시각적 깊이를 만드는 계층화 된 이미지가있는 헤더 배너를 만들 것입니다. 업데이트 된 플러그인은 jQuery 1.6.4 이상에서 작동합니다. 다운로드

내 자신의 JavaScript 라이브러리를 어떻게 작성하고 게시합니까?내 자신의 JavaScript 라이브러리를 어떻게 작성하고 게시합니까?Mar 18, 2025 pm 03:12 PM

기사는 JavaScript 라이브러리 작성, 게시 및 유지 관리, 계획, 개발, 테스트, 문서 및 홍보 전략에 중점을 둡니다.

브라우저에서 성능을 위해 JavaScript 코드를 최적화하려면 어떻게해야합니까?브라우저에서 성능을 위해 JavaScript 코드를 최적화하려면 어떻게해야합니까?Mar 18, 2025 pm 03:14 PM

이 기사는 브라우저에서 JavaScript 성능을 최적화하기위한 전략에 대해 설명하고 실행 시간을 줄이고 페이지로드 속도에 미치는 영향을 최소화하는 데 중점을 둡니다.

jQuery 및 Ajax를 사용한 자동 새로 고침 DIV 컨텐츠jQuery 및 Ajax를 사용한 자동 새로 고침 DIV 컨텐츠Mar 08, 2025 am 12:58 AM

이 기사에서는 jQuery 및 Ajax를 사용하여 5 초마다 DIV의 컨텐츠를 자동으로 새로 고치는 방법을 보여줍니다. 이 예제는 RSS 피드의 최신 블로그 게시물을 마지막 새로 고침 타임 스탬프와 함께 가져오고 표시합니다. 로딩 이미지는 선택 사항입니다

Matter.js : 소개를 시작합니다Matter.js : 소개를 시작합니다Mar 08, 2025 am 12:53 AM

Matter.js는 JavaScript로 작성된 2D 강성 신체 물리 엔진입니다. 이 라이브러리를 사용하면 브라우저에서 2D 물리학을 쉽게 시뮬레이션 할 수 있습니다. 그것은 단단한 몸체를 생성하고 질량, 면적 또는 밀도와 같은 물리적 특성을 할당하는 능력과 같은 많은 기능을 제공합니다. 중력 마찰과 같은 다양한 유형의 충돌 및 힘을 시뮬레이션 할 수도 있습니다. Matter.js는 모든 주류 브라우저를 지원합니다. 또한, 터치를 감지하고 반응이 좋기 때문에 모바일 장치에 적합합니다. 이러한 모든 기능을 사용하면 엔진 사용 방법을 배울 수있는 시간이 필요합니다. 이는 물리 기반 2D 게임 또는 시뮬레이션을 쉽게 만들 수 있습니다. 이 튜토리얼에서는 설치 및 사용을 포함한이 라이브러리의 기본 사항을 다루고

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 옷 제거제

AI Hentai Generator

AI Hentai Generator

AI Hentai를 무료로 생성하십시오.

뜨거운 도구

맨티스BT

맨티스BT

Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

MinGW - Windows용 미니멀리스트 GNU

MinGW - Windows용 미니멀리스트 GNU

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

SublimeText3 Mac 버전

SublimeText3 Mac 버전

신 수준의 코드 편집 소프트웨어(SublimeText3)

SublimeText3 영어 버전

SublimeText3 영어 버전

권장 사항: Win 버전, 코드 프롬프트 지원!

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경