İçeriğe atla

Başlarken

Node.js hızlı başlangıcı

SDK'yı yükleyin ve Node.js'den ilk herkese açık odanızı barındırın.

Ön koşullar

Kurulum

Bir proje oluşturun ve SDK'yı ekleyin.

npm install ball2d

Host'u yazın

Bu oda kendini herkese açık olarak listeler, her yeni oyuncuyu daha küçük takıma yerleştirir ve sahada iki oyuncu olur olmaz bir maç başlatır.

host.mjs
import { createRoom } from 'ball2d/node';

const apiKey = process.env.BALL2D_API_KEY;
if (!apiKey) throw new Error('Set BALL2D_API_KEY');

const room = await createRoom({
  apiKey,
  roomName: 'Evening football',
  noPlayer: true,
  maxPlayers: 12,
  public: true,
});

room.onError = (message) =>
  console.error('Room error:', message);

room.onPlayerJoin = async (player) => {
  const players = room.getPlayerList();
  const red = players.filter((p) => p.team === 1).length;
  const blue = players.filter((p) => p.team === 2).length;
  await room.setPlayerTeam(
    player.id,
    red <= blue ? 1 : 2,
  );
  await room.sendAnnouncement(
    `Welcome, ${player.name}!`,
    player.id,
  );

  const fielded = room
    .getPlayerList()
    .filter((p) => p.team !== 0).length;
  if (fielded >= 2 && room.getScores() === null)
    await room.startGame();
};

await room.setDefaultStadium('Classic');
await room.setScoreLimit(3);
await room.setTimeLimit(5);

console.log(`Room open: ${room.roomLink}`);

for (const signal of ['SIGINT', 'SIGTERM']) {
  process.once(signal, async () => {
    room.close();
    await room.closed;
    process.exit(0);
  });
}

Çalıştırın

Uçbirim
BALL2D_API_KEY="b2d_…" node host.mjs

Yazdırılan bağlantıyı açın veya ball2d.com üzerindeki oda listesinde Evening football'ı bulun. Odayı kapatmak için Ctrl + C tuşlarına basın.

noPlayer: true, odayı tamamen kod üzerinden çalıştırır. Bunu belirtmezseniz süreciniz oyuncu 0 olarak katılır; bu, sendChat() ile sohbet edebilen Host adlı bir yöneticidir.

Sonraki adımlar