diff --git a/common/constant/match_game_type.go b/common/constant/match_game_type.go new file mode 100644 index 00000000..3f90ac6a --- /dev/null +++ b/common/constant/match_game_type.go @@ -0,0 +1,6 @@ +package constant + +const ( + MATCH_GAME_TYPE_NONE = iota + MATCH_GAME_TYPE_PUBG // pubg游戏 +) diff --git a/common/mq/net_msg.go b/common/mq/net_msg.go index 228ca234..08be94b0 100644 --- a/common/mq/net_msg.go +++ b/common/mq/net_msg.go @@ -61,6 +61,16 @@ const ( ServerStopNotify // 停服通知 ServerDispatchCancelNotify // 服务器取消调度通知 ServerGmCmdNotify // 服务器GM指令执行通知 + ServerGetMatchGameListReq // 服务器匹配服游戏列表请求 + ServerGetMatchGameListRsp // 服务器匹配服游戏列表响应 + ServerGetMatchRoomAiUidReq // 服务器匹配服房间ai的uid请求 + ServerGetMatchRoomAiUidRsp // 服务器匹配服房间ai的uid响应 + ServerMatchCreateAiReq // 服务器匹配服创建ai请求 + ServerMatchCreateAiRsp // 服务器匹配服创建ai响应 + ServerMatchPlayerJoinGameNotify // 服务器匹配服玩家加入游戏通知 + ServerMatchPlayerExitGameNotify // 服务器匹配服玩家离开游戏通知 + ServerMatchGameStartNotify // 服务器匹配服游戏开始通知 + ServerMatchGameStopNotify // 服务器匹配服游戏结束通知 ) type ServerMsg struct { @@ -76,6 +86,12 @@ type ServerMsg struct { AppVersion string GmCmdFuncName string GmCmdParamList []string + MatchGameList []*MatchGameInfo + MatchGameId uint32 + MatchRoomId uint32 + MatchAiUid uint32 + MatchAiInfo *AiInfo + MatchGameType uint8 } type OriginInfo struct { @@ -127,3 +143,18 @@ type ForwardDispatchInfo struct { GatePort uint32 DispatchKey []byte } + +// MatchGameInfo 匹配游戏信息 +type MatchGameInfo struct { + GameId uint32 // 游戏id + PlayerCount uint32 // 玩家数量 + AiInfo *AiInfo // Ai信息 +} + +// AiInfo ai信息 +type AiInfo struct { + Name string // 游戏名 + Sign string // 描述签名 + HeadImage uint32 // 头像id + NameCard uint32 // 名片id +} diff --git a/gs/game/audio_video.go b/gs/game/audio_video.go index 0c76d8b7..efb16bca 100644 --- a/gs/game/audio_video.go +++ b/gs/game/audio_video.go @@ -295,7 +295,7 @@ func UpdateFrame(fileData []byte, basePos *model.Vector, rgb bool) { if err != nil { return } - world := WORLD_MANAGER.GetAiWorld() + world := WORLD_MANAGER.GetWorldById(GAME.ai.WorldId) scene := world.GetSceneById(3) for _, v := range SCREEN_ENTITY_ID_LIST { scene.DestroyEntity(v) diff --git a/gs/game/game.go b/gs/game/game.go index 5836c33b..659292a7 100644 --- a/gs/game/game.go +++ b/gs/game/game.go @@ -37,6 +37,7 @@ var TICK_MANAGER *TickManager = nil var COMMAND_MANAGER *CommandManager = nil var GCG_MANAGER *GCGManager = nil var PLUGIN_MANAGER *PluginManager = nil +var AI_MANAGER *AiManager = nil var MESSAGE_QUEUE *mq.MessageQueue var ONLINE_PLAYER_NUM int32 = 0 // 当前在线玩家数 @@ -73,13 +74,12 @@ func NewGameCore(db *dao.Dao, messageQueue *mq.MessageQueue, gsId uint32, gsAppi COMMAND_MANAGER = NewCommandManager() GCG_MANAGER = NewGCGManager() PLUGIN_MANAGER = NewPluginManager() + AI_MANAGER = NewAiManager() RegLuaScriptLibFunc() - // 创建本服的Ai世界 - uid := AiBaseUid + gsId + // 创建本服的Ai name := AiName sign := AiSign + " GS:" + strconv.Itoa(int(gsId)) - r.ai = r.CreateRobot(uid, name, sign) - WORLD_MANAGER.InitAiWorld(r.ai) + r.ai = AI_MANAGER.CreateAi(name, sign, 10000007, 210001, "") COMMAND_MANAGER.SetSystem(r.ai) // 初始化插件 最后再调用以免插件需要访问其他模块导致出错 PLUGIN_MANAGER.InitPlugin() @@ -102,35 +102,6 @@ func (g *Game) GetAi() *model.Player { return g.ai } -func (g *Game) CreateRobot(uid uint32, name string, sign string) *model.Player { - g.OnLogin(uid, 0, "", nil, new(proto.PlayerLoginReq), true) - robot := USER_MANAGER.GetOnlineUser(uid) - robot.DbState = model.DbNormal - g.SetPlayerBornDataReq(robot, &proto.SetPlayerBornDataReq{AvatarId: 10000007, NickName: name}) - robot.Signature = sign - world := WORLD_MANAGER.GetWorldById(robot.WorldId) - g.EnterSceneReadyReq(robot, &proto.EnterSceneReadyReq{ - EnterSceneToken: world.GetEnterSceneToken(), - }) - g.SceneInitFinishReq(robot, &proto.SceneInitFinishReq{ - EnterSceneToken: world.GetEnterSceneToken(), - }) - g.EnterSceneDoneReq(robot, &proto.EnterSceneDoneReq{ - EnterSceneToken: world.GetEnterSceneToken(), - }) - g.PostEnterSceneReq(robot, &proto.PostEnterSceneReq{ - EnterSceneToken: world.GetEnterSceneToken(), - }) - g.EntityForceSyncReq(robot, &proto.EntityForceSyncReq{ - MotionInfo: &proto.MotionInfo{ - Pos: &proto.Vector{X: 500.0, Y: 900.0, Z: -500.0}, - Rot: new(proto.Vector), - }, - EntityId: world.GetPlayerWorldAvatarEntityId(robot, 10000007), - }) - return robot -} - func (g *Game) run() { go g.gameMainLoopD() } diff --git a/gs/game/game_ai_manager.go b/gs/game/game_ai_manager.go new file mode 100644 index 00000000..7135cd4a --- /dev/null +++ b/gs/game/game_ai_manager.go @@ -0,0 +1,138 @@ +package game + +import ( + "hk4e/common/mq" + "hk4e/gs/model" + "hk4e/pkg/logger" + "hk4e/protocol/proto" +) + +// AiManager ai管理器 +type AiManager struct { + aiMap map[uint32]*model.Player // ai集合 + aiUidCounter uint32 // ai的uid计数器 + gameRoomAiUidMap map[uint32]map[uint32]uint32 // 游戏房间ai的uid集合 +} + +func NewAiManager() *AiManager { + r := new(AiManager) + + r.aiMap = make(map[uint32]*model.Player) + r.gameRoomAiUidMap = make(map[uint32]map[uint32]uint32) + + return r +} + +// CreateAi 创建ai机器人 +func (a *AiManager) CreateAi(name string, sign string, headImage uint32, nameCard uint32, multiServerAppId string) *model.Player { + a.aiUidCounter++ + uid := GAME.gsId*AiBaseUid + a.aiUidCounter + GAME.OnLogin(uid, 0, "", nil, new(proto.PlayerLoginReq), true) + ai := USER_MANAGER.GetOnlineUser(uid) + ai.DbState = model.DbNormal + + // 记录ai + a.aiMap[ai.PlayerId] = ai + + GAME.SetPlayerBornDataReq(ai, &proto.SetPlayerBornDataReq{AvatarId: 10000007, NickName: name}) + ai.Signature = sign + ai.HeadImage = headImage + ai.NameCard = nameCard + ai.MultiServerAppId = multiServerAppId + world := WORLD_MANAGER.GetWorldById(ai.WorldId) + GAME.EnterSceneReadyReq(ai, &proto.EnterSceneReadyReq{ + EnterSceneToken: world.GetEnterSceneToken(), + }) + GAME.SceneInitFinishReq(ai, &proto.SceneInitFinishReq{ + EnterSceneToken: world.GetEnterSceneToken(), + }) + GAME.EnterSceneDoneReq(ai, &proto.EnterSceneDoneReq{ + EnterSceneToken: world.GetEnterSceneToken(), + }) + GAME.PostEnterSceneReq(ai, &proto.PostEnterSceneReq{ + EnterSceneToken: world.GetEnterSceneToken(), + }) + GAME.EntityForceSyncReq(ai, &proto.EntityForceSyncReq{ + MotionInfo: &proto.MotionInfo{ + Pos: &proto.Vector{X: 500.0, Y: 900.0, Z: -500.0}, + Rot: new(proto.Vector), + }, + EntityId: world.GetPlayerWorldAvatarEntityId(ai, 10000007), + }) + return ai +} + +// DeleteAi 清除ai机器人 +func (a *AiManager) DeleteAi(uid uint32) { + // 确保uid为ai + _, exist := a.aiMap[uid] + if !exist { + logger.Error("ai not exist, uid: %v", uid) + return + } + // ai离线 + GAME.OnOffline(uid, &ChangeGsInfo{ + IsChangeGs: false, + }) + delete(a.aiMap, uid) +} + +// IsAi uid是否为ai +func (a *AiManager) IsAi(uid uint32) bool { + _, exist := a.aiMap[uid] + return exist +} + +// GetAiUidGameId 获取ai的uid存在的游戏id +func (a *AiManager) GetAiUidGameId(uid uint32) (ok bool, matchGameId uint32, matchRoomId uint32) { + for gameId, roomUidMap := range a.gameRoomAiUidMap { + for roomId, u := range roomUidMap { + if u == uid { + return true, gameId, roomId + } + } + } + return +} + +// ServerMatchCreateAiReq 匹配服创建ai请求 +func (g *Game) ServerMatchCreateAiReq(gameType uint8, gameId uint32, roomId uint32, aiInfo *mq.AiInfo, multiAppId string) { + // 校验ai是否已经注册 + roomUidMap, exist := AI_MANAGER.gameRoomAiUidMap[gameId] + if !exist { + roomUidMap = make(map[uint32]uint32) + AI_MANAGER.gameRoomAiUidMap[gameId] = roomUidMap + } + uid, exist := roomUidMap[roomId] + if exist { + logger.Error("room has been create ai, gameId: %v, roomId: %v, uid: %v", gameId, roomId, uid) + return + } + + ai := AI_MANAGER.CreateAi(aiInfo.Name, aiInfo.Sign, aiInfo.HeadImage, aiInfo.NameCard, multiAppId) + WORLD_MANAGER.InitAiWorld(ai) + + // 记录游戏房间ai的uid + roomUidMap[roomId] = ai.PlayerId + + // 触发事件 + if PLUGIN_MANAGER.TriggerEvent(PluginEventIdMatchCreateAi, &PluginEventMatchCreateAi{ + PluginEvent: NewPluginEvent(), + GameType: gameType, + GameId: gameId, + RoomId: roomId, + Ai: ai, + }) { + return + } + + MESSAGE_QUEUE.SendToMulti(multiAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchCreateAiRsp, + ServerMsg: &mq.ServerMsg{ + MatchGameId: gameId, + MatchRoomId: roomId, + MatchAiUid: ai.PlayerId, + }, + }) +} diff --git a/gs/game/game_command_gm.go b/gs/game/game_command_gm.go index e38faec2..ebd9dbb1 100644 --- a/gs/game/game_command_gm.go +++ b/gs/game/game_command_gm.go @@ -30,6 +30,17 @@ func (g *GMCmd) GMTeleportPlayer(userId, sceneId uint32, posX, posY, posZ float6 logger.Error("player is nil, uid: %v", userId) return } + world := WORLD_MANAGER.GetWorldById(player.WorldId) + if world == nil { + logger.Error("world is nil, worldId: %v, uid: %v", player.WorldId, player.PlayerId) + return + } + + // ai世界禁止用命令传送 + if WORLD_MANAGER.IsAiWorld(world) && player.CmdPerm != uint8(CommandPermGM) { + return + } + GAME.TeleportPlayer( player, proto.EnterReason_ENTER_REASON_GM, @@ -543,10 +554,7 @@ func (g *GMCmd) AvUpdateFrame(fileDataBase64 string, rgb bool, posX, posY, posZ UpdateFrame(fileData, basePos, rgb) } -func (g *GMCmd) CreateRobotInAiWorld(uid uint32, name string, avatarId uint32, posX, posY, posZ float64) { - if uid == 0 { - return - } +func (g *GMCmd) CreateRobotInAiWorld(aiUid uint32, name string, avatarId uint32, posX, posY, posZ float64) { if name == "" { name = random.GetRandomStr(8) } @@ -556,9 +564,14 @@ func (g *GMCmd) CreateRobotInAiWorld(uid uint32, name string, avatarId uint32, p break } } - aiWorld := WORLD_MANAGER.GetAiWorld() - robot := GAME.CreateRobot(uid, name, name) - GAME.AddPlayerAvatar(uid, avatarId) + ai := USER_MANAGER.GetOnlineUser(aiUid) + if ai == nil { + logger.Error("ai is nil, uid: %v", aiUid) + return + } + world := WORLD_MANAGER.GetWorldById(ai.WorldId) + robot := AI_MANAGER.CreateAi(name, name, 10000007, 210001, "") + GAME.AddPlayerAvatar(robot.PlayerId, avatarId) dbAvatar := robot.GetDbAvatar() GAME.SetUpAvatarTeamReq(robot, &proto.SetUpAvatarTeamReq{ TeamId: 1, @@ -569,23 +582,23 @@ func (g *GMCmd) CreateRobotInAiWorld(uid uint32, name string, avatarId uint32, p AvatarId: avatarId, }) GAME.JoinPlayerSceneReq(robot, &proto.JoinPlayerSceneReq{ - TargetUid: aiWorld.GetOwner().PlayerId, + TargetUid: world.GetOwner().PlayerId, }) GAME.EnterSceneReadyReq(robot, &proto.EnterSceneReadyReq{ - EnterSceneToken: aiWorld.GetEnterSceneToken(), + EnterSceneToken: world.GetEnterSceneToken(), }) GAME.SceneInitFinishReq(robot, &proto.SceneInitFinishReq{ - EnterSceneToken: aiWorld.GetEnterSceneToken(), + EnterSceneToken: world.GetEnterSceneToken(), }) GAME.EnterSceneDoneReq(robot, &proto.EnterSceneDoneReq{ - EnterSceneToken: aiWorld.GetEnterSceneToken(), + EnterSceneToken: world.GetEnterSceneToken(), }) GAME.PostEnterSceneReq(robot, &proto.PostEnterSceneReq{ - EnterSceneToken: aiWorld.GetEnterSceneToken(), + EnterSceneToken: world.GetEnterSceneToken(), }) - activeAvatarId := aiWorld.GetPlayerActiveAvatarId(robot) + activeAvatarId := world.GetPlayerActiveAvatarId(robot) entityMoveInfo := &proto.EntityMoveInfo{ - EntityId: aiWorld.GetPlayerWorldAvatarEntityId(robot, activeAvatarId), + EntityId: world.GetPlayerWorldAvatarEntityId(robot, activeAvatarId), MotionInfo: &proto.MotionInfo{ Pos: &proto.Vector{X: float32(posX), Y: float32(posY), Z: float32(posZ)}, Rot: &proto.Vector{X: float32(0.0), Y: float32(0.0), Z: float32(0.0)}, @@ -638,45 +651,37 @@ func (g *GMCmd) SendMsgToPlayer(cmdName string, userId uint32, msgJson string) { GAME.SendMsg(cmdId, userId, 0, msg) } -func (g *GMCmd) StartPubg(v bool) { - iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) - if err != nil { - logger.Error("get plugin pubg error: %v", err) +func (g *GMCmd) SetPhysicsEngineParam(aiUid uint32, pathTracing bool, acc float32, drag float32, pao float32, is float32, ayo float32) { + ai := USER_MANAGER.GetOnlineUser(aiUid) + if ai == nil { + logger.Error("ai is nil, uid: %v", aiUid) return } - pluginPubg := iPlugin.(*PluginPubg) - pluginPubg.StartPubg() -} - -func (g *GMCmd) StopPubg(v bool) { - iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) - if err != nil { - logger.Error("get plugin pubg error: %v", err) - return - } - pluginPubg := iPlugin.(*PluginPubg) - pluginPubg.StopPubg() -} - -func (g *GMCmd) SetPhysicsEngineParam(pathTracing bool, acc float32, drag float32, pao float32, is float32, ayo float32) { - world := WORLD_MANAGER.GetAiWorld() + world := WORLD_MANAGER.GetWorldById(ai.WorldId) engine := world.GetBulletPhysicsEngine() engine.SetPhysicsEngineParam(pathTracing, acc, drag, pao, is, ayo) } -func (g *GMCmd) ShowAvatarCollider(v bool) { - world := WORLD_MANAGER.GetAiWorld() +func (g *GMCmd) ShowAvatarCollider(aiUid uint32) { + ai := USER_MANAGER.GetOnlineUser(aiUid) + if ai == nil { + logger.Error("ai is nil, uid: %v", aiUid) + return + } + world := WORLD_MANAGER.GetWorldById(ai.WorldId) engine := world.GetBulletPhysicsEngine() engine.ShowAvatarCollider() } -func (g *GMCmd) AiWorldAoiDebug(v bool) { - aiWorld := WORLD_MANAGER.GetAiWorld() - if aiWorld == nil { +func (g *GMCmd) AiWorldAoiDebug(aiUid uint32) { + ai := USER_MANAGER.GetOnlineUser(aiUid) + if ai == nil { + logger.Error("ai is nil, uid: %v", aiUid) return } - scene := aiWorld.GetSceneById(aiWorld.GetOwner().SceneId) - aiWorldAoi := aiWorld.GetAiWorldAoi() + world := WORLD_MANAGER.GetWorldById(ai.WorldId) + scene := world.GetSceneById(world.GetOwner().SceneId) + aiWorldAoi := world.GetAiWorldAoi() gridMap := aiWorldAoi.Debug() logger.Debug("total grid num: %v", len(gridMap)) for _, grid := range gridMap { diff --git a/gs/game/game_plugin_manager.go b/gs/game/game_plugin_manager.go index 02ec5b23..81368e5f 100644 --- a/gs/game/game_plugin_manager.go +++ b/gs/game/game_plugin_manager.go @@ -3,6 +3,8 @@ package game import ( "errors" "fmt" + "hk4e/common/constant" + "hk4e/common/mq" "reflect" "sort" @@ -35,6 +37,11 @@ const ( PluginEventIdAvatarDieAnimationEnd PluginEventIdGadgetInteract PluginEventIdPostEnterScene + PluginEventIdMatchCreateAi + PluginEventIdJoinOtherWorld + PluginEventIdEvtDoSkillSucc + PluginEventIdBackMyWorld + PluginEventIdUserOffline ) // PluginEventKillAvatar 角色被杀死 @@ -73,6 +80,43 @@ type PluginEventPostEnterScene struct { Req *proto.PostEnterSceneReq // 请求 } +// PluginEventMatchCreateAi 匹配服请求创建ai +type PluginEventMatchCreateAi struct { + *PluginEvent + GameType uint8 // 游戏类型 + GameId uint32 // 游戏id + RoomId uint32 // 房间id + Ai *model.Player // ai +} + +// PluginEventJoinOtherWorld 加入其他人的世界 +type PluginEventJoinOtherWorld struct { + *PluginEvent + Player *model.Player // 玩家 + HostPlayer *model.Player // 主机玩家 +} + +// PluginEventEvtDoSkillSucc 使用技能完毕 +type PluginEventEvtDoSkillSucc struct { + *PluginEvent + Player *model.Player // 玩家 + Ntf *proto.EvtDoSkillSuccNotify // 通知 +} + +// PluginEventBackMyWorld 玩家返回自己的世界 +type PluginEventBackMyWorld struct { + *PluginEvent + Player *model.Player // 玩家 + HostWorld *World // 主机世界 +} + +// PluginEventUserOffline 玩家离线 +type PluginEventUserOffline struct { + *PluginEvent + Player *model.Player // 玩家 + ChangeGsInfo *ChangeGsInfo // 改变gs信息 +} + type PluginEventFunc func(event IPluginEvent) // IPluginEvent 插件事件接口 @@ -131,7 +175,17 @@ type PluginGlobalTick uint8 const ( PluginGlobalTickSecond = PluginGlobalTick(iota) + PluginGlobalTick50MilliSecond + PluginGlobalTick100MilliSecond + PluginGlobalTick200MilliSecond + PluginGlobalTick5Second + PluginGlobalTick10Second + PluginGlobalTickMinute + PluginGlobalTickHour PluginGlobalTickMinuteChange + PluginGlobalTickHourChange + PluginGlobalTickDayChange + PluginGlobalTickMonthChange ) // PluginUserTimerFunc 用户timer处理函数 @@ -139,18 +193,18 @@ type PluginUserTimerFunc func(player *model.Player, data []any) // Plugin 插件结构 type Plugin struct { - isEnable bool // 是否启用 - eventMap map[PluginEventId][]*PluginEventInfo // 事件集合 - globalTickMap map[PluginGlobalTick][]func() // 全局tick集合 - userTimerMap map[uint64]PluginUserTimerFunc // 用户timer集合 - commandControllerList []*CommandController // 命令控制器列表 + isEnable bool // 是否启用 + eventMap map[PluginEventId][]*PluginEventInfo // 事件集合 + globalTickMap map[PluginGlobalTick][]func(now int64) // 全局tick集合 + userTimerMap map[uint64]PluginUserTimerFunc // 用户timer集合 + commandControllerList []*CommandController // 命令控制器列表 } func NewPlugin() *Plugin { return &Plugin{ isEnable: true, eventMap: make(map[PluginEventId][]*PluginEventInfo), - globalTickMap: make(map[PluginGlobalTick][]func()), + globalTickMap: make(map[PluginGlobalTick][]func(now int64)), userTimerMap: make(map[uint64]PluginUserTimerFunc), commandControllerList: make([]*CommandController, 0), } @@ -188,11 +242,11 @@ func (p *Plugin) ListenEvent(eventId PluginEventId, priority PluginEventPriority } // AddGlobalTick 添加全局tick -func (p *Plugin) AddGlobalTick(tick PluginGlobalTick, tickFuncList ...func()) { +func (p *Plugin) AddGlobalTick(tick PluginGlobalTick, tickFuncList ...func(now int64)) { for _, tickFunc := range tickFuncList { _, exist := p.globalTickMap[tick] if !exist { - p.globalTickMap[tick] = make([]func(), 0) + p.globalTickMap[tick] = make([]func(now int64), 0) } p.globalTickMap[tick] = append(p.globalTickMap[tick], tickFunc) } @@ -213,6 +267,44 @@ func (p *Plugin) RegCommandController(controller *CommandController) { COMMAND_MANAGER.RegController(controller) } +// MatchGameStart 发送匹配服游戏开始通知 +func (p *Plugin) MatchGameStart(ai *model.Player, gameId uint32, roomId uint32) { + if ai.MultiServerAppId == "" { + logger.Error("ai multiServerAppId empty, gameId: %v, roomId: %v, uid: %v", gameId, roomId, ai.PlayerId) + return + } + // 禁止世界进入玩家 + ai.PropertiesMap[constant.PLAYER_PROP_PLAYER_MP_SETTING_TYPE] = 0 + + MESSAGE_QUEUE.SendToMulti(ai.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchGameStartNotify, + ServerMsg: &mq.ServerMsg{ + MatchGameId: gameId, + MatchRoomId: roomId, + }, + }) +} + +// MatchGameStop 发送匹配服游戏结束通知 +func (p *Plugin) MatchGameStop(ai *model.Player, gameId uint32, roomId uint32) { + if ai.MultiServerAppId == "" { + logger.Error("ai multiServerAppId empty, gameId: %v, roomId: %v, uid: %v", gameId, roomId, ai.PlayerId) + return + } + // 清除ai + AI_MANAGER.DeleteAi(ai.PlayerId) + + MESSAGE_QUEUE.SendToMulti(ai.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchGameStopNotify, + ServerMsg: &mq.ServerMsg{ + MatchGameId: gameId, + MatchRoomId: roomId, + }, + }) +} + type PluginManager struct { pluginMap map[reflect.Type]IPlugin // 插件集合 userTimerCounter uint64 // 用户timer计数器 @@ -336,7 +428,7 @@ func (p *PluginManager) TriggerEvent(eventId PluginEventId, event IPluginEvent) } // HandleGlobalTick 处理全局tick -func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick) { +func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick, now int64) { for _, iPlugin := range p.pluginMap { plugin := iPlugin.GetPlugin() // 插件未启用则跳过 @@ -349,7 +441,7 @@ func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick) { continue } for _, tickFunc := range tickFuncList { - tickFunc() + tickFunc(now) } } } diff --git a/gs/game/game_plugin_pubg.go b/gs/game/game_plugin_pubg.go index 15a84c2e..07c811e8 100644 --- a/gs/game/game_plugin_pubg.go +++ b/gs/game/game_plugin_pubg.go @@ -2,7 +2,6 @@ package game import ( "encoding/base64" - "fmt" "math" "time" @@ -18,7 +17,18 @@ import ( ) const ( - PUBG_PHASE_WAIT = -1 + PUBG_STATE_WAIT = iota + PUBG_STATE_START + PUBG_STATE_STOP +) + +const ( + PUBG_START_MIN_PLAYER_COUNT = 2 // pubg游戏开始需要的最少玩家数 + PUBG_WAIT_TICK = 30 // pubg游戏玩家人数足够后需等待的时间 + PUBG_STOP_TICK = 5 // pubg游戏结束后后需等待的时间 +) + +const ( PUBG_PHASE_START = 0 PUBG_PHASE_II = 2 PUBG_PHASE_END = 16 @@ -39,40 +49,42 @@ const ( PUBG_NORMAL_ATTACK_ATK_RATIO = 5.0 ) -// PluginPubg pubg游戏插件 -type PluginPubg struct { - *Plugin - seq uint32 +// PubgGame pubg游戏 +type PubgGame struct { + gameTick uint64 // 游戏tick + gameState uint8 // 游戏状态 + waitTick uint64 // 等待tick + stopTick uint64 // 等待tick + phase uint16 // 阶段 + ai *model.Player // ai world *World // 世界对象 + gameId uint32 // 匹配服游戏id + roomId uint32 // 匹配服房间id + playerUidList []uint32 // 玩家uid列表 blueAreaCenterPos *model.Vector // 蓝区中心点 blueAreaRadius float64 // 蓝区半径 safeAreaCenterPos *model.Vector // 安全区中心点 safeAreaRadius float64 // 安全区半径 - phase int // 阶段 areaReduceRadiusSpeed float64 // 缩圈半径速度 areaReduceXSpeed float64 // 缩圈X速度 areaReduceZSpeed float64 // 缩圈Z速度 areaPointList []*proto.MapMarkPoint // 客户端区域地图坐标列表 entityIdWorldGadgetIdMap map[uint32]int32 // 实体id世界物件id映射集合 playerHitTimeMap map[uint32]int64 // 玩家攻击命中时间集合 + + pluginPubg *PluginPubg +} + +// PluginPubg pubg游戏插件 +type PluginPubg struct { + *Plugin + pubgGameMap map[uint32]*PubgGame // pubg游戏集合 } func NewPluginPubg() *PluginPubg { p := &PluginPubg{ - Plugin: NewPlugin(), - seq: 0, - world: nil, - blueAreaCenterPos: &model.Vector{X: 0.0, Y: 0.0, Z: 0.0}, - blueAreaRadius: 0.0, - safeAreaCenterPos: &model.Vector{X: 0.0, Y: 0.0, Z: 0.0}, - safeAreaRadius: 0.0, - phase: PUBG_PHASE_WAIT, - areaReduceRadiusSpeed: 0.0, - areaReduceXSpeed: 0.0, - areaReduceZSpeed: 0.0, - areaPointList: make([]*proto.MapMarkPoint, 0), - entityIdWorldGadgetIdMap: make(map[uint32]int32), - playerHitTimeMap: make(map[uint32]int64), + Plugin: NewPlugin(), + pubgGameMap: make(map[uint32]*PubgGame), } return p } @@ -85,35 +97,146 @@ func (p *PluginPubg) OnEnable() { p.ListenEvent(PluginEventIdAvatarDieAnimationEnd, PluginEventPriorityNormal, p.EventAvatarDieAnimationEnd) p.ListenEvent(PluginEventIdGadgetInteract, PluginEventPriorityNormal, p.EventGadgetInteract) p.ListenEvent(PluginEventIdPostEnterScene, PluginEventPriorityNormal, p.EventPostEnterScene) + p.ListenEvent(PluginEventIdMatchCreateAi, PluginEventPriorityNormal, p.EventMatchCreateAi) + p.ListenEvent(PluginEventIdJoinOtherWorld, PluginEventPriorityNormal, p.EventJoinOtherWorld) + p.ListenEvent(PluginEventIdEvtDoSkillSucc, PluginEventPriorityNormal, p.EventEvtDoSkillSucc) + p.ListenEvent(PluginEventIdBackMyWorld, PluginEventPriorityNormal, p.EventBackMyWorld) + p.ListenEvent(PluginEventIdUserOffline, PluginEventPriorityNormal, p.EventUserOffline) // 添加全局定时器 p.AddGlobalTick(PluginGlobalTickSecond, p.GlobalTickPubg) - p.AddGlobalTick(PluginGlobalTickMinuteChange, p.GlobalTickMinuteChange) + p.AddGlobalTick(PluginGlobalTick100MilliSecond, p.GlobalTickPubgHit) // 注册命令 - p.RegCommandController(p.NewPubgCommandController()) + // p.RegCommandController(p.NewPubgCommandController()) } /************************************************** 事件监听 **************************************************/ +// EventMatchCreateAi 游戏房间ai创建 +func (p *PluginPubg) EventMatchCreateAi(iEvent IPluginEvent) { + event := iEvent.(*PluginEventMatchCreateAi) + // 判断是否为pubg游戏类型 + if event.GameType != constant.MATCH_GAME_TYPE_PUBG { + return + } + // 创建pubg游戏 + p.CreatePubgGame(event.Ai, event.GameId, event.RoomId, p) +} + +// EventJoinOtherWorld 玩家加入游戏世界 +func (p *PluginPubg) EventJoinOtherWorld(iEvent IPluginEvent) { + event := iEvent.(*PluginEventJoinOtherWorld) + player := event.Player + // 通过ai获取pubg游戏 + pubgGame, exist := p.pubgGameMap[event.HostPlayer.PlayerId] + if !exist { + return + } + p.PlayerJoinGame(player, pubgGame) +} + +// EventBackMyWorld 玩家返回自己的世界 +func (p *PluginPubg) EventBackMyWorld(iEvent IPluginEvent) { + event := iEvent.(*PluginEventBackMyWorld) + player := event.Player + // 通过ai获取pubg游戏 + pubgGame, exist := p.pubgGameMap[event.HostWorld.GetOwner().PlayerId] + if !exist { + return + } + p.PlayerExitGame(player, pubgGame) +} + +// EventUserOffline 玩家离线 +func (p *PluginPubg) EventUserOffline(iEvent IPluginEvent) { + event := iEvent.(*PluginEventUserOffline) + player := event.Player + // 获取玩家所在的世界 + world := WORLD_MANAGER.GetWorldById(player.WorldId) + if world == nil { + return + } + // 通过ai获取pubg游戏 + pubgGame, exist := p.pubgGameMap[world.GetOwner().PlayerId] + if !exist { + return + } + p.PlayerExitGame(player, pubgGame) +} + +// EventEvtDoSkillSucc 使用技能完毕 +func (p *PluginPubg) EventEvtDoSkillSucc(iEvent IPluginEvent) { + event := iEvent.(*PluginEventEvtDoSkillSucc) + player := event.Player + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { + return + } + // 确保游戏开启 + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + return + } + worldAvatar := pubgGame.world.GetWorldAvatarByEntityId(event.Ntf.CasterId) + if worldAvatar == nil { + return + } + avatarDataConfig := gdconf.GetAvatarDataById(int32(worldAvatar.GetAvatarId())) + if avatarDataConfig == nil { + return + } + logger.Debug("avatar normal attack, avatarId: %v, weaponType: %v, uid: %v", avatarDataConfig.AvatarId, avatarDataConfig.WeaponType, player.PlayerId) + switch avatarDataConfig.WeaponType { + case constant.WEAPON_TYPE_SWORD_ONE_HAND, constant.WEAPON_TYPE_CLAYMORE, constant.WEAPON_TYPE_POLE, constant.WEAPON_TYPE_CATALYST, constant.WEAPON_TYPE_BOW: + scene := pubgGame.world.GetSceneById(player.SceneId) + avatarEntity := scene.GetEntity(worldAvatar.GetAvatarEntityId()) + for _, entity := range scene.GetAllEntity() { + if entity.GetId() == avatarEntity.GetId() || entity.GetEntityType() != constant.ENTITY_TYPE_AVATAR { + continue + } + distance3D := math.Sqrt( + (avatarEntity.GetPos().X-entity.GetPos().X)*(avatarEntity.GetPos().X-entity.GetPos().X) + + (avatarEntity.GetPos().Y-entity.GetPos().Y)*(avatarEntity.GetPos().Y-entity.GetPos().Y) + + (avatarEntity.GetPos().Z-entity.GetPos().Z)*(avatarEntity.GetPos().Z-entity.GetPos().Z), + ) + if distance3D > PUBG_NORMAL_ATTACK_DISTANCE { + continue + } + pubgGame.PubgHit(scene, entity.GetId(), avatarEntity.GetId(), false) + } + default: + } +} + // EventKillAvatar 角色被杀死事件 func (p *PluginPubg) EventKillAvatar(iEvent IPluginEvent) { event := iEvent.(*PluginEventKillAvatar) player := event.Player - // 确保游戏开启 - if !p.IsStartPubg() || p.world.GetId() != player.WorldId { + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { return } - p.CreateUserTimer(player.PlayerId, 10, p.UserTimerPubgDieExit, p.world.GetId()) + // 确保游戏开启 + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + return + } + p.CreateUserTimer(player.PlayerId, 10, pubgGame.UserTimerPubgDieExit, pubgGame.world.GetId()) } // EventMarkMap 地图标点事件 func (p *PluginPubg) EventMarkMap(iEvent IPluginEvent) { event := iEvent.(*PluginEventMarkMap) player := event.Player - // 确保游戏开启 - if !p.IsStartPubg() || p.world.GetId() != player.WorldId { + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { return } - GAME.SendMsg(cmd.MarkMapRsp, player.PlayerId, player.ClientSeq, &proto.MarkMapRsp{MarkList: p.GetAreaPointList()}) + // 确保游戏开启 + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + return + } + GAME.SendMsg(cmd.MarkMapRsp, player.PlayerId, player.ClientSeq, &proto.MarkMapRsp{MarkList: pubgGame.GetAreaPointList()}) event.Cancel() } @@ -121,29 +244,37 @@ func (p *PluginPubg) EventMarkMap(iEvent IPluginEvent) { func (p *PluginPubg) EventAvatarDieAnimationEnd(iEvent IPluginEvent) { event := iEvent.(*PluginEventAvatarDieAnimationEnd) player := event.Player - // 确保游戏开启 - if !p.IsStartPubg() || p.world.GetId() != player.WorldId { + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { return } - alivePlayerNum := len(p.GetAlivePlayerList()) - info := fmt.Sprintf("『%v』死亡了,剩余%v位存活玩家。", player.NickName, alivePlayerNum) - GAME.PlayerChatReq(p.world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) - GAME.SendMsg(cmd.AvatarDieAnimationEndRsp, player.PlayerId, player.ClientSeq, &proto.AvatarDieAnimationEndRsp{SkillId: event.Req.SkillId, DieGuid: event.Req.DieGuid}) + // 确保游戏开启 + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + return + } + alivePlayerNum := len(pubgGame.GetAlivePlayerList()) + GAME.SendWorldChat(pubgGame.world, "『%v』死亡了,剩余%v位存活玩家。", player.NickName, alivePlayerNum) event.Cancel() } func (p *PluginPubg) EventGadgetInteract(iEvent IPluginEvent) { event := iEvent.(*PluginEventGadgetInteract) player := event.Player + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { + return + } // 确保游戏开启 - if !p.IsStartPubg() || p.world.GetId() != player.WorldId { + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { return } req := event.Req - worldGadgetId, exist := p.entityIdWorldGadgetIdMap[req.GadgetEntityId] + worldGadgetId, exist := pubgGame.entityIdWorldGadgetIdMap[req.GadgetEntityId] if exist { dbAvatar := player.GetDbAvatar() - avatarId := p.world.GetPlayerActiveAvatarId(player) + avatarId := pubgGame.world.GetPlayerActiveAvatarId(player) avatar := dbAvatar.AvatarMap[avatarId] pubgWorldGadgetDataConfig := gdconf.GetPubgWorldGadgetDataById(worldGadgetId) switch pubgWorldGadgetDataConfig.Type { @@ -151,16 +282,14 @@ func (p *PluginPubg) EventGadgetInteract(iEvent IPluginEvent) { avatar.FightPropMap[constant.FIGHT_PROP_BASE_ATTACK] += float32(pubgWorldGadgetDataConfig.Param[0]) avatar.FightPropMap[constant.FIGHT_PROP_CUR_ATTACK] += float32(pubgWorldGadgetDataConfig.Param[0]) // 提示玩家 - info := fmt.Sprintf("你的角色攻击力增加:%v,增加后的攻击力:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_BASE_ATTACK]) - GAME.PlayerChatReq(p.world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) + GAME.SendWorldChat(pubgGame.world, "你的角色攻击力增加:%v,增加后的攻击力:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_BASE_ATTACK]) case gdconf.PubgWorldGadgetTypeIncHp: avatar.FightPropMap[constant.FIGHT_PROP_CUR_HP] += float32(pubgWorldGadgetDataConfig.Param[0]) if avatar.FightPropMap[constant.FIGHT_PROP_CUR_HP] > avatar.FightPropMap[constant.FIGHT_PROP_MAX_HP] { avatar.FightPropMap[constant.FIGHT_PROP_CUR_HP] = avatar.FightPropMap[constant.FIGHT_PROP_MAX_HP] } // 提示玩家 - info := fmt.Sprintf("你的角色生命值增加:%v,目前为:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_CUR_HP]) - GAME.PlayerChatReq(p.world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) + GAME.SendWorldChat(pubgGame.world, "你的角色生命值增加:%v,目前为:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_CUR_HP]) } GAME.SendMsg(cmd.AvatarFightPropUpdateNotify, player.PlayerId, player.ClientSeq, &proto.AvatarFightPropUpdateNotify{ AvatarGuid: avatar.Guid, @@ -187,8 +316,13 @@ func (p *PluginPubg) EventGadgetInteract(iEvent IPluginEvent) { func (p *PluginPubg) EventPostEnterScene(iEvent IPluginEvent) { event := iEvent.(*PluginEventPostEnterScene) player := event.Player + // 获取玩家所在的pubg游戏 + pubgGame := p.GetPlayerInPubgGame(player) + if pubgGame == nil { + return + } // 确保游戏开启 - if !p.IsStartPubg() || p.world.GetId() != player.WorldId { + if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { return } // 开启GM按钮 隐藏多人世界玩家位置地图标记 @@ -214,70 +348,48 @@ func (p *PluginPubg) EventPostEnterScene(iEvent IPluginEvent) { /************************************************** 全局定时器 **************************************************/ // GlobalTickPubg pubg游戏定时器 -func (p *PluginPubg) GlobalTickPubg() { - world := p.world - if world == nil { - return - } - // 确保游戏开启 - if !p.IsStartPubg() { - return - } - p.UpdateArea() - scene := world.GetSceneById(world.GetOwner().SceneId) - for _, scenePlayer := range scene.GetAllPlayer() { - if !p.IsInBlueArea(scenePlayer.Pos) { - GAME.handleEvtBeingHit(scenePlayer, scene, &proto.EvtBeingHitInfo{ - AttackResult: &proto.AttackResult{ - AttackerId: 0, - DefenseId: world.GetPlayerWorldAvatarEntityId(scenePlayer, world.GetPlayerActiveAvatarId(scenePlayer)), - Damage: PUBG_HP_LOST, - }, - }) +func (p *PluginPubg) GlobalTickPubg(now int64) { + for _, game := range p.pubgGameMap { + // 游戏没有玩家则不进行tick + if len(game.playerUidList) == 0 { + continue } - } - alivePlayerList := p.GetAlivePlayerList() - if len(alivePlayerList) <= 1 { - if len(alivePlayerList) == 1 { - info := fmt.Sprintf("『%v』大吉大利,今晚吃鸡。", alivePlayerList[0].NickName) - GAME.PlayerChatReq(world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) + game.gameTick++ + // 处理当前阶段 + switch game.gameState { + case PUBG_STATE_WAIT: + // 等待阶段 + game.PhaseWait() + case PUBG_STATE_START: + // 开始阶段 + game.HandleStateStart() + case PUBG_STATE_STOP: + // 结束阶段 + game.HandleStateStop() } - p.StopPubg() } } -// GlobalTickMinuteChange 定时开启pubg游戏 -func (p *PluginPubg) GlobalTickMinuteChange() { - minute := time.Now().Minute() - roomNumber := GAME.GetGsId() - 1 - startMinute := roomNumber % 6 * 10 - if uint32(minute) == startMinute { - p.StartPubg() +// GlobalTickPubgHit pubg命中 +func (p *PluginPubg) GlobalTickPubgHit(now int64) { + for _, game := range p.pubgGameMap { + if !game.IsStartPubg() { + return + } + bulletPhysicsEngine := game.world.GetBulletPhysicsEngine() + hitList := bulletPhysicsEngine.Update(now) + for _, rigidBody := range hitList { + scene := game.world.GetSceneById(rigidBody.sceneId) + game.PubgHit(scene, rigidBody.hitAvatarEntityId, rigidBody.avatarEntityId, true) + } } } /************************************************** 用户定时器 **************************************************/ -// UserTimerPubgEnd pubg游戏结束后执行定时器 -func (p *PluginPubg) UserTimerPubgEnd(player *model.Player, data []any) { - logger.Debug("UserTimerPubgEnd, seq: %v", p.seq) - oldWorld := WORLD_MANAGER.GetWorldById(player.WorldId) - if oldWorld == nil { - return - } - GAME.WorldRemovePlayer(oldWorld, player) - newWorld := WORLD_MANAGER.CreateWorld(player) - GAME.WorldAddPlayer(newWorld, player) - WORLD_MANAGER.InitAiWorld(player) - roomNumber := GAME.GetGsId() - 1 - startMinute := roomNumber % 6 * 10 - info := fmt.Sprintf("下一次游戏开启时间:%02d:%02d。", time.Now().Add(time.Hour).Hour(), startMinute) - GAME.PlayerChatReq(player, &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) -} - // UserTimerPubgUpdateArea 更新游戏区域 -func (p *PluginPubg) UserTimerPubgUpdateArea(player *model.Player, data []any) { - logger.Debug("UserTimerPubgUpdateArea, seq: %v", p.seq) +func (p *PubgGame) UserTimerPubgUpdateArea(player *model.Player, data []any) { + logger.Debug("UserTimerPubgUpdateArea, gameId: %v, roomId: %v", p.gameId, p.roomId) if !p.IsStartPubg() { return } @@ -286,8 +398,8 @@ func (p *PluginPubg) UserTimerPubgUpdateArea(player *model.Player, data []any) { } // UserTimerPubgDieExit pubg死亡离开 -func (p *PluginPubg) UserTimerPubgDieExit(player *model.Player, data []any) { - logger.Debug("UserTimerPubgDieExit, seq: %v", p.seq) +func (p *PubgGame) UserTimerPubgDieExit(player *model.Player, data []any) { + logger.Debug("UserTimerPubgDieExit, gameId: %v, roomId: %v", p.gameId, p.roomId) pubgWorldId := data[0].(uint64) if player.WorldId != pubgWorldId { return @@ -323,11 +435,11 @@ func (p *PluginPubg) PubgCommand(c *CommandContent) bool { switch mode { case "start": // 开始游戏 - p.StartPubg() + // p.StartPubg() c.SendSuccMessage(c.Executor, "已开始PUBG游戏。") case "stop": // 结束游戏 - p.StopPubg() + // p.StopPubg() c.SendSuccMessage(c.Executor, "已结束PUBG游戏。") default: return false @@ -338,17 +450,174 @@ func (p *PluginPubg) PubgCommand(c *CommandContent) bool { /************************************************** 插件功能 **************************************************/ -// StartPubg 开始pubg游戏 -func (p *PluginPubg) StartPubg() { - if p.IsStartPubg() { +// CreatePubgGame 创建pubg游戏 +func (p *PluginPubg) CreatePubgGame(ai *model.Player, gameId uint32, roomId uint32, pluginPubg *PluginPubg) { + world := WORLD_MANAGER.GetWorldById(ai.WorldId) + if world == nil { + logger.Error("world is nil, worldId: %v, uid: %v", ai.WorldId, ai.PlayerId) return } - p.seq++ - logger.Debug("StartPubg, seq: %v", p.seq) - world := WORLD_MANAGER.GetAiWorld() - p.world = world - info := "游戏开始。" - GAME.PlayerChatReq(p.world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) + p.pubgGameMap[ai.PlayerId] = &PubgGame{ + gameTick: 0, + gameState: PUBG_STATE_WAIT, + waitTick: PUBG_WAIT_TICK, + stopTick: PUBG_STOP_TICK, + phase: PUBG_PHASE_START, + ai: ai, + world: world, + gameId: gameId, + roomId: roomId, + playerUidList: make([]uint32, 0), + blueAreaCenterPos: &model.Vector{X: 0.0, Y: 0.0, Z: 0.0}, + blueAreaRadius: 0.0, + safeAreaCenterPos: &model.Vector{X: 0.0, Y: 0.0, Z: 0.0}, + safeAreaRadius: 0.0, + areaReduceRadiusSpeed: 0.0, + areaReduceXSpeed: 0.0, + areaReduceZSpeed: 0.0, + areaPointList: make([]*proto.MapMarkPoint, 0), + entityIdWorldGadgetIdMap: make(map[uint32]int32), + playerHitTimeMap: make(map[uint32]int64), + pluginPubg: pluginPubg, + } +} + +// DeletePubgGame 删除pubg游戏 +func (p *PluginPubg) DeletePubgGame(game *PubgGame) { + _, exist := p.pubgGameMap[game.ai.PlayerId] + if !exist { + logger.Error("pubg game not exist, gameId: %v, roomId: %v, aiUid: %v", game.gameId, game.roomId, game.ai.PlayerId) + return + } + delete(p.pubgGameMap, game.ai.PlayerId) +} + +// PlayerJoinGame 玩家加入游戏 +func (p *PluginPubg) PlayerJoinGame(player *model.Player, game *PubgGame) { + // 校验是否已加入 + for _, uid := range game.playerUidList { + if uid == player.PlayerId { + logger.Error("player has been join, uid: %v", player.PlayerId) + return + } + } + game.playerUidList = append(game.playerUidList, player.PlayerId) +} + +// PlayerExitGame 玩家离开游戏 +func (p *PluginPubg) PlayerExitGame(player *model.Player, game *PubgGame) { + // 清除uid + for i, uid := range game.playerUidList { + if uid == player.PlayerId { + game.playerUidList = append(game.playerUidList[:i], game.playerUidList[i+1:]...) + } + } +} + +// GetPlayerInPubgGame 获取玩家所在的pubg游戏 +func (p *PluginPubg) GetPlayerInPubgGame(player *model.Player) *PubgGame { + for _, game := range p.pubgGameMap { + for _, uid := range game.playerUidList { + if uid == player.PlayerId { + return game + } + } + } + return nil +} + +// PhaseWait 等待阶段处理 +func (p *PubgGame) PhaseWait() { + // 玩家数是否到达设定值 到达则开始倒计时 没有则提示玩家 + if len(p.playerUidList) >= PUBG_START_MIN_PLAYER_COUNT { + switch p.waitTick { + case PUBG_WAIT_TICK: + GAME.SendWorldChat(p.world, "玩家数量足够,开始倒计时!\n感谢各位玩家参与PUBG游戏~") + case 20, 10, 5, 4, 3, 2, 1: + GAME.SendWorldChat(p.world, "游戏将在%v秒后开始!", p.waitTick) + case 0: + // 倒计时到了则开始游戏 + p.StartPubg() + return + } + p.waitTick-- // 计时-1 + + // 如果人少于设定值并正在倒计时的话那就是取消了 + } else if p.waitTick != PUBG_WAIT_TICK { + GAME.SendWorldChat(p.world, "玩家数量不足!暂停游戏开始倒计时。") + // 重置计时器 + p.waitTick = PUBG_WAIT_TICK + + // 玩家不足每5s提示一次 + } else if p.gameTick%5 == 0 { + GAME.SendWorldChat(p.world, "玩家数量不足,还需要%v名玩家加入。", PUBG_START_MIN_PLAYER_COUNT-len(p.playerUidList)) + } +} + +// HandleStateStart 开始状态处理 +func (p *PubgGame) HandleStateStart() { + // 更新区域 + p.UpdateArea() + scene := p.world.GetSceneById(p.world.GetOwner().SceneId) + for _, scenePlayer := range scene.GetAllPlayer() { + if !p.IsInBlueArea(scenePlayer.Pos) { + GAME.handleEvtBeingHit(scenePlayer, scene, &proto.EvtBeingHitInfo{ + AttackResult: &proto.AttackResult{ + AttackerId: 0, + DefenseId: p.world.GetPlayerWorldAvatarEntityId(scenePlayer, p.world.GetPlayerActiveAvatarId(scenePlayer)), + Damage: PUBG_HP_LOST, + }, + }) + } + } + // 判断玩家存活状况 + alivePlayerList := p.GetAlivePlayerList() + if len(alivePlayerList) <= 1 { + if len(alivePlayerList) == 1 { + GAME.SendWorldChat(p.world, "『%v』大吉大利,今晚吃鸡。", alivePlayerList[0].NickName) + } + p.StopPubg() + } +} + +// HandleStateStop 结束状态处理 +func (p *PubgGame) HandleStateStop() { + if p.stopTick <= 0 { + GAME.SendWorldChat(p.world, "游戏结束。") + // 清除游戏 + p.pluginPubg.DeletePubgGame(p) + // 通知匹配服游戏结束 + p.pluginPubg.MatchGameStop(p.ai, p.gameId, p.roomId) + return + } + p.stopTick-- +} + +// WaitPubg 等待pubg游戏开始 +func (p *PubgGame) WaitPubg() { + logger.Debug("WaitPubg, gameId: %v, roomId: %v", p.gameId, p.roomId) + // 确保上个阶段为结束状态 + if p.gameState != PUBG_STATE_STOP { + logger.Error("pubg game state not end, gameState: %v", p.gameState) + return + } + // 切换阶段 + p.gameState = PUBG_STATE_WAIT +} + +// StartPubg 开始pubg游戏 +func (p *PubgGame) StartPubg() { + logger.Debug("StartPubg, gameId: %v, roomId: %v", p.gameId, p.roomId) + // 确保上个阶段为等待状态 + if p.gameState != PUBG_STATE_WAIT { + logger.Error("pubg game state not wait, gameState: %v", p.gameState) + return + } + // 切换阶段 + p.gameState = PUBG_STATE_START + // 重置game tick + p.gameTick = 0 + // 初始化pubg游戏 for _, pubgWorldGadgetDataConfig := range gdconf.GetPubgWorldGadgetDataMap() { rn := random.GetRandomInt32(1, 100) if rn > pubgWorldGadgetDataConfig.Probability { @@ -362,9 +631,13 @@ func (p *PluginPubg) StartPubg() { ) p.entityIdWorldGadgetIdMap[entityId] = pubgWorldGadgetDataConfig.WorldGadgetId } - p.phase = PUBG_PHASE_START + // 刷新区域 p.RefreshArea() - for _, player := range world.GetAllPlayer() { + for _, player := range p.world.GetAllPlayer() { + // 跳过ai + if player.PlayerId == p.ai.PlayerId { + continue + } dbAvatar := player.GetDbAvatar() avatarId := p.world.GetPlayerActiveAvatarId(player) avatar := dbAvatar.AvatarMap[avatarId] @@ -381,45 +654,46 @@ func (p *PluginPubg) StartPubg() { FightPropMap: avatar.FightPropMap, }) p.playerHitTimeMap[player.PlayerId] = 0 + // 传送玩家至ai身边 + GAME.TeleportPlayer( + player, + proto.EnterReason_ENTER_REASON_GM, + p.ai.SceneId, + &model.Vector{X: p.ai.Pos.X, Y: p.ai.Pos.Y, Z: p.ai.Pos.Z}, + new(model.Vector), + 0, + 0, + ) } + GAME.SendWorldChat(p.world, "游戏开始。祝您游戏愉快~") + // 通知匹配服游戏开始 + p.pluginPubg.MatchGameStart(p.ai, p.gameId, p.roomId) } // StopPubg 结束pubg游戏 -func (p *PluginPubg) StopPubg() { +func (p *PubgGame) StopPubg() { + logger.Debug("StopPubg, gameId: %v, roomId: %v", p.gameId, p.roomId) + // 确保上个阶段为不为等待状态和结束状态 if !p.IsStartPubg() { + logger.Error("pubg game state not end, gameState: %v", p.gameState) return } - logger.Debug("StopPubg, seq: %v", p.seq) - owner := p.world.GetOwner() - p.world = nil - p.blueAreaCenterPos = &model.Vector{X: 0.0, Y: 0.0, Z: 0.0} - p.blueAreaRadius = 0.0 - p.safeAreaCenterPos = &model.Vector{X: 0.0, Y: 0.0, Z: 0.0} - p.safeAreaRadius = 0.0 - p.phase = PUBG_PHASE_WAIT - p.areaReduceRadiusSpeed = 0.0 - p.areaReduceXSpeed = 0.0 - p.areaReduceZSpeed = 0.0 - p.areaPointList = make([]*proto.MapMarkPoint, 0) - p.entityIdWorldGadgetIdMap = make(map[uint32]int32) - p.playerHitTimeMap = make(map[uint32]int64) - p.CreateUserTimer(owner.PlayerId, 60, p.UserTimerPubgEnd) - info := "游戏结束。" - GAME.PlayerChatReq(owner, &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) + // 切换阶段 + p.gameState = PUBG_STATE_STOP } // IsStartPubg pubg游戏是否开启 -func (p *PluginPubg) IsStartPubg() bool { - return p.phase != PUBG_PHASE_WAIT +func (p *PubgGame) IsStartPubg() bool { + return p.gameState != PUBG_STATE_WAIT && p.gameState != PUBG_STATE_STOP } // GetAreaPointList 获取游戏区域标点列表 -func (p *PluginPubg) GetAreaPointList() []*proto.MapMarkPoint { +func (p *PubgGame) GetAreaPointList() []*proto.MapMarkPoint { return p.areaPointList } // UpdateArea 更新游戏区域 -func (p *PluginPubg) UpdateArea() { +func (p *PubgGame) UpdateArea() { if p.areaReduceRadiusSpeed > 0.0 && p.blueAreaRadius > p.safeAreaRadius { p.blueAreaRadius -= p.areaReduceRadiusSpeed p.blueAreaCenterPos.X += p.areaReduceXSpeed @@ -429,7 +703,7 @@ func (p *PluginPubg) UpdateArea() { } // IsInBlueArea 是否在蓝圈内 -func (p *PluginPubg) IsInBlueArea(pos *model.Vector) bool { +func (p *PubgGame) IsInBlueArea(pos *model.Vector) bool { distance2D := math.Sqrt( (p.blueAreaCenterPos.X-pos.X)*(p.blueAreaCenterPos.X-pos.X) + (p.blueAreaCenterPos.Z-pos.Z)*(p.blueAreaCenterPos.Z-pos.Z), @@ -438,23 +712,22 @@ func (p *PluginPubg) IsInBlueArea(pos *model.Vector) bool { } // RefreshArea 刷新游戏区域 -func (p *PluginPubg) RefreshArea() { - info := "" +func (p *PubgGame) RefreshArea() { if p.phase == PUBG_PHASE_START { - info = fmt.Sprintf("安全区已生成,当前%v位存活玩家。", len(p.GetAlivePlayerList())) + GAME.SendWorldChat(p.world, "安全区已生成,当前%v位存活玩家。", len(p.GetAlivePlayerList())) p.blueAreaCenterPos = &model.Vector{X: 500.0, Y: 0.0, Z: -500.0} p.blueAreaRadius = 2000.0 p.safeAreaCenterPos = &model.Vector{X: 0.0, Y: 0.0, Z: 0.0} p.safeAreaRadius = 0.0 - p.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) + p.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) } else if p.phase == PUBG_PHASE_END { - info = "安全区已消失。" + GAME.SendWorldChat(p.world, "安全区已消失。") p.blueAreaRadius = 0.0 p.safeAreaRadius = 0.0 } else { switch p.phase % 3 { case 1: - info = fmt.Sprintf("新的安全区已出现,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + GAME.SendWorldChat(p.world, "新的安全区已出现,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) p.safeAreaCenterPos = &model.Vector{ X: p.blueAreaCenterPos.X + random.GetRandomFloat64(-(p.blueAreaRadius*0.7/2.0), p.blueAreaRadius*0.7/2.0), Y: 0.0, @@ -462,9 +735,9 @@ func (p *PluginPubg) RefreshArea() { } p.safeAreaRadius = p.blueAreaRadius / 2.0 p.areaReduceRadiusSpeed = 0.0 - p.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) + p.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) case 2: - info = fmt.Sprintf("安全区正在缩小,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + GAME.SendWorldChat(p.world, "安全区正在缩小,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) invTime := 0.0 if p.phase == PUBG_PHASE_II { invTime = PUBG_FIRST_AREA_REDUCE_TIME @@ -474,18 +747,17 @@ func (p *PluginPubg) RefreshArea() { p.areaReduceRadiusSpeed = (p.blueAreaRadius - p.safeAreaRadius) / invTime p.areaReduceXSpeed = (p.safeAreaCenterPos.X - p.blueAreaCenterPos.X) / invTime p.areaReduceZSpeed = (p.safeAreaCenterPos.Z - p.blueAreaCenterPos.Z) / invTime - p.CreateUserTimer(p.world.GetOwner().PlayerId, uint32(invTime), p.UserTimerPubgUpdateArea) + p.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, uint32(invTime), p.UserTimerPubgUpdateArea) case 0: - info = fmt.Sprintf("安全区缩小完毕,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) - p.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) + GAME.SendWorldChat(p.world, "安全区缩小完毕,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + p.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) } } p.SyncMapMarkArea() - GAME.PlayerChatReq(p.world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) } // SyncMapMarkArea 同步地图标点区域 -func (p *PluginPubg) SyncMapMarkArea() { +func (p *PubgGame) SyncMapMarkArea() { p.areaPointList = make([]*proto.MapMarkPoint, 0) if p.blueAreaRadius > 0.0 { for angleStep := 0; angleStep < 360; angleStep += 5 { @@ -517,7 +789,7 @@ func (p *PluginPubg) SyncMapMarkArea() { } // GetAlivePlayerList 获取存活玩家列表 -func (p *PluginPubg) GetAlivePlayerList() []*model.Player { +func (p *PubgGame) GetAlivePlayerList() []*model.Player { scene := p.world.GetSceneById(p.world.GetOwner().SceneId) alivePlayerList := make([]*model.Player, 0) for _, scenePlayer := range scene.GetAllPlayer() { @@ -534,7 +806,7 @@ func (p *PluginPubg) GetAlivePlayerList() []*model.Player { return alivePlayerList } -func (p *PluginPubg) PubgHit(scene *Scene, defAvatarEntityId uint32, atkAvatarEntityId uint32, isBow bool) { +func (p *PubgGame) PubgHit(scene *Scene, defAvatarEntityId uint32, atkAvatarEntityId uint32, isBow bool) { defAvatarEntity := scene.GetEntity(defAvatarEntityId) if defAvatarEntity == nil { return diff --git a/gs/game/game_route_manager.go b/gs/game/game_route_manager.go index b58a8ace..aa6ea4a9 100644 --- a/gs/game/game_route_manager.go +++ b/gs/game/game_route_manager.go @@ -196,7 +196,7 @@ func (r *RouteManager) RouteHandle(netMsg *mq.NetMsg) { serverMsg := netMsg.ServerMsg switch netMsg.EventId { case mq.ServerUserOnlineStateChangeNotify: - logger.Debug("remote user online state change, uid: %v, online: %v", serverMsg.UserId, serverMsg.IsOnline) + logger.Debug("remote user online gameState change, uid: %v, online: %v", serverMsg.UserId, serverMsg.IsOnline) USER_MANAGER.SetRemoteUserOnlineState(serverMsg.UserId, serverMsg.IsOnline, netMsg.OriginServerAppId) case mq.ServerAppidBindNotify: GAME.ServerAppidBindNotify(serverMsg.UserId, serverMsg.MultiServerAppId) @@ -220,6 +220,12 @@ func (r *RouteManager) RouteHandle(netMsg *mq.NetMsg) { ParamList: serverMsg.GmCmdParamList, ResultChan: nil, } + case mq.ServerGetMatchGameListRsp: + GAME.ServerGetMatchGameListRsp(serverMsg.UserId, serverMsg.MatchGameList) + case mq.ServerGetMatchRoomAiUidRsp: + GAME.ServerGetMatchRoomAiUidRsp(serverMsg.UserId, serverMsg.MatchAiUid) + case mq.ServerMatchCreateAiReq: + GAME.ServerMatchCreateAiReq(serverMsg.MatchGameType, serverMsg.MatchGameId, serverMsg.MatchRoomId, serverMsg.MatchAiInfo, netMsg.OriginServerAppId) } } } diff --git a/gs/game/game_tick_manager.go b/gs/game/game_tick_manager.go index 067d4665..8d81f325 100644 --- a/gs/game/game_tick_manager.go +++ b/gs/game/game_tick_manager.go @@ -159,28 +159,35 @@ func (t *TickManager) OnGameServerTick() { now := tm.UnixMilli() if t.globalTickCount%(50/ServerTickTime) == 0 { t.onTick50MilliSecond(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTick50MilliSecond, now) } if t.globalTickCount%(100/ServerTickTime) == 0 { t.onTick100MilliSecond(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTick100MilliSecond, now) } if t.globalTickCount%(200/ServerTickTime) == 0 { t.onTick200MilliSecond(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTick200MilliSecond, now) } if t.globalTickCount%(1000/ServerTickTime) == 0 { t.onTickSecond(now) - PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickSecond) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickSecond, now) } if t.globalTickCount%(5000/ServerTickTime) == 0 { t.onTick5Second(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTick5Second, now) } if t.globalTickCount%(10000/ServerTickTime) == 0 { t.onTick10Second(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTick10Second, now) } if t.globalTickCount%(60000/ServerTickTime) == 0 { t.onTickMinute(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMinute, now) } if t.globalTickCount%(60000*60/ServerTickTime) == 0 { t.onTickHour(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickHour, now) } for userId, userTick := range t.userTickMap { if len(userTick.globalTick.C) == 0 { @@ -206,16 +213,19 @@ func (t *TickManager) OnGameServerTick() { } if tm.Minute() != t.tm.Minute() { t.onMinuteChange(now) - PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMinuteChange) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMinuteChange, now) } if tm.Hour() != t.tm.Hour() { t.onHourChange(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickHourChange, now) } if tm.Day() != t.tm.Day() { t.onDayChange(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickDayChange, now) } if tm.Month() != t.tm.Month() { t.onMonthChange(now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMonthChange, now) } t.tm = tm } @@ -265,22 +275,11 @@ func (t *TickManager) onTick5Second(now int64) { GAME.ScenePlayerLocationNotify(world) } } - iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) - if err != nil { - logger.Error("get plugin pubg error: %v", err) - return - } - pluginPubg := iPlugin.(*PluginPubg) - agree := true - if pluginPubg.IsStartPubg() { - agree = false - } - aiWorld := WORLD_MANAGER.GetAiWorld() - if aiWorld.GetWorldPlayerNum() >= 100 { - agree = false - } - for applyUid := range aiWorld.GetOwner().CoopApplyMap { - GAME.PlayerDealEnterWorld(aiWorld.GetOwner(), applyUid, agree) + // ai世界自动同意进入 + for _, player := range AI_MANAGER.aiMap { + for applyUid := range player.CoopApplyMap { + GAME.PlayerDealEnterWorld(player, applyUid, true) + } } } @@ -325,29 +324,12 @@ func (t *TickManager) onTick100MilliSecond(now int64) { } } } - - iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) - if err != nil { - logger.Error("get plugin pubg error: %v", err) - return - } - pluginPubg := iPlugin.(*PluginPubg) - if !pluginPubg.IsStartPubg() { - return - } - world := WORLD_MANAGER.GetAiWorld() - bulletPhysicsEngine := world.GetBulletPhysicsEngine() - hitList := bulletPhysicsEngine.Update(now) - for _, rigidBody := range hitList { - scene := world.GetSceneById(rigidBody.sceneId) - pluginPubg.PubgHit(scene, rigidBody.hitAvatarEntityId, rigidBody.avatarEntityId, true) - } } func (t *TickManager) onTick50MilliSecond(now int64) { // 音乐播放器 for i := 0; i < len(AUDIO_CHAN); i++ { - world := WORLD_MANAGER.GetAiWorld() + world := WORLD_MANAGER.GetWorldById(GAME.ai.WorldId) GAME.SendToWorldA(world, cmd.SceneAudioNotify, 0, &proto.SceneAudioNotify{ Type: 5, SourceUid: world.GetOwner().PlayerId, diff --git a/gs/game/game_user_manager.go b/gs/game/game_user_manager.go index 8daf1e36..fe3c1bcf 100644 --- a/gs/game/game_user_manager.go +++ b/gs/game/game_user_manager.go @@ -174,6 +174,15 @@ type PlayerOfflineInfo struct { // OfflineUser 玩家离线 func (u *UserManager) OfflineUser(player *model.Player, changeGsInfo *ChangeGsInfo) { + // 触发事件 + if PLUGIN_MANAGER.TriggerEvent(PluginEventIdUserOffline, &PluginEventUserOffline{ + PluginEvent: NewPluginEvent(), + Player: player, + ChangeGsInfo: changeGsInfo, + }) { + return + } + if player.OfflineNotSave { LOCAL_EVENT_MANAGER.GetLocalEventChan() <- &LocalEvent{ EventId: UserOfflineSaveToDbFinish, @@ -232,22 +241,22 @@ func (u *UserManager) ChangeUserDbState(player *model.Player, state int) { } else if state == model.DbNormal { player.DbState = model.DbNormal } else { - logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) } case model.DbInsert: - logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) break case model.DbDelete: if state == model.DbNormal { player.DbState = model.DbNormal } else { - logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) } case model.DbNormal: if state == model.DbDelete { player.DbState = model.DbDelete } else { - logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) } } } @@ -319,12 +328,10 @@ func (u *UserManager) SetRemoteUserOnlineState(userId uint32, isOnline bool, app func (u *UserManager) GetAllRemoteAiUidList() []uint32 { userIdList := make([]uint32, 0) u.remotePlayerMapLock.RLock() - for userId := uint32(AiBaseUid); userId < AiBaseUid+1000; userId++ { - _, exist := u.remotePlayerMap[userId] - if !exist { - continue + for userId := range u.remotePlayerMap { + if userId <= PlayerBaseUid { + userIdList = append(userIdList, userId) } - userIdList = append(userIdList, userId) } u.remotePlayerMapLock.RUnlock() return userIdList @@ -546,7 +553,7 @@ func (u *UserManager) SaveUserToDbSync(player *model.Player) { return } } else { - logger.Error("invalid player db state: %v", player.DbState) + logger.Error("invalid player db gameState: %v", player.DbState) } } diff --git a/gs/game/game_world_manager.go b/gs/game/game_world_manager.go index c216ea14..95b0753a 100644 --- a/gs/game/game_world_manager.go +++ b/gs/game/game_world_manager.go @@ -24,7 +24,6 @@ const ( type WorldManager struct { worldMap map[uint64]*World snowflake *alg.SnowflakeWorker - aiWorld *World // 本服的Ai玩家世界 sceneBlockAoiMap map[uint32]*alg.AoiManager // 全局各场景地图的aoi管理器 multiplayerWorldNum uint32 // 本服务器的多人世界数量 } @@ -92,20 +91,15 @@ func (w *WorldManager) DestroyWorld(worldId uint64) { } } -// GetAiWorld 获取本服务器的Ai世界 -func (w *WorldManager) GetAiWorld() *World { - return w.aiWorld -} - // InitAiWorld 初始化Ai世界 func (w *WorldManager) InitAiWorld(owner *model.Player) { - w.aiWorld = w.GetWorldById(owner.WorldId) - w.aiWorld.ChangeToMultiplayer() - w.aiWorld.NewPhysicsEngine() + aiWorld := w.GetWorldById(owner.WorldId) + aiWorld.ChangeToMultiplayer() + aiWorld.NewPhysicsEngine() } func (w *WorldManager) IsAiWorld(world *World) bool { - return world.owner.PlayerId < PlayerBaseUid + return AI_MANAGER.IsAi(world.owner.PlayerId) } func (w *WorldManager) GetSceneBlockAoiMap() map[uint32]*alg.AoiManager { diff --git a/gs/game/player_chat.go b/gs/game/player_chat.go index 30eb04a1..622d1a60 100644 --- a/gs/game/player_chat.go +++ b/gs/game/player_chat.go @@ -1,6 +1,7 @@ package game import ( + "fmt" "time" "hk4e/common/mq" @@ -180,6 +181,12 @@ func (g *Game) PlayerChatReq(player *model.Player, payloadMsg pb.Message) { /************************************************** 游戏功能 **************************************************/ +// SendWorldChat 发送世界聊天 +func (g *Game) SendWorldChat(world *World, msg string, param ...any) { + info := fmt.Sprintf(msg, param...) + g.PlayerChatReq(world.GetOwner(), &proto.PlayerChatReq{ChatInfo: &proto.ChatInfo{Content: &proto.ChatInfo_Text{Text: info}}}) +} + // SendPrivateChat 发送私聊文本消息给玩家 func (g *Game) SendPrivateChat(player *model.Player, targetUid uint32, content any) { chatMsg := &model.ChatMsg{ diff --git a/gs/game/player_fight_sync.go b/gs/game/player_fight_sync.go index 30d0b59f..44dbf4a7 100644 --- a/gs/game/player_fight_sync.go +++ b/gs/game/player_fight_sync.go @@ -692,54 +692,19 @@ func (g *Game) EvtDoSkillSuccNotify(player *model.Player, payloadMsg pb.Message) return } // logger.Debug("EvtDoSkillSuccNotify: %+v", ntf) + + // 触发事件 + if PLUGIN_MANAGER.TriggerEvent(PluginEventIdEvtDoSkillSucc, &PluginEventEvtDoSkillSucc{ + PluginEvent: NewPluginEvent(), + Player: player, + Ntf: ntf, + }) { + return + } + // 处理技能开始的耐力消耗 g.SkillStartStamina(player, ntf.CasterId, ntf.SkillId) g.TriggerQuest(player, constant.QUEST_FINISH_COND_TYPE_SKILL, "", int32(ntf.SkillId)) - world := WORLD_MANAGER.GetWorldById(player.WorldId) - if world == nil { - return - } - if !WORLD_MANAGER.IsAiWorld(world) { - return - } - iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) - if err != nil { - logger.Error("get plugin pubg error: %v", err) - return - } - pluginPubg := iPlugin.(*PluginPubg) - if !pluginPubg.IsStartPubg() { - return - } - worldAvatar := world.GetWorldAvatarByEntityId(ntf.CasterId) - if worldAvatar == nil { - return - } - avatarDataConfig := gdconf.GetAvatarDataById(int32(worldAvatar.GetAvatarId())) - if avatarDataConfig == nil { - return - } - logger.Debug("avatar normal attack, avatarId: %v, weaponType: %v, uid: %v", avatarDataConfig.AvatarId, avatarDataConfig.WeaponType, player.PlayerId) - switch avatarDataConfig.WeaponType { - case constant.WEAPON_TYPE_SWORD_ONE_HAND, constant.WEAPON_TYPE_CLAYMORE, constant.WEAPON_TYPE_POLE, constant.WEAPON_TYPE_CATALYST, constant.WEAPON_TYPE_BOW: - scene := world.GetSceneById(player.SceneId) - avatarEntity := scene.GetEntity(worldAvatar.GetAvatarEntityId()) - for _, entity := range scene.GetAllEntity() { - if entity.GetId() == avatarEntity.GetId() || entity.GetEntityType() != constant.ENTITY_TYPE_AVATAR { - continue - } - distance3D := math.Sqrt( - (avatarEntity.GetPos().X-entity.GetPos().X)*(avatarEntity.GetPos().X-entity.GetPos().X) + - (avatarEntity.GetPos().Y-entity.GetPos().Y)*(avatarEntity.GetPos().Y-entity.GetPos().Y) + - (avatarEntity.GetPos().Z-entity.GetPos().Z)*(avatarEntity.GetPos().Z-entity.GetPos().Z), - ) - if distance3D > PUBG_NORMAL_ATTACK_DISTANCE { - continue - } - pluginPubg.PubgHit(scene, entity.GetId(), avatarEntity.GetId(), false) - } - default: - } } func (g *Game) EvtAvatarEnterFocusNotify(player *model.Player, payloadMsg pb.Message) { diff --git a/gs/game/player_multiplayer.go b/gs/game/player_multiplayer.go index 760b9c6e..ddb870e6 100644 --- a/gs/game/player_multiplayer.go +++ b/gs/game/player_multiplayer.go @@ -16,6 +16,16 @@ import ( /************************************************** 接口请求 **************************************************/ +// ServerGetMatchRoomAiUidRsp 获取房间ai的uid响应 +func (g *Game) ServerGetMatchRoomAiUidRsp(userId uint32, aiUid uint32) { + player := USER_MANAGER.GetOnlineUser(userId) + if player == nil { + logger.Error("player is nil, uid: %v", userId) + return + } + g.PlayerApplyEnterWorld(player, aiUid) +} + func (g *Game) PlayerApplyEnterMpReq(player *model.Player, payloadMsg pb.Message) { req := payloadMsg.(*proto.PlayerApplyEnterMpReq) targetUid := req.TargetUid @@ -25,6 +35,20 @@ func (g *Game) PlayerApplyEnterMpReq(player *model.Player, payloadMsg pb.Message } g.SendMsg(cmd.PlayerApplyEnterMpRsp, player.PlayerId, player.ClientSeq, playerApplyEnterMpRsp) + // 确保匹配游戏id存在 发送到匹配服异步获取房间ai的uid + _, exist := AI_MANAGER.gameRoomAiUidMap[targetUid] + if exist && player.MultiServerAppId != "" { + MESSAGE_QUEUE.SendToMulti(player.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerGetMatchRoomAiUidReq, + ServerMsg: &mq.ServerMsg{ + UserId: player.PlayerId, + MatchGameId: targetUid, + }, + }) + return + } + g.PlayerApplyEnterWorld(player, targetUid) } @@ -100,6 +124,21 @@ func (g *Game) PlayerGetForceQuitBanInfoReq(player *model.Player, payloadMsg pb. } func (g *Game) BackMyWorldReq(player *model.Player, payloadMsg pb.Message) { + // 获取玩家现在所在的世界 + world := WORLD_MANAGER.GetWorldById(player.WorldId) + if world == nil { + logger.Error("world is nil, worldId: %v, uid: %v", player.WorldId, player.PlayerId) + return + } + // 触发事件 + if PLUGIN_MANAGER.TriggerEvent(PluginEventIdBackMyWorld, &PluginEventBackMyWorld{ + PluginEvent: NewPluginEvent(), + Player: player, + HostWorld: world, + }) { + return + } + // 其他玩家 ok := g.PlayerLeaveWorld(player, false) @@ -107,6 +146,21 @@ func (g *Game) BackMyWorldReq(player *model.Player, payloadMsg pb.Message) { g.SendError(cmd.BackMyWorldRsp, player, &proto.BackMyWorldRsp{}, proto.Retcode_RET_MP_TARGET_PLAYER_IN_TRANSFER) return } + + // 通知匹配服玩家离开游戏ai的世界 + exist, gameId, roomId := AI_MANAGER.GetAiUidGameId(world.GetOwner().PlayerId) + if exist && player.MultiServerAppId != "" { + MESSAGE_QUEUE.SendToMulti(player.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchPlayerExitGameNotify, + ServerMsg: &mq.ServerMsg{ + UserId: player.PlayerId, + MatchGameId: gameId, + MatchRoomId: roomId, + }, + }) + } + g.SendSucc(cmd.BackMyWorldRsp, player, &proto.BackMyWorldRsp{}) } @@ -163,6 +217,15 @@ func (g *Game) SceneKickPlayerReq(player *model.Player, payloadMsg pb.Message) { func (g *Game) JoinOtherWorld(player *model.Player, hostPlayer *model.Player) { hostWorld := WORLD_MANAGER.GetWorldById(hostPlayer.WorldId) if hostPlayer.SceneLoadState == model.SceneEnterDone { + // 触发事件 + if PLUGIN_MANAGER.TriggerEvent(PluginEventIdJoinOtherWorld, &PluginEventJoinOtherWorld{ + PluginEvent: NewPluginEvent(), + Player: player, + HostPlayer: hostPlayer, + }) { + return + } + player.SceneJump = true player.SceneId = hostPlayer.SceneId player.SceneLoadState = model.SceneNone @@ -171,6 +234,20 @@ func (g *Game) JoinOtherWorld(player *model.Player, hostPlayer *model.Player) { player.Rot.X, player.Rot.Y, player.Rot.Z = hostPlayer.Rot.X, hostPlayer.Rot.Y, hostPlayer.Rot.Z g.WorldAddPlayer(hostWorld, player) + // 通知匹配服玩家加入游戏ai的世界 + exist, gameId, roomId := AI_MANAGER.GetAiUidGameId(hostPlayer.PlayerId) + if exist && player.MultiServerAppId != "" { + MESSAGE_QUEUE.SendToMulti(player.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchPlayerJoinGameNotify, + ServerMsg: &mq.ServerMsg{ + UserId: player.PlayerId, + MatchGameId: gameId, + MatchRoomId: roomId, + }, + }) + } + playerEnterSceneNotify := g.PacketPlayerEnterSceneNotifyMp( player, hostPlayer, diff --git a/gs/game/player_social.go b/gs/game/player_social.go index 733cc64b..e9d1d5eb 100644 --- a/gs/game/player_social.go +++ b/gs/game/player_social.go @@ -1,7 +1,6 @@ package game import ( - "fmt" "regexp" "time" "unicode/utf8" @@ -371,67 +370,54 @@ func (g *Game) DealAddFriendReq(player *model.Player, payloadMsg pb.Message) { } } -func (g *Game) GetOnlinePlayerListReq(player *model.Player, payloadMsg pb.Message) { - count := 0 - rsp := &proto.GetOnlinePlayerListRsp{ - PlayerInfoList: make([]*proto.OnlinePlayerInfo, 0), +// ServerGetMatchGameListRsp 获取匹配游戏列表响应 +func (g *Game) ServerGetMatchGameListRsp(userId uint32, matchGameInfoList []*mq.MatchGameInfo) { + player := USER_MANAGER.GetOnlineUser(userId) + if player == nil { + logger.Error("player is nil, uid: %v", userId) + return } - // 最先添加全服ai玩家 - aiUidList := USER_MANAGER.GetAllRemoteAiUidList() - aiUidList = append(aiUidList, g.GetAi().PlayerId) - for _, aiUid := range aiUidList { - aiGsId := aiUid - AiBaseUid - roomNumber := aiGsId - 1 - startMinute := roomNumber % 6 * 10 - name := fmt.Sprintf("房间:%v", roomNumber) - sign := fmt.Sprintf("开启时间:%02d:%02d。", time.Now().Hour(), startMinute) - rsp.PlayerInfoList = append(rsp.PlayerInfoList, &proto.OnlinePlayerInfo{ - Uid: aiUid, - Nickname: name, + playerInfoList := make([]*proto.OnlinePlayerInfo, 0, len(matchGameInfoList)) + // 匹配游戏信息 + for _, info := range matchGameInfoList { + playerInfoList = append(playerInfoList, &proto.OnlinePlayerInfo{ + Uid: info.GameId, + Nickname: info.AiInfo.Name, PlayerLevel: 1, - AvatarId: 10000007, + AvatarId: info.AiInfo.HeadImage, MpSettingType: proto.MpSettingType_MP_SETTING_ENTER_AFTER_APPLY, - NameCardId: 210001, - Signature: sign, - ProfilePicture: &proto.ProfilePicture{AvatarId: 10000007}, - CurPlayerNumInWorld: 1, + NameCardId: info.AiInfo.NameCard, + Signature: info.AiInfo.Sign, + ProfilePicture: &proto.ProfilePicture{AvatarId: info.AiInfo.HeadImage}, + CurPlayerNumInWorld: info.PlayerCount, }) - count++ - } - onlinePlayerList := make([]*model.Player, 0) - // 优先获取本地的在线玩家 - for _, onlinePlayer := range USER_MANAGER.GetAllOnlineUserList() { - if onlinePlayer.PlayerId < PlayerBaseUid || onlinePlayer.PlayerId > MaxPlayerBaseUid { - continue - } - if onlinePlayer.PlayerId == player.PlayerId { - continue - } - onlinePlayerList = append(onlinePlayerList, onlinePlayer) - count++ - if count >= 50 { - break - } - } - if count < 50 { - // 本地不够时获取远程的在线玩家 - for _, onlinePlayer := range USER_MANAGER.GetRemoteOnlineUserList(50 - count) { - if onlinePlayer.PlayerId == player.PlayerId { - continue - } - onlinePlayerList = append(onlinePlayerList, onlinePlayer) - count++ - if count >= 50 { - break - } - } } + // 添加本服其他的玩家 + playerInfoList = append(playerInfoList, g.GetOnlinePlayerInfoList(player, len(playerInfoList))...) - for _, onlinePlayer := range onlinePlayerList { - onlinePlayerInfo := g.PacketOnlinePlayerInfo(onlinePlayer) - rsp.PlayerInfoList = append(rsp.PlayerInfoList, onlinePlayerInfo) + getOnlinePlayerListRsp := &proto.GetOnlinePlayerListRsp{ + PlayerInfoList: playerInfoList, } - g.SendMsg(cmd.GetOnlinePlayerListRsp, player.PlayerId, player.ClientSeq, rsp) + g.SendMsg(cmd.GetOnlinePlayerListRsp, player.PlayerId, player.ClientSeq, getOnlinePlayerListRsp) +} + +// GetOnlinePlayerListReq 获取在线玩家列表请求 +func (g *Game) GetOnlinePlayerListReq(player *model.Player, payloadMsg pb.Message) { + // 发送到匹配服异步获取游戏列表 + if player.MultiServerAppId != "" { + MESSAGE_QUEUE.SendToMulti(player.MultiServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerGetMatchGameListReq, + ServerMsg: &mq.ServerMsg{ + UserId: player.PlayerId, + }, + }) + return + } + getOnlinePlayerListRsp := &proto.GetOnlinePlayerListRsp{ + PlayerInfoList: g.GetOnlinePlayerInfoList(player, 0), + } + g.SendMsg(cmd.GetOnlinePlayerListRsp, player.PlayerId, player.ClientSeq, getOnlinePlayerListRsp) } func (g *Game) GetOnlinePlayerInfoReq(player *model.Player, payloadMsg pb.Message) { @@ -505,6 +491,53 @@ func (g *Game) ServerAddFriendNotify(addFriendInfo *mq.AddFriendInfo) { /************************************************** 打包封装 **************************************************/ +// GetOnlinePlayerInfoList 获取在线玩家信息列表 +func (g *Game) GetOnlinePlayerInfoList(player *model.Player, count int) []*proto.OnlinePlayerInfo { + onlinePlayerList := make([]*model.Player, 0) + + addOnlinePlayer := func(onlinePlayer *model.Player) { + if onlinePlayer.PlayerId < PlayerBaseUid || onlinePlayer.PlayerId > MaxPlayerBaseUid { + return + } + if onlinePlayer.PlayerId == player.PlayerId { + return + } + // 如果在其他人的世界则不添加 + world := WORLD_MANAGER.GetWorldById(onlinePlayer.WorldId) + if world == nil { + return + } + if world.GetOwner().PlayerId != onlinePlayer.PlayerId { + return + } + onlinePlayerList = append(onlinePlayerList, onlinePlayer) + count++ + } + + // 优先获取本地的在线玩家 + for _, onlinePlayer := range USER_MANAGER.GetAllOnlineUserList() { + addOnlinePlayer(onlinePlayer) + if count >= 50 { + break + } + } + if count < 50 { + // 本地不够时获取远程的在线玩家 + for _, onlinePlayer := range USER_MANAGER.GetRemoteOnlineUserList(50 - count) { + addOnlinePlayer(onlinePlayer) + if count >= 50 { + break + } + } + } + playerInfoList := make([]*proto.OnlinePlayerInfo, 0, len(onlinePlayerList)) + for _, onlinePlayer := range onlinePlayerList { + onlinePlayerInfo := g.PacketOnlinePlayerInfo(onlinePlayer) + playerInfoList = append(playerInfoList, onlinePlayerInfo) + } + return playerInfoList +} + func (g *Game) PacketOnlinePlayerInfo(player *model.Player) *proto.OnlinePlayerInfo { world := WORLD_MANAGER.GetWorldById(player.WorldId) worldPlayerNum := uint32(1) diff --git a/gs/game/player_stamina.go b/gs/game/player_stamina.go index 9a27aa2a..8e567264 100644 --- a/gs/game/player_stamina.go +++ b/gs/game/player_stamina.go @@ -379,7 +379,7 @@ func (g *Game) HandleDrown(player *model.Player, stamina uint32) { if player.StaminaInfo.State != proto.MotionState_MOTION_SWIM_MOVE && player.StaminaInfo.State != proto.MotionState_MOTION_SWIM_DASH { return } - logger.Debug("player drown, curStamina: %v, state: %v", stamina, player.StaminaInfo.State) + logger.Debug("player drown, curStamina: %v, gameState: %v", stamina, player.StaminaInfo.State) // 设置角色为死亡 world := WORLD_MANAGER.GetWorldById(player.WorldId) if world == nil { diff --git a/gs/game/player_world.go b/gs/game/player_world.go index 8e01ed1e..c3138306 100644 --- a/gs/game/player_world.go +++ b/gs/game/player_world.go @@ -677,10 +677,6 @@ func (g *Game) TeleportPlayer( return } - if WORLD_MANAGER.IsAiWorld(world) && player.CmdPerm != uint8(CommandPermGM) { - return - } - newSceneId := sceneId oldSceneId := player.SceneId oldPos := &model.Vector{X: player.Pos.X, Y: player.Pos.Y, Z: player.Pos.Z} diff --git a/gs/model/db_quest.go b/gs/model/db_quest.go index 44f5b3c7..22d6311a 100644 --- a/gs/model/db_quest.go +++ b/gs/model/db_quest.go @@ -87,7 +87,7 @@ func (q *DbQuest) StartQuest(questId uint32) { func (q *DbQuest) DeleteQuest(questId uint32) { _, exist := q.QuestMap[questId] if !exist { - logger.Error("quest is not exist, questId: %v", questId) + logger.Error("quest not exist, questId: %v", questId) return } delete(q.QuestMap, questId) diff --git a/multi/app/app.go b/multi/app/app.go index 55cc00fe..a423484c 100644 --- a/multi/app/app.go +++ b/multi/app/app.go @@ -69,7 +69,7 @@ func Run(ctx context.Context, configFile string) error { messageQueue := mq.NewMessageQueue(api.MULTI, APPID, discoveryClient) defer messageQueue.Close() - _ = handle.NewHandle(messageQueue) + _ = handle.NewHandle(messageQueue, discoveryClient) c := make(chan os.Signal, 1) signal.Notify(c, syscall.SIGHUP, syscall.SIGQUIT, syscall.SIGTERM, syscall.SIGINT) diff --git a/multi/handle/handle.go b/multi/handle/handle.go index 0fc1030b..36efd21b 100644 --- a/multi/handle/handle.go +++ b/multi/handle/handle.go @@ -1,27 +1,37 @@ package handle import ( + "context" "hk4e/common/mq" + "hk4e/common/rpc" "hk4e/gate/kcp" "hk4e/node/api" "hk4e/pkg/logger" "hk4e/protocol/cmd" + "time" pb "google.golang.org/protobuf/proto" ) type Handle struct { - messageQueue *mq.MessageQueue - playerAcCtxMap map[uint32]*AnticheatContext - worldStatic *WorldStatic + messageQueue *mq.MessageQueue + discoveryClient *rpc.DiscoveryClient + playerAcCtxMap map[uint32]*AnticheatContext + worldStatic *WorldStatic + match *Match + minLoadGsServerAppId string } -func NewHandle(messageQueue *mq.MessageQueue) (r *Handle) { +func NewHandle(messageQueue *mq.MessageQueue, discoveryClient *rpc.DiscoveryClient) (r *Handle) { r = new(Handle) r.messageQueue = messageQueue + r.discoveryClient = discoveryClient r.playerAcCtxMap = make(map[uint32]*AnticheatContext) r.worldStatic = NewWorldStatic() r.worldStatic.InitTerrain() + r.syncMinLoadServerAppid() + go r.autoSyncMinLoadServerAppid() + r.match = NewMatch(r) go r.run() return r } @@ -59,11 +69,48 @@ func (h *Handle) run() { } else { h.DelPlayerAcCtx(serverMsg.UserId) } + case mq.ServerGetMatchGameListReq: + h.ServerGetMatchGameListReq(serverMsg.UserId, netMsg.OriginServerAppId) + case mq.ServerGetMatchRoomAiUidReq: + h.ServerGetMatchRoomAiUidReq(serverMsg.UserId, serverMsg.MatchGameId, netMsg.OriginServerAppId) + case mq.ServerMatchCreateAiRsp: + h.ServerMatchCreateAiRsp(serverMsg.MatchGameId, serverMsg.MatchRoomId, serverMsg.MatchAiUid) + case mq.ServerMatchPlayerJoinGameNotify: + h.ServerMatchPlayerJoinGameNotify(serverMsg.UserId, serverMsg.MatchGameId, serverMsg.MatchRoomId) + case mq.ServerMatchPlayerExitGameNotify: + h.ServerMatchPlayerExitGameNotify(serverMsg.UserId, serverMsg.MatchGameId, serverMsg.MatchRoomId) + case mq.ServerMatchGameStartNotify: + h.ServerMatchGameStartNotify(serverMsg.MatchGameId, serverMsg.MatchRoomId) + case mq.ServerMatchGameStopNotify: + h.ServerMatchGameStopNotify(serverMsg.MatchGameId, serverMsg.MatchRoomId) } } } } +func (h *Handle) syncMinLoadServerAppid() { + gsServerAppId, err := h.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{ + ServerType: api.GS, + }) + if err != nil { + logger.Error("get gs server appid error: %v", err) + h.minLoadGsServerAppId = "" + } else { + h.minLoadGsServerAppId = gsServerAppId.AppId + } +} + +func (h *Handle) autoSyncMinLoadServerAppid() { + ticker := time.NewTicker(time.Second * 15) + for { + <-ticker.C + h.syncMinLoadServerAppid() + + // 同步完负载最小的gs后重新尝试请求创建ai + h.match.HandleWaitCreateAiRoom() + } +} + func (h *Handle) KickPlayer(userId uint32, gateAppId string) { if !KickCheatPlayer { return diff --git a/multi/handle/match.go b/multi/handle/match.go new file mode 100644 index 00000000..c3a4f3d0 --- /dev/null +++ b/multi/handle/match.go @@ -0,0 +1,351 @@ +package handle + +import ( + "fmt" + "hk4e/common/constant" + "hk4e/common/mq" + "hk4e/pkg/logger" +) + +// InitGame 初始化游戏 +func (m *Match) InitGame() { + m.CreateGame(constant.MATCH_GAME_TYPE_PUBG, 100, "PUBG游戏", "在原的世界中体验大逃杀吧~", 10000007, 210001) +} + +// MatchPhase 阶段 +type MatchPhase uint8 + +const ( + MatchPhaseWait = MatchPhase(iota) // 等待游戏开始 + MatchPhaseStart // 游戏开始 + MatchPhaseStop // 游戏结束 +) + +// MatchRoom 匹配房间 +type MatchRoom struct { + RoomId uint32 // 房间id + AiUid uint32 // 房间世界对应ai的uid + PlayerUidList []uint32 // 玩家uid列表 + Phase MatchPhase // 游戏阶段 +} + +// MatchGame 匹配游戏 +type MatchGame struct { + GameId uint32 // 游戏id + GameType uint8 // 游戏类型 + MaxPlayerCount uint16 // 最大玩家数量 + Name string // 游戏名 + Sign string // 描述签名 + HeadImage uint32 // 头像id + NameCard uint32 // 名片id + RoomMap map[uint32]*MatchRoom // 房间集合 TODO gs关闭清除无用room + roomIdCounter uint32 // 房间id计数器 + WaitCreateAiRoomList []uint32 // 等待创建ai的房间请求列表 +} + +// Match 匹配功能 +type Match struct { + GameMap map[uint32]*MatchGame // 游戏集合 + gameIdCounter uint32 // 游戏id计数器 + + handle *Handle +} + +func NewMatch(handle *Handle) *Match { + m := new(Match) + + m.handle = handle + m.GameMap = make(map[uint32]*MatchGame) + + m.InitGame() + return m +} + +// CreateGame 创建游戏 +func (m *Match) CreateGame(gameType uint8, maxPlayerCount uint16, name, sign string, headImage, nameCard uint32) { + m.gameIdCounter++ + m.GameMap[m.gameIdCounter] = &MatchGame{ + GameId: m.gameIdCounter, + GameType: gameType, + MaxPlayerCount: maxPlayerCount, + Name: name, + Sign: sign, + HeadImage: headImage, + NameCard: nameCard, + RoomMap: make(map[uint32]*MatchRoom), + WaitCreateAiRoomList: make([]uint32, 0), + } + // 创建游戏后添加默认房间 + m.AddRoom(m.gameIdCounter) +} + +// RoomCreateAi 房间请求gs创建ai +func (m *Match) RoomCreateAi(gameId uint32, roomId uint32) { + game, exist := m.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", gameId) + return + } + // 请求负载最低的gs创建ai + m.handle.messageQueue.SendToGs(m.handle.minLoadGsServerAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerMatchCreateAiReq, + ServerMsg: &mq.ServerMsg{ + MatchGameId: game.GameId, + MatchRoomId: roomId, + MatchGameType: game.GameType, + MatchAiInfo: &mq.AiInfo{ + Name: game.Name, + Sign: game.Sign, + HeadImage: game.HeadImage, + NameCard: game.NameCard, + }, + }, + }) + // 添加到等待列表 + for _, id := range game.WaitCreateAiRoomList { + if id == roomId { + return + } + } + game.WaitCreateAiRoomList = append(game.WaitCreateAiRoomList, roomId) +} + +// CreateRoom 创建房间 +func (m *Match) CreateRoom(gameId uint32, oldRoomId uint32) { + game, exist := m.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", gameId) + return + } + // 没有新房间则直接创建 + if game.roomIdCounter != oldRoomId { + // 如果已有新房间校验人数 + room, exist := game.RoomMap[game.roomIdCounter] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, game.roomIdCounter) + return + } + // 人数未满不创建 + if len(room.PlayerUidList) < int(game.MaxPlayerCount) { + return + } + } + m.AddRoom(gameId) +} + +// AddRoom 添加房间 +func (m *Match) AddRoom(gameId uint32) { + game, exist := m.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", gameId) + return + } + game.roomIdCounter++ + game.RoomMap[game.roomIdCounter] = &MatchRoom{ + RoomId: game.roomIdCounter, + AiUid: 0, // 请求负载最低的gs创建ai + PlayerUidList: make([]uint32, 0), + Phase: MatchPhaseWait, + } + // 请求gs创建ai + m.RoomCreateAi(game.GameId, game.roomIdCounter) +} + +// HandleWaitCreateAiRoom 同步完负载最小的gs后请求创建ai +func (m *Match) HandleWaitCreateAiRoom() { + for _, game := range m.GameMap { + for _, roomId := range game.WaitCreateAiRoomList { + m.RoomCreateAi(game.GameId, roomId) + } + } +} + +// ServerGetMatchGameListReq 获取游戏列表请求 +func (h *Handle) ServerGetMatchGameListReq(userId uint32, gsAppId string) { + matchGameList := make([]*mq.MatchGameInfo, 0) + // 遍历游戏列表 + for _, game := range h.match.GameMap { + curRoom, exist := game.RoomMap[game.roomIdCounter] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, game.roomIdCounter) + return + } + // 校验房间是否满人 满人创建新房间 + if len(curRoom.PlayerUidList) >= int(game.MaxPlayerCount) { + h.match.CreateRoom(game.GameId, curRoom.RoomId) + } + matchGameList = append(matchGameList, &mq.MatchGameInfo{ + GameId: game.GameId, + AiInfo: &mq.AiInfo{ + Name: game.Name + " " + fmt.Sprintf("[ %v / %v ]", len(curRoom.PlayerUidList), game.MaxPlayerCount), // 添加玩家人数显示 + Sign: game.Sign, + HeadImage: game.HeadImage, + NameCard: game.NameCard, + }, + PlayerCount: uint32(len(curRoom.PlayerUidList)), + }) + } + h.messageQueue.SendToGs(gsAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerGetMatchGameListRsp, + ServerMsg: &mq.ServerMsg{ + UserId: userId, + MatchGameList: matchGameList, + }, + }) +} + +// ServerGetMatchRoomAiUidReq 获取房间ai的uid请求 +func (h *Handle) ServerGetMatchRoomAiUidReq(userId, gameId uint32, gsAppId string) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取现行房间 + curRoom, exist := game.RoomMap[game.roomIdCounter] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, game.roomIdCounter) + return + } + aiUid := curRoom.AiUid + // 确保房间处于等待状态 + if curRoom.Phase != MatchPhaseWait { + aiUid = 0 + } + // 确保房间没有满人 + if len(curRoom.PlayerUidList) >= int(game.MaxPlayerCount) { + aiUid = 0 + } + h.messageQueue.SendToGs(gsAppId, &mq.NetMsg{ + MsgType: mq.MsgTypeServer, + EventId: mq.ServerGetMatchRoomAiUidRsp, + ServerMsg: &mq.ServerMsg{ + UserId: userId, + MatchAiUid: aiUid, + }, + }) +} + +// ServerMatchCreateAiRsp 创建ai响应 +func (h *Handle) ServerMatchCreateAiRsp(gameId, roomId, aiUid uint32) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取房间 + room, exist := game.RoomMap[roomId] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, roomId) + return + } + // 如果不为0代表已经设置过了 + if room.AiUid != 0 { + logger.Error("ai uid has been set, aiUid: %v", room.AiUid) + return + } + // 设置房间ai的uid + room.AiUid = aiUid + // 清除等待 + for i, u := range game.WaitCreateAiRoomList { + if u == roomId { + game.WaitCreateAiRoomList = append(game.WaitCreateAiRoomList[:i], game.WaitCreateAiRoomList[i+1:]...) + break + } + } +} + +// ServerMatchPlayerJoinGameNotify 玩家加入游戏通知 +func (h *Handle) ServerMatchPlayerJoinGameNotify(userId, gameId, roomId uint32) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取房间 + room, exist := game.RoomMap[roomId] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, roomId) + return + } + // 校验玩家是否已加入 + for _, uid := range room.PlayerUidList { + if uid == userId { + logger.Error("player has been join, uid: %v", userId) + return + } + } + // 添加玩家列表 + room.PlayerUidList = append(room.PlayerUidList, userId) +} + +// ServerMatchPlayerExitGameNotify 玩家离开游戏通知 +func (h *Handle) ServerMatchPlayerExitGameNotify(userId, gameId, roomId uint32) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取房间 + room, exist := game.RoomMap[roomId] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, roomId) + return + } + // 清理玩家uid + for i, uid := range room.PlayerUidList { + if uid == userId { + room.PlayerUidList = append(room.PlayerUidList[:i], room.PlayerUidList[i+1:]...) + } + } +} + +// ServerMatchGameStartNotify 游戏开始通知 +func (h *Handle) ServerMatchGameStartNotify(gameId, roomId uint32) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取房间 + room, exist := game.RoomMap[roomId] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, roomId) + return + } + // 确保房间处于等待阶段 + if room.Phase != MatchPhaseWait { + logger.Error("room phase not wait, gameId: %v, roomId: %v, phase: %v", game.GameId, roomId, room.Phase) + return + } + // 游戏创建新房间 + h.match.CreateRoom(gameId, roomId) + // 切换阶段 + room.Phase = MatchPhaseStart +} + +// ServerMatchGameStopNotify 游戏结束通知 +func (h *Handle) ServerMatchGameStopNotify(gameId, roomId uint32) { + game, exist := h.match.GameMap[gameId] + if !exist { + logger.Error("game not exist, gameId: %v", game.GameId) + return + } + // 获取房间 + room, exist := game.RoomMap[roomId] + if !exist { + logger.Error("room not exist, gameId: %v, roomId: %v", game.GameId, roomId) + return + } + // 确保房间处于开始阶段 + if room.Phase != MatchPhaseStart { + logger.Error("room phase not start, gameId: %v, roomId: %v, phase: %v", game.GameId, roomId, room.Phase) + return + } + // 切换阶段 + room.Phase = MatchPhaseStop + // 清除房间 + delete(game.RoomMap, roomId) +}