Rumah > hujung hadapan web > tutorial js > Membina Permainan Berbilang Pemain Masa Nyata dengan React dan Firebase: Gladiator Taunt Wars

Membina Permainan Berbilang Pemain Masa Nyata dengan React dan Firebase: Gladiator Taunt Wars

Barbara Streisand
Lepaskan: 2024-11-14 11:27:02
asal
191 orang telah melayarinya

Building a Real-Time Multiplayer Game with React and Firebase: Gladiator Taunt Wars

소개

이 심층 가이드에서는 Gladiator Taunt Wars의 자세한 예를 들어 Firebase와 React를 사용하여 실시간 멀티플레이어 게임을 구축하는 방법을 살펴보겠습니다. 이 게임 모드에서 플레이어는 전략적 도발 결투에 참여하며, 차례대로 도발을 선택하고 대응하여 상대방의 체력(HP)을 줄입니다. 이 문서에서는 Firebase 설정, 매치메이킹, 게임 상태 관리, 애니메이션, 실시간 업데이트 및 ELO 기반 리더보드 통합을 포함하여 이러한 게임 구축의 모든 측면을 다룹니다. 마지막에는 반응성이 뛰어나고 매력적인 실시간 멀티플레이어 경험을 구현하는 방법을 확실하게 이해하게 될 것입니다.

Firebase 설정 및 프로젝트 초기화
Firebase 설정
실시간 데이터 처리 및 플레이어 확인을 위해 Firestore 및 인증으로 Firebase를 초기화합니다. 이는 경기 데이터, 플레이어 정보 및 실시간 순위표 업데이트를 저장하고 관리하기 위한 백본을 제공합니다. 일치 데이터에 대한 액세스를 제한하여 인증된 플레이어만 관련 정보를 보고 업데이트할 수 있도록 Firestore 규칙을 설정하세요.

React 프로젝트 구조
매치메이킹 시스템, 게임 보드, 리더보드, 채팅 등 각 게임 요소를 나타내는 재사용 가능한 구성 요소로 React 프로젝트를 구성하세요. 명확하고 유지 관리 가능한 아키텍처를 위해 구성 요소를 계층적으로 구성합니다.

게임의 주요 구성 요소

  1. 메인 메뉴 및 매치메이킹 MainMenu 구성 요소는 플레이어에게 옵션을 제공하여 매치메이킹에 참여하고, 통계를 보고, 순위표에 액세스할 수 있도록 합니다. 매치메이킹 구성요소는 일관성을 위해 Firestore 트랜잭션을 활용하여 플레이어를 실시간으로 페어링합니다.

중매 논리
startSearching 함수는 Firestore의 대기열에 플레이어를 추가하여 매치메이킹 프로세스를 시작합니다. 상대가 발견되면 두 플레이어의 ID를 저장하고 게임 매개변수를 초기화하는 새로운 경기 문서가 생성됩니다.

const startSearching = async () => {
  const user = auth.currentUser;
  if (user && db) {
    try {
      const matchmakingRef = collection(db, 'tauntWars_matchmaking');
      const userDocRef = doc(matchmakingRef, user.uid);
      await runTransaction(db, async (transaction) => {
        const userDoc = await transaction.get(userDocRef);
        if (!userDoc.exists()) {
          transaction.set(userDocRef, { userId: user.uid, status: 'waiting', timestamp: serverTimestamp() });
        } else {
          transaction.update(userDocRef, { status: 'waiting', timestamp: serverTimestamp() });
        }

        const q = query(matchmakingRef, where('status', '==', 'waiting'));
        const waitingPlayers = await getDocs(q);
        if (waitingPlayers.size > 1) {
          // Pairing logic
        }
      });
    } catch (error) {
      setIsSearching(false);
    }
  }
};
Salin selepas log masuk

이 기능은 Firestore 트랜잭션을 사용하여 플레이어가 매치메이킹 시스템을 방해할 수 있는 이중 매치를 방지합니다. Firebase의 serverTimestamp 기능은 여러 시간대에 걸쳐 일관된 타임스탬프를 보장하는 데 유용합니다.

  1. Real-Time Game State on the GameBoard Component Listening to Game State Changes The GameBoard component listens for changes in the tauntWars_matches collection. When a player selects a taunt or responds, the change is immediately reflected in Firestore, triggering a re-render for both players.
useEffect(() => {
  const matchRef = doc(db, 'tauntWars_matches', matchId);
  const unsubscribe = onSnapshot(matchRef, (docSnapshot) => {
    if (docSnapshot.exists()) {
      setMatchData(docSnapshot.data());
      if (docSnapshot.data().currentTurn === 'response') {
        setResponses(getAvailableResponses(docSnapshot.data().selectedTaunt));
      }
    }
  });
  return () => unsubscribe();
}, [matchId]);
Salin selepas log masuk

Handling Game Phases
Players alternate turns, each choosing a taunt or response. The currentTurn attribute indicates which action phase the game is in. Each action is updated in Firestore, triggering real-time synchronization across both clients. For instance, a player selecting a taunt switches currentTurn to “response,” alerting the opponent to choose a response.

  1. Player Actions and Taunt Selection ActionSelection Component This component displays available taunts and handles the selection process. Players select a taunt or response, which is stored in Firestore and triggers the next phase.
const handleTauntSelection = async (taunt) => {
  const otherPlayer = currentPlayer === matchData.player1 ? matchData.player2 : matchData.player1;
  await updateDoc(doc(db, 'tauntWars_matches', matchId), {
    currentTurn: 'response',
    turn: otherPlayer,
    selectedTaunt: taunt.id,
  });
};
Salin selepas log masuk

The Timer component restricts the duration of each turn. This timeout function maintains a steady game flow and penalizes players who fail to act in time, reducing their HP.

const Timer = ({ isPlayerTurn, onTimeUp }) => {
  const [timeLeft, setTimeLeft] = useState(30);
  useEffect(() => {
    if (isPlayerTurn) {
      const interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            clearInterval(interval);
            onTimeUp();
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
      return () => clearInterval(interval);
    }
  }, [isPlayerTurn, onTimeUp]);
};
Salin selepas log masuk
  1. Animations with Konva for Health and Attacks CanvasComponent: Uses react-konva to animate health changes and attacks. The health bars visually represent the damage taken or inflicted based on taunts, enhancing engagement.
const animateAttack = useCallback((attacker, defender) => {
  const targetX = attacker === 'player1' ? player1Pos.x + 50 : player2Pos.x - 50;
  const attackerRef = attacker === 'player1' ? player1Ref : player2Ref;
  attackerRef.current.to({
    x: targetX,
    duration: 0.2,
    onFinish: () => attackerRef.current.to({ x: player1Pos.x, duration: 0.2 })
  });
});
Salin selepas log masuk

By simulating attacks in this way, we visually indicate the power and result of each taunt or response, creating a more immersive experience.

  1. Real-Time Chat with ChatBox The ChatBox component is a real-time chat that displays taunt and response messages. This chat interface gives players feedback and context, creating an interactive experience.
const ChatBox = ({ matchId }) => {
  const [messages, setMessages] = useState([]);
  useEffect(() => {
    const chatRef = collection(db, 'tauntWars_matches', matchId, 'chat');
    const unsubscribe = onSnapshot(chatRef, (snapshot) => {
      setMessages(snapshot.docs.map((doc) => doc.data()));
    });
    return () => unsubscribe();
  }, [matchId]);
};
Salin selepas log masuk

Each message is rendered conditionally based on the user’s ID, differentiating sent and received messages with distinct styling.

  1. Leaderboard with ELO Rankings The EloLeaderboard component sorts players based on their ELO rating. Each match updates player ratings in Firestore, which is fetched and displayed in real-time.
const EloLeaderboard = () => {
  const [players, setPlayers] = useState([]);
  useEffect(() => {
    const q = query(collection(db, 'users'), orderBy('tauntWars.elo', 'desc'), limit(100));
    const unsubscribe = onSnapshot(q, (querySnapshot) => {
      setPlayers(querySnapshot.docs.map((doc, index) => ({
        rank: index + 1,
        username: doc.data().username,
        elo: doc.data().tauntWars.elo,
      })));
    });
    return () => unsubscribe();
  }, []);
};
Salin selepas log masuk

The leaderboard ranks players based on their ELO, providing competitive motivation and a way for players to track their progress.

Technical Challenges and Best Practices
Consistency with Firestore Transactions
Using transactions ensures that simultaneous reads/writes to Firestore maintain data integrity, especially during matchmaking and scoring updates.

Optimizing Real-Time Listeners
Employ listener cleanup using unsubscribe() to prevent memory leaks. Also, limiting queries can help reduce the number of Firestore reads, optimizing costs and performance.

Reka Bentuk Responsif dengan Kanvas
CanvasComponent melaraskan saiznya berdasarkan port pandangan, menjadikan permainan responsif merentas peranti. Penggunaan perpustakaan react-konva membolehkan pemaparan mantap elemen interaktif, memberikan pemain maklum balas visual melalui animasi.

Mengendalikan Kes Edge
Pertimbangkan senario di mana pemain memutuskan sambungan pertengahan permainan. Untuk ini, laksanakan fungsi pembersihan yang memastikan data padanan dikemas kini dan sebarang tika perlawanan yang ditinggalkan ditutup.

Membungkus
Dengan Firebase dan React, anda boleh mencipta pengalaman berbilang pemain pantas yang menyesuaikan diri dengan tindakan pengguna masa nyata. Contoh dalam Gladiator Taunt Wars menunjukkan cara mengintegrasikan kemas kini masa nyata, transaksi selamat dan animasi dinamik untuk menghasilkan permainan yang menarik dan menarik secara visual.

Kesimpulan

Membina Gladiator Taunt Wars untuk Pertempuran Gladiators telah menjadi perjalanan yang memberangsangkan, menggabungkan React, Firebase dan mekanik permainan yang mengasyikkan untuk menangkap keamatan pertempuran arena Rom dalam permainan berasaskan web. Memanfaatkan pangkalan data Firestore masa nyata Firebase, pengesahan selamat dan keupayaan pengehosan yang mantap telah membolehkan kami mencipta pengalaman yang didorong oleh komuniti yang lancar di mana pemain boleh berhadapan dalam pertempuran strategik. Mengintegrasikan Tindakan GitHub untuk penggunaan berterusan juga telah memperkemas pembangunan, membolehkan kami menumpukan perhatian pada mempertingkatkan permainan dan interaksi pengguna.

Sambil kami terus mengembangkan Gladiator Taunt Wars, kami teruja dengan potensi ciri baharu, termasuk lawan yang dipacu AI dan strategi perlawanan yang dipertingkatkan, yang akan memperdalam pengalaman permainan dan menjadikan setiap pertempuran terasa lebih mengasyikkan. Gabungan strategi sejarah dan teknologi moden menyediakan cara yang dinamik untuk pemain terlibat dengan dunia gladiator.

Artikel akan datang dalam siri ini akan menyelami butiran teknikal untuk mencipta aplikasi web interaktif dengan Firebase, termasuk mengoptimumkan aliran data masa nyata, mengurus keadaan permainan yang kompleks dan memanfaatkan AI untuk meningkatkan penglibatan pemain. Kami akan meneroka amalan terbaik untuk merapatkan perkhidmatan bahagian hadapan dan bahagian belakang untuk mewujudkan persekitaran berbilang pemain masa nyata yang responsif.

Sama ada anda sedang membangunkan permainan interaktif anda sendiri atau ingin tahu tentang teknologi di sebalik Gladiators Battle, siri ini menawarkan cerapan berharga tentang membina aplikasi web moden dengan Firebase. Sertai kami sambil kami terus menggabungkan sejarah purba dengan teknologi termaju, membayangkan semula keseronokan pertempuran gladiator untuk dunia digital hari ini.

? Temui Lagi:

검투사 전투 탐험: https://gladiatorsbattle.com에서 로마 세계로 뛰어들어 전략과 전투를 경험하세요
GitHub를 확인하세요: https://github.com/HanGPIErr/Gladiators-Battle-Documentation에서 코드베이스와 기여를 확인하세요.
LinkedIn에서 연결: 내 프로젝트에 대한 업데이트를 보려면 LinkedIn에서 팔로우하세요 https://www.linkedin.com/in/pierre-romain-lopez/
내 X 계정도 있습니다: https://x.com/GladiatorsBT

Atas ialah kandungan terperinci Membina Permainan Berbilang Pemain Masa Nyata dengan React dan Firebase: Gladiator Taunt Wars. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

sumber:dev.to
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Artikel terbaru oleh pengarang
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan