# TapBattleClient.CreateRoom

# 功能描述

创建一个新的多人联机房间,可以设置房间配置(房间名称、最大人数、匹配参数等)和玩家配置(自定义状态和属性)。创建成功后,创建者自动成为房主。

# 方法签名

public static void CreateRoom(CreateRoomOption option)

# 参数说明

# CreateRoomOption

参数名 类型 必填 说明
data CreateRoomConfig 创建房间配置数据
success Action<CreateRoomSuccessResponse> 创建成功回调
fail Action<TapCallbackResult> 创建失败回调
complete Action<TapCallbackResult> 创建完成回调

# CreateRoomConfig

字段名 类型 必填 说明
roomCfg RoomConfig 房间配置
playerCfg PlayerConfig 玩家配置

# RoomConfig

字段名 类型 必填 说明
maxPlayerCount int 房间最大人数(通常设为2)
type string 房间类型(如"新手区"、"高级区")
name string 房间名称
customProperties string 自定义房间属性(JSON字符串,最大2048字节)
matchParams MatchParams 匹配参数

# PlayerConfig

字段名 类型 必填 说明
customStatus int 自定义玩家状态(如0=未准备,1=已准备)
customProperties string 自定义玩家属性(JSON字符串,最大2048字节)

# MatchParams

字段名 类型 必填 说明
level string 玩家等级(string类型)
score string 玩家积分(string类型)

# CreateRoomSuccessResponse

字段名 类型 说明
roomInfo RoomInfo 完整的房间信息
errMsg string 成功时为"createRoom:ok"

# 使用说明

# 适用场景

  • 创建私人房间(朋友对战)
  • 创建特定配置的房间
  • 需要自定义房间名称时

# 注意事项

  • 自动成为房主 - 创建者自动成为房间的房主
  • 房间名称必填 - 与MatchRoom不同,CreateRoom必须提供房间名称
  • 等待其他玩家 - 创建后需要等待其他玩家加入
  • 只有房主能开始帧同步 - 只有房主才能调用StartFrameSync

# 代码示例

# 示例1:创建带自定义属性的房间

using UnityEngine;

public class AdvancedRoomCreator : MonoBehaviour
{
    public void CreateCustomRoom()
    {
        // 定义房间自定义属性
        var roomProperties = new {
            gameMode = "classic",
            mapName = "forest",
            maxPlayers = 2
        };

        // 定义玩家自定义属性
        var playerProperties = new {
            playerName = "玩家A",
            playerLevel = 10,
            avatarId = "avatar_001"
        };

        TapBattleClient.CreateRoom(new CreateRoomOption
        {
            data = new CreateRoomConfig
            {
                roomCfg = new RoomConfig
                {
                    maxPlayerCount = 2,
                    type = "新手区",
                    name = "1v1经典模式",
                    customProperties = JsonUtility.ToJson(roomProperties),
                    matchParams = new MatchParams
                    {
                        level = "5",
                        score = "1000"
                    }
                },
                playerCfg = new PlayerConfig
                {
                    customStatus = 0, // 0=未准备
                    customProperties = JsonUtility.ToJson(playerProperties)
                }
            },
            success = (result) => {
                Debug.Log($"创建房间成功: {result.roomInfo.id}");
                ShowRoomUI(result.roomInfo);
            },
            fail = (result) => {
                Debug.LogError($"创建失败: {result.errMsg}");
            }
        });
    }

    private void ShowRoomUI(RoomInfo roomInfo) { }
}

# 最佳实践

  1. 合理命名 - 给房间起一个有意义的名称,方便识别
  2. 设置匹配参数 - 即使是创建房间,也建议设置matchParams以便后续匹配
  3. 监听玩家加入 - 实现OnPlayerEntered事件,及时响应玩家加入
  4. 房间已满判断 - 检查房间人数,满员后显示开始按钮

# 相关API