joinRoom method

SwampRoom? joinRoom(
  1. Uint8List roomId,
  2. Channel player
)

Attempts to add a player to a room.

Returns the SwampRoom if successful, or null if the room wasn't found, is full, or the application ID doesn't match.

Implementation

SwampRoom? joinRoom(Uint8List roomId, Channel player) {
  final room = getRoom(roomId);
  if (room == null) {
    _sendJoinFailed(player, JoinFailedReason.roomNotFound);
    return null;
  }
  final application = _application[player];
  if (application != null &&
      room.application != null &&
      encodeRoomCode(room.application!) != encodeRoomCode(application)) {
    _sendJoinFailed(player, JoinFailedReason.applicationMismatch);
    return null;
  }
  if (room.maxPlayers != 0 && room.players.length >= room.maxPlayers) {
    _sendJoinFailed(player, JoinFailedReason.roomFull);
    return null;
  }
  final id = room._findAvailableChannel();
  if (id == kAnyChannel) {
    _sendJoinFailed(player, JoinFailedReason.roomFull);
    return null;
  }
  _joined[player] = room;
  room._addPlayer(player, id);
  _playerCount++;
  sendRoomInfo(player);
  _sendPacketToRoom(
    room,
    RpcNetworkerPacket.named(
      name: SwampEvent.playerJoined,
      data: Uint8List.fromList([id >> 8, id & 0xFF]),
    ),
  );
  return room;
}