From 1d8aff9554ce2600b4ff9632cfb594fc6af66076 Mon Sep 17 00:00:00 2001 From: flswld Date: Mon, 30 Oct 2023 00:28:17 +0800 Subject: [PATCH] =?UTF-8?q?Revert=20"=E6=B7=BB=E5=8A=A0=E5=8C=B9=E9=85=8D?= =?UTF-8?q?=E6=9C=8D=E3=80=81AI=E7=AE=A1=E7=90=86=E5=99=A8=E3=80=81?= =?UTF-8?q?=E6=B8=B8=E6=88=8F=E6=88=BF=E9=97=B4=E5=8A=A8=E6=80=81=E6=89=A9?= =?UTF-8?q?=E5=AE=B9=EF=BC=8C=E4=BF=AE=E6=94=B9PUBG=E6=B8=B8=E6=88=8F?= =?UTF-8?q?=E6=B5=81=E7=A8=8B=EF=BC=8C=E4=BF=AE=E5=A4=8Dbug"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit f1abc92681ddabcda955a2f778ca04ea63177453. --- common/constant/match_game_type.go | 6 - common/mq/net_msg.go | 31 -- gs/game/audio_video.go | 2 +- gs/game/game.go | 37 +- gs/game/game_ai_manager.go | 138 ------- gs/game/game_command_gm.go | 87 +++-- gs/game/game_plugin_manager.go | 112 +----- gs/game/game_plugin_pubg.go | 562 ++++++++--------------------- gs/game/game_route_manager.go | 8 +- gs/game/game_tick_manager.go | 54 ++- gs/game/game_user_manager.go | 27 +- gs/game/game_world_manager.go | 14 +- gs/game/player_chat.go | 7 - gs/game/player_fight_sync.go | 55 ++- gs/game/player_multiplayer.go | 77 ---- gs/game/player_social.go | 149 +++----- gs/game/player_stamina.go | 2 +- gs/game/player_world.go | 4 + gs/model/db_quest.go | 2 +- multi/app/app.go | 2 +- multi/handle/handle.go | 55 +-- multi/handle/match.go | 351 ------------------ 22 files changed, 401 insertions(+), 1381 deletions(-) delete mode 100644 common/constant/match_game_type.go delete mode 100644 gs/game/game_ai_manager.go delete mode 100644 multi/handle/match.go diff --git a/common/constant/match_game_type.go b/common/constant/match_game_type.go deleted file mode 100644 index 3f90ac6a..00000000 --- a/common/constant/match_game_type.go +++ /dev/null @@ -1,6 +0,0 @@ -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 08be94b0..228ca234 100644 --- a/common/mq/net_msg.go +++ b/common/mq/net_msg.go @@ -61,16 +61,6 @@ const ( ServerStopNotify // 停服通知 ServerDispatchCancelNotify // 服务器取消调度通知 ServerGmCmdNotify // 服务器GM指令执行通知 - ServerGetMatchGameListReq // 服务器匹配服游戏列表请求 - ServerGetMatchGameListRsp // 服务器匹配服游戏列表响应 - ServerGetMatchRoomAiUidReq // 服务器匹配服房间ai的uid请求 - ServerGetMatchRoomAiUidRsp // 服务器匹配服房间ai的uid响应 - ServerMatchCreateAiReq // 服务器匹配服创建ai请求 - ServerMatchCreateAiRsp // 服务器匹配服创建ai响应 - ServerMatchPlayerJoinGameNotify // 服务器匹配服玩家加入游戏通知 - ServerMatchPlayerExitGameNotify // 服务器匹配服玩家离开游戏通知 - ServerMatchGameStartNotify // 服务器匹配服游戏开始通知 - ServerMatchGameStopNotify // 服务器匹配服游戏结束通知 ) type ServerMsg struct { @@ -86,12 +76,6 @@ type ServerMsg struct { AppVersion string GmCmdFuncName string GmCmdParamList []string - MatchGameList []*MatchGameInfo - MatchGameId uint32 - MatchRoomId uint32 - MatchAiUid uint32 - MatchAiInfo *AiInfo - MatchGameType uint8 } type OriginInfo struct { @@ -143,18 +127,3 @@ 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 efb16bca..0c76d8b7 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.GetWorldById(GAME.ai.WorldId) + world := WORLD_MANAGER.GetAiWorld() 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 659292a7..5836c33b 100644 --- a/gs/game/game.go +++ b/gs/game/game.go @@ -37,7 +37,6 @@ 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 // 当前在线玩家数 @@ -74,12 +73,13 @@ 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 + // 创建本服的Ai世界 + uid := AiBaseUid + gsId name := AiName sign := AiSign + " GS:" + strconv.Itoa(int(gsId)) - r.ai = AI_MANAGER.CreateAi(name, sign, 10000007, 210001, "") + r.ai = r.CreateRobot(uid, name, sign) + WORLD_MANAGER.InitAiWorld(r.ai) COMMAND_MANAGER.SetSystem(r.ai) // 初始化插件 最后再调用以免插件需要访问其他模块导致出错 PLUGIN_MANAGER.InitPlugin() @@ -102,6 +102,35 @@ 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 deleted file mode 100644 index 7135cd4a..00000000 --- a/gs/game/game_ai_manager.go +++ /dev/null @@ -1,138 +0,0 @@ -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 ebd9dbb1..e38faec2 100644 --- a/gs/game/game_command_gm.go +++ b/gs/game/game_command_gm.go @@ -30,17 +30,6 @@ 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, @@ -554,7 +543,10 @@ func (g *GMCmd) AvUpdateFrame(fileDataBase64 string, rgb bool, posX, posY, posZ UpdateFrame(fileData, basePos, rgb) } -func (g *GMCmd) CreateRobotInAiWorld(aiUid uint32, name string, avatarId uint32, posX, posY, posZ float64) { +func (g *GMCmd) CreateRobotInAiWorld(uid uint32, name string, avatarId uint32, posX, posY, posZ float64) { + if uid == 0 { + return + } if name == "" { name = random.GetRandomStr(8) } @@ -564,14 +556,9 @@ func (g *GMCmd) CreateRobotInAiWorld(aiUid uint32, name string, avatarId uint32, break } } - 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) + aiWorld := WORLD_MANAGER.GetAiWorld() + robot := GAME.CreateRobot(uid, name, name) + GAME.AddPlayerAvatar(uid, avatarId) dbAvatar := robot.GetDbAvatar() GAME.SetUpAvatarTeamReq(robot, &proto.SetUpAvatarTeamReq{ TeamId: 1, @@ -582,23 +569,23 @@ func (g *GMCmd) CreateRobotInAiWorld(aiUid uint32, name string, avatarId uint32, AvatarId: avatarId, }) GAME.JoinPlayerSceneReq(robot, &proto.JoinPlayerSceneReq{ - TargetUid: world.GetOwner().PlayerId, + TargetUid: aiWorld.GetOwner().PlayerId, }) GAME.EnterSceneReadyReq(robot, &proto.EnterSceneReadyReq{ - EnterSceneToken: world.GetEnterSceneToken(), + EnterSceneToken: aiWorld.GetEnterSceneToken(), }) GAME.SceneInitFinishReq(robot, &proto.SceneInitFinishReq{ - EnterSceneToken: world.GetEnterSceneToken(), + EnterSceneToken: aiWorld.GetEnterSceneToken(), }) GAME.EnterSceneDoneReq(robot, &proto.EnterSceneDoneReq{ - EnterSceneToken: world.GetEnterSceneToken(), + EnterSceneToken: aiWorld.GetEnterSceneToken(), }) GAME.PostEnterSceneReq(robot, &proto.PostEnterSceneReq{ - EnterSceneToken: world.GetEnterSceneToken(), + EnterSceneToken: aiWorld.GetEnterSceneToken(), }) - activeAvatarId := world.GetPlayerActiveAvatarId(robot) + activeAvatarId := aiWorld.GetPlayerActiveAvatarId(robot) entityMoveInfo := &proto.EntityMoveInfo{ - EntityId: world.GetPlayerWorldAvatarEntityId(robot, activeAvatarId), + EntityId: aiWorld.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)}, @@ -651,37 +638,45 @@ func (g *GMCmd) SendMsgToPlayer(cmdName string, userId uint32, msgJson string) { GAME.SendMsg(cmdId, userId, 0, msg) } -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) +func (g *GMCmd) StartPubg(v bool) { + iPlugin, err := PLUGIN_MANAGER.GetPlugin(&PluginPubg{}) + if err != nil { + logger.Error("get plugin pubg error: %v", err) return } - world := WORLD_MANAGER.GetWorldById(ai.WorldId) + 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() engine := world.GetBulletPhysicsEngine() engine.SetPhysicsEngineParam(pathTracing, acc, drag, pao, is, ayo) } -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) +func (g *GMCmd) ShowAvatarCollider(v bool) { + world := WORLD_MANAGER.GetAiWorld() engine := world.GetBulletPhysicsEngine() engine.ShowAvatarCollider() } -func (g *GMCmd) AiWorldAoiDebug(aiUid uint32) { - ai := USER_MANAGER.GetOnlineUser(aiUid) - if ai == nil { - logger.Error("ai is nil, uid: %v", aiUid) +func (g *GMCmd) AiWorldAoiDebug(v bool) { + aiWorld := WORLD_MANAGER.GetAiWorld() + if aiWorld == nil { return } - world := WORLD_MANAGER.GetWorldById(ai.WorldId) - scene := world.GetSceneById(world.GetOwner().SceneId) - aiWorldAoi := world.GetAiWorldAoi() + scene := aiWorld.GetSceneById(aiWorld.GetOwner().SceneId) + aiWorldAoi := aiWorld.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 81368e5f..02ec5b23 100644 --- a/gs/game/game_plugin_manager.go +++ b/gs/game/game_plugin_manager.go @@ -3,8 +3,6 @@ package game import ( "errors" "fmt" - "hk4e/common/constant" - "hk4e/common/mq" "reflect" "sort" @@ -37,11 +35,6 @@ const ( PluginEventIdAvatarDieAnimationEnd PluginEventIdGadgetInteract PluginEventIdPostEnterScene - PluginEventIdMatchCreateAi - PluginEventIdJoinOtherWorld - PluginEventIdEvtDoSkillSucc - PluginEventIdBackMyWorld - PluginEventIdUserOffline ) // PluginEventKillAvatar 角色被杀死 @@ -80,43 +73,6 @@ 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 插件事件接口 @@ -175,17 +131,7 @@ type PluginGlobalTick uint8 const ( PluginGlobalTickSecond = PluginGlobalTick(iota) - PluginGlobalTick50MilliSecond - PluginGlobalTick100MilliSecond - PluginGlobalTick200MilliSecond - PluginGlobalTick5Second - PluginGlobalTick10Second - PluginGlobalTickMinute - PluginGlobalTickHour PluginGlobalTickMinuteChange - PluginGlobalTickHourChange - PluginGlobalTickDayChange - PluginGlobalTickMonthChange ) // PluginUserTimerFunc 用户timer处理函数 @@ -193,18 +139,18 @@ type PluginUserTimerFunc func(player *model.Player, data []any) // Plugin 插件结构 type Plugin struct { - isEnable bool // 是否启用 - eventMap map[PluginEventId][]*PluginEventInfo // 事件集合 - globalTickMap map[PluginGlobalTick][]func(now int64) // 全局tick集合 - userTimerMap map[uint64]PluginUserTimerFunc // 用户timer集合 - commandControllerList []*CommandController // 命令控制器列表 + isEnable bool // 是否启用 + eventMap map[PluginEventId][]*PluginEventInfo // 事件集合 + globalTickMap map[PluginGlobalTick][]func() // 全局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(now int64)), + globalTickMap: make(map[PluginGlobalTick][]func()), userTimerMap: make(map[uint64]PluginUserTimerFunc), commandControllerList: make([]*CommandController, 0), } @@ -242,11 +188,11 @@ func (p *Plugin) ListenEvent(eventId PluginEventId, priority PluginEventPriority } // AddGlobalTick 添加全局tick -func (p *Plugin) AddGlobalTick(tick PluginGlobalTick, tickFuncList ...func(now int64)) { +func (p *Plugin) AddGlobalTick(tick PluginGlobalTick, tickFuncList ...func()) { for _, tickFunc := range tickFuncList { _, exist := p.globalTickMap[tick] if !exist { - p.globalTickMap[tick] = make([]func(now int64), 0) + p.globalTickMap[tick] = make([]func(), 0) } p.globalTickMap[tick] = append(p.globalTickMap[tick], tickFunc) } @@ -267,44 +213,6 @@ 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计数器 @@ -428,7 +336,7 @@ func (p *PluginManager) TriggerEvent(eventId PluginEventId, event IPluginEvent) } // HandleGlobalTick 处理全局tick -func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick, now int64) { +func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick) { for _, iPlugin := range p.pluginMap { plugin := iPlugin.GetPlugin() // 插件未启用则跳过 @@ -441,7 +349,7 @@ func (p *PluginManager) HandleGlobalTick(tick PluginGlobalTick, now int64) { continue } for _, tickFunc := range tickFuncList { - tickFunc(now) + tickFunc() } } } diff --git a/gs/game/game_plugin_pubg.go b/gs/game/game_plugin_pubg.go index 07c811e8..15a84c2e 100644 --- a/gs/game/game_plugin_pubg.go +++ b/gs/game/game_plugin_pubg.go @@ -2,6 +2,7 @@ package game import ( "encoding/base64" + "fmt" "math" "time" @@ -17,18 +18,7 @@ import ( ) const ( - 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_WAIT = -1 PUBG_PHASE_START = 0 PUBG_PHASE_II = 2 PUBG_PHASE_END = 16 @@ -49,42 +39,40 @@ const ( PUBG_NORMAL_ATTACK_ATK_RATIO = 5.0 ) -// PubgGame pubg游戏 -type PubgGame struct { - gameTick uint64 // 游戏tick - gameState uint8 // 游戏状态 - waitTick uint64 // 等待tick - stopTick uint64 // 等待tick - phase uint16 // 阶段 - ai *model.Player // ai +// PluginPubg pubg游戏插件 +type PluginPubg struct { + *Plugin + seq uint32 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(), - pubgGameMap: make(map[uint32]*PubgGame), + 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), } return p } @@ -97,146 +85,35 @@ 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(PluginGlobalTick100MilliSecond, p.GlobalTickPubgHit) + p.AddGlobalTick(PluginGlobalTickMinuteChange, p.GlobalTickMinuteChange) // 注册命令 - // 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 - // 获取玩家所在的pubg游戏 - pubgGame := p.GetPlayerInPubgGame(player) - if pubgGame == nil { - return - } // 确保游戏开启 - if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + if !p.IsStartPubg() || p.world.GetId() != player.WorldId { return } - p.CreateUserTimer(player.PlayerId, 10, pubgGame.UserTimerPubgDieExit, pubgGame.world.GetId()) + p.CreateUserTimer(player.PlayerId, 10, p.UserTimerPubgDieExit, p.world.GetId()) } // EventMarkMap 地图标点事件 func (p *PluginPubg) EventMarkMap(iEvent IPluginEvent) { event := iEvent.(*PluginEventMarkMap) player := event.Player - // 获取玩家所在的pubg游戏 - pubgGame := p.GetPlayerInPubgGame(player) - if pubgGame == nil { - return - } // 确保游戏开启 - if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + if !p.IsStartPubg() || p.world.GetId() != player.WorldId { return } - GAME.SendMsg(cmd.MarkMapRsp, player.PlayerId, player.ClientSeq, &proto.MarkMapRsp{MarkList: pubgGame.GetAreaPointList()}) + GAME.SendMsg(cmd.MarkMapRsp, player.PlayerId, player.ClientSeq, &proto.MarkMapRsp{MarkList: p.GetAreaPointList()}) event.Cancel() } @@ -244,37 +121,29 @@ func (p *PluginPubg) EventMarkMap(iEvent IPluginEvent) { func (p *PluginPubg) EventAvatarDieAnimationEnd(iEvent IPluginEvent) { event := iEvent.(*PluginEventAvatarDieAnimationEnd) player := event.Player - // 获取玩家所在的pubg游戏 - pubgGame := p.GetPlayerInPubgGame(player) - if pubgGame == nil { - return - } // 确保游戏开启 - if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + if !p.IsStartPubg() || p.world.GetId() != player.WorldId { return } - alivePlayerNum := len(pubgGame.GetAlivePlayerList()) - GAME.SendWorldChat(pubgGame.world, "『%v』死亡了,剩余%v位存活玩家。", player.NickName, alivePlayerNum) + 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}) event.Cancel() } func (p *PluginPubg) EventGadgetInteract(iEvent IPluginEvent) { event := iEvent.(*PluginEventGadgetInteract) player := event.Player - // 获取玩家所在的pubg游戏 - pubgGame := p.GetPlayerInPubgGame(player) - if pubgGame == nil { - return - } // 确保游戏开启 - if !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + if !p.IsStartPubg() || p.world.GetId() != player.WorldId { return } req := event.Req - worldGadgetId, exist := pubgGame.entityIdWorldGadgetIdMap[req.GadgetEntityId] + worldGadgetId, exist := p.entityIdWorldGadgetIdMap[req.GadgetEntityId] if exist { dbAvatar := player.GetDbAvatar() - avatarId := pubgGame.world.GetPlayerActiveAvatarId(player) + avatarId := p.world.GetPlayerActiveAvatarId(player) avatar := dbAvatar.AvatarMap[avatarId] pubgWorldGadgetDataConfig := gdconf.GetPubgWorldGadgetDataById(worldGadgetId) switch pubgWorldGadgetDataConfig.Type { @@ -282,14 +151,16 @@ 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]) // 提示玩家 - GAME.SendWorldChat(pubgGame.world, "你的角色攻击力增加:%v,增加后的攻击力:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_BASE_ATTACK]) + 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}}}) 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] } // 提示玩家 - GAME.SendWorldChat(pubgGame.world, "你的角色生命值增加:%v,目前为:%v。", pubgWorldGadgetDataConfig.Param[0], avatar.FightPropMap[constant.FIGHT_PROP_CUR_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.SendMsg(cmd.AvatarFightPropUpdateNotify, player.PlayerId, player.ClientSeq, &proto.AvatarFightPropUpdateNotify{ AvatarGuid: avatar.Guid, @@ -316,13 +187,8 @@ 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 !pubgGame.IsStartPubg() || pubgGame.world.GetId() != player.WorldId { + if !p.IsStartPubg() || p.world.GetId() != player.WorldId { return } // 开启GM按钮 隐藏多人世界玩家位置地图标记 @@ -348,48 +214,70 @@ func (p *PluginPubg) EventPostEnterScene(iEvent IPluginEvent) { /************************************************** 全局定时器 **************************************************/ // GlobalTickPubg pubg游戏定时器 -func (p *PluginPubg) GlobalTickPubg(now int64) { - for _, game := range p.pubgGameMap { - // 游戏没有玩家则不进行tick - if len(game.playerUidList) == 0 { - continue +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, + }, + }) } - game.gameTick++ - // 处理当前阶段 - switch game.gameState { - case PUBG_STATE_WAIT: - // 等待阶段 - game.PhaseWait() - case PUBG_STATE_START: - // 开始阶段 - game.HandleStateStart() - case PUBG_STATE_STOP: - // 结束阶段 - game.HandleStateStop() + } + 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}}}) } + p.StopPubg() } } -// 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) - } +// GlobalTickMinuteChange 定时开启pubg游戏 +func (p *PluginPubg) GlobalTickMinuteChange() { + minute := time.Now().Minute() + roomNumber := GAME.GetGsId() - 1 + startMinute := roomNumber % 6 * 10 + if uint32(minute) == startMinute { + p.StartPubg() } } /************************************************** 用户定时器 **************************************************/ +// 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 *PubgGame) UserTimerPubgUpdateArea(player *model.Player, data []any) { - logger.Debug("UserTimerPubgUpdateArea, gameId: %v, roomId: %v", p.gameId, p.roomId) +func (p *PluginPubg) UserTimerPubgUpdateArea(player *model.Player, data []any) { + logger.Debug("UserTimerPubgUpdateArea, seq: %v", p.seq) if !p.IsStartPubg() { return } @@ -398,8 +286,8 @@ func (p *PubgGame) UserTimerPubgUpdateArea(player *model.Player, data []any) { } // UserTimerPubgDieExit pubg死亡离开 -func (p *PubgGame) UserTimerPubgDieExit(player *model.Player, data []any) { - logger.Debug("UserTimerPubgDieExit, gameId: %v, roomId: %v", p.gameId, p.roomId) +func (p *PluginPubg) UserTimerPubgDieExit(player *model.Player, data []any) { + logger.Debug("UserTimerPubgDieExit, seq: %v", p.seq) pubgWorldId := data[0].(uint64) if player.WorldId != pubgWorldId { return @@ -435,11 +323,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 @@ -450,174 +338,17 @@ func (p *PluginPubg) PubgCommand(c *CommandContent) bool { /************************************************** 插件功能 **************************************************/ -// 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.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) +func (p *PluginPubg) StartPubg() { + if p.IsStartPubg() { return } - // 切换阶段 - p.gameState = PUBG_STATE_START - // 重置game tick - p.gameTick = 0 - // 初始化pubg游戏 + 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}}}) for _, pubgWorldGadgetDataConfig := range gdconf.GetPubgWorldGadgetDataMap() { rn := random.GetRandomInt32(1, 100) if rn > pubgWorldGadgetDataConfig.Probability { @@ -631,13 +362,9 @@ func (p *PubgGame) StartPubg() { ) p.entityIdWorldGadgetIdMap[entityId] = pubgWorldGadgetDataConfig.WorldGadgetId } - // 刷新区域 + p.phase = PUBG_PHASE_START p.RefreshArea() - for _, player := range p.world.GetAllPlayer() { - // 跳过ai - if player.PlayerId == p.ai.PlayerId { - continue - } + for _, player := range world.GetAllPlayer() { dbAvatar := player.GetDbAvatar() avatarId := p.world.GetPlayerActiveAvatarId(player) avatar := dbAvatar.AvatarMap[avatarId] @@ -654,46 +381,45 @@ func (p *PubgGame) 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 *PubgGame) StopPubg() { - logger.Debug("StopPubg, gameId: %v, roomId: %v", p.gameId, p.roomId) - // 确保上个阶段为不为等待状态和结束状态 +func (p *PluginPubg) StopPubg() { if !p.IsStartPubg() { - logger.Error("pubg game state not end, gameState: %v", p.gameState) return } - // 切换阶段 - p.gameState = PUBG_STATE_STOP + 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}}}) } // IsStartPubg pubg游戏是否开启 -func (p *PubgGame) IsStartPubg() bool { - return p.gameState != PUBG_STATE_WAIT && p.gameState != PUBG_STATE_STOP +func (p *PluginPubg) IsStartPubg() bool { + return p.phase != PUBG_PHASE_WAIT } // GetAreaPointList 获取游戏区域标点列表 -func (p *PubgGame) GetAreaPointList() []*proto.MapMarkPoint { +func (p *PluginPubg) GetAreaPointList() []*proto.MapMarkPoint { return p.areaPointList } // UpdateArea 更新游戏区域 -func (p *PubgGame) UpdateArea() { +func (p *PluginPubg) UpdateArea() { if p.areaReduceRadiusSpeed > 0.0 && p.blueAreaRadius > p.safeAreaRadius { p.blueAreaRadius -= p.areaReduceRadiusSpeed p.blueAreaCenterPos.X += p.areaReduceXSpeed @@ -703,7 +429,7 @@ func (p *PubgGame) UpdateArea() { } // IsInBlueArea 是否在蓝圈内 -func (p *PubgGame) IsInBlueArea(pos *model.Vector) bool { +func (p *PluginPubg) 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), @@ -712,22 +438,23 @@ func (p *PubgGame) IsInBlueArea(pos *model.Vector) bool { } // RefreshArea 刷新游戏区域 -func (p *PubgGame) RefreshArea() { +func (p *PluginPubg) RefreshArea() { + info := "" if p.phase == PUBG_PHASE_START { - GAME.SendWorldChat(p.world, "安全区已生成,当前%v位存活玩家。", len(p.GetAlivePlayerList())) + info = fmt.Sprintf("安全区已生成,当前%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.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) + p.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) } else if p.phase == PUBG_PHASE_END { - GAME.SendWorldChat(p.world, "安全区已消失。") + info = "安全区已消失。" p.blueAreaRadius = 0.0 p.safeAreaRadius = 0.0 } else { switch p.phase % 3 { case 1: - GAME.SendWorldChat(p.world, "新的安全区已出现,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + info = fmt.Sprintf("新的安全区已出现,进度%.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, @@ -735,9 +462,9 @@ func (p *PubgGame) RefreshArea() { } p.safeAreaRadius = p.blueAreaRadius / 2.0 p.areaReduceRadiusSpeed = 0.0 - p.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) + p.CreateUserTimer(p.world.GetOwner().PlayerId, PUBG_PHASE_INV_TIME, p.UserTimerPubgUpdateArea) case 2: - GAME.SendWorldChat(p.world, "安全区正在缩小,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + info = fmt.Sprintf("安全区正在缩小,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) invTime := 0.0 if p.phase == PUBG_PHASE_II { invTime = PUBG_FIRST_AREA_REDUCE_TIME @@ -747,17 +474,18 @@ func (p *PubgGame) 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.pluginPubg.CreateUserTimer(p.world.GetOwner().PlayerId, uint32(invTime), p.UserTimerPubgUpdateArea) + p.CreateUserTimer(p.world.GetOwner().PlayerId, uint32(invTime), p.UserTimerPubgUpdateArea) case 0: - 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) + info = fmt.Sprintf("安全区缩小完毕,进度%.1f%%。", float64(p.phase)/PUBG_PHASE_END*100.0) + p.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 *PubgGame) SyncMapMarkArea() { +func (p *PluginPubg) SyncMapMarkArea() { p.areaPointList = make([]*proto.MapMarkPoint, 0) if p.blueAreaRadius > 0.0 { for angleStep := 0; angleStep < 360; angleStep += 5 { @@ -789,7 +517,7 @@ func (p *PubgGame) SyncMapMarkArea() { } // GetAlivePlayerList 获取存活玩家列表 -func (p *PubgGame) GetAlivePlayerList() []*model.Player { +func (p *PluginPubg) GetAlivePlayerList() []*model.Player { scene := p.world.GetSceneById(p.world.GetOwner().SceneId) alivePlayerList := make([]*model.Player, 0) for _, scenePlayer := range scene.GetAllPlayer() { @@ -806,7 +534,7 @@ func (p *PubgGame) GetAlivePlayerList() []*model.Player { return alivePlayerList } -func (p *PubgGame) PubgHit(scene *Scene, defAvatarEntityId uint32, atkAvatarEntityId uint32, isBow bool) { +func (p *PluginPubg) 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 aa6ea4a9..b58a8ace 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 gameState change, uid: %v, online: %v", serverMsg.UserId, serverMsg.IsOnline) + logger.Debug("remote user online state 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,12 +220,6 @@ 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 8d81f325..067d4665 100644 --- a/gs/game/game_tick_manager.go +++ b/gs/game/game_tick_manager.go @@ -159,35 +159,28 @@ 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, now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickSecond) } 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 { @@ -213,19 +206,16 @@ func (t *TickManager) OnGameServerTick() { } if tm.Minute() != t.tm.Minute() { t.onMinuteChange(now) - PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMinuteChange, now) + PLUGIN_MANAGER.HandleGlobalTick(PluginGlobalTickMinuteChange) } 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 } @@ -275,11 +265,22 @@ func (t *TickManager) onTick5Second(now int64) { GAME.ScenePlayerLocationNotify(world) } } - // ai世界自动同意进入 - for _, player := range AI_MANAGER.aiMap { - for applyUid := range player.CoopApplyMap { - GAME.PlayerDealEnterWorld(player, applyUid, true) - } + 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) } } @@ -324,12 +325,29 @@ 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.GetWorldById(GAME.ai.WorldId) + world := WORLD_MANAGER.GetAiWorld() 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 fe3c1bcf..8daf1e36 100644 --- a/gs/game/game_user_manager.go +++ b/gs/game/game_user_manager.go @@ -174,15 +174,6 @@ 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, @@ -241,22 +232,22 @@ func (u *UserManager) ChangeUserDbState(player *model.Player, state int) { } else if state == model.DbNormal { player.DbState = model.DbNormal } else { - logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) } case model.DbInsert: - logger.Error("player db gameState change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db state 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 gameState change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db state 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 gameState change not allow, before: %v, after: %v", player.DbState, state) + logger.Error("player db state change not allow, before: %v, after: %v", player.DbState, state) } } } @@ -328,10 +319,12 @@ func (u *UserManager) SetRemoteUserOnlineState(userId uint32, isOnline bool, app func (u *UserManager) GetAllRemoteAiUidList() []uint32 { userIdList := make([]uint32, 0) u.remotePlayerMapLock.RLock() - for userId := range u.remotePlayerMap { - if userId <= PlayerBaseUid { - userIdList = append(userIdList, userId) + for userId := uint32(AiBaseUid); userId < AiBaseUid+1000; userId++ { + _, exist := u.remotePlayerMap[userId] + if !exist { + continue } + userIdList = append(userIdList, userId) } u.remotePlayerMapLock.RUnlock() return userIdList @@ -553,7 +546,7 @@ func (u *UserManager) SaveUserToDbSync(player *model.Player) { return } } else { - logger.Error("invalid player db gameState: %v", player.DbState) + logger.Error("invalid player db state: %v", player.DbState) } } diff --git a/gs/game/game_world_manager.go b/gs/game/game_world_manager.go index 95b0753a..c216ea14 100644 --- a/gs/game/game_world_manager.go +++ b/gs/game/game_world_manager.go @@ -24,6 +24,7 @@ const ( type WorldManager struct { worldMap map[uint64]*World snowflake *alg.SnowflakeWorker + aiWorld *World // 本服的Ai玩家世界 sceneBlockAoiMap map[uint32]*alg.AoiManager // 全局各场景地图的aoi管理器 multiplayerWorldNum uint32 // 本服务器的多人世界数量 } @@ -91,15 +92,20 @@ 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) { - aiWorld := w.GetWorldById(owner.WorldId) - aiWorld.ChangeToMultiplayer() - aiWorld.NewPhysicsEngine() + w.aiWorld = w.GetWorldById(owner.WorldId) + w.aiWorld.ChangeToMultiplayer() + w.aiWorld.NewPhysicsEngine() } func (w *WorldManager) IsAiWorld(world *World) bool { - return AI_MANAGER.IsAi(world.owner.PlayerId) + return world.owner.PlayerId < PlayerBaseUid } func (w *WorldManager) GetSceneBlockAoiMap() map[uint32]*alg.AoiManager { diff --git a/gs/game/player_chat.go b/gs/game/player_chat.go index 622d1a60..30eb04a1 100644 --- a/gs/game/player_chat.go +++ b/gs/game/player_chat.go @@ -1,7 +1,6 @@ package game import ( - "fmt" "time" "hk4e/common/mq" @@ -181,12 +180,6 @@ 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 44dbf4a7..30d0b59f 100644 --- a/gs/game/player_fight_sync.go +++ b/gs/game/player_fight_sync.go @@ -692,19 +692,54 @@ 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 ddb870e6..760b9c6e 100644 --- a/gs/game/player_multiplayer.go +++ b/gs/game/player_multiplayer.go @@ -16,16 +16,6 @@ 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 @@ -35,20 +25,6 @@ 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) } @@ -124,21 +100,6 @@ 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) @@ -146,21 +107,6 @@ 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{}) } @@ -217,15 +163,6 @@ 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 @@ -234,20 +171,6 @@ 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 e9d1d5eb..733cc64b 100644 --- a/gs/game/player_social.go +++ b/gs/game/player_social.go @@ -1,6 +1,7 @@ package game import ( + "fmt" "regexp" "time" "unicode/utf8" @@ -370,54 +371,67 @@ func (g *Game) DealAddFriendReq(player *model.Player, payloadMsg pb.Message) { } } -// 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 - } - 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: info.AiInfo.HeadImage, - MpSettingType: proto.MpSettingType_MP_SETTING_ENTER_AFTER_APPLY, - NameCardId: info.AiInfo.NameCard, - Signature: info.AiInfo.Sign, - ProfilePicture: &proto.ProfilePicture{AvatarId: info.AiInfo.HeadImage}, - CurPlayerNumInWorld: info.PlayerCount, - }) - } - // 添加本服其他的玩家 - playerInfoList = append(playerInfoList, g.GetOnlinePlayerInfoList(player, len(playerInfoList))...) - - getOnlinePlayerListRsp := &proto.GetOnlinePlayerListRsp{ - PlayerInfoList: playerInfoList, - } - 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, - }, + count := 0 + rsp := &proto.GetOnlinePlayerListRsp{ + PlayerInfoList: make([]*proto.OnlinePlayerInfo, 0), + } + // 最先添加全服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, + PlayerLevel: 1, + AvatarId: 10000007, + MpSettingType: proto.MpSettingType_MP_SETTING_ENTER_AFTER_APPLY, + NameCardId: 210001, + Signature: sign, + ProfilePicture: &proto.ProfilePicture{AvatarId: 10000007}, + CurPlayerNumInWorld: 1, }) - return + count++ } - getOnlinePlayerListRsp := &proto.GetOnlinePlayerListRsp{ - PlayerInfoList: g.GetOnlinePlayerInfoList(player, 0), + 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 + } } - g.SendMsg(cmd.GetOnlinePlayerListRsp, player.PlayerId, player.ClientSeq, getOnlinePlayerListRsp) + 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 + } + } + } + + for _, onlinePlayer := range onlinePlayerList { + onlinePlayerInfo := g.PacketOnlinePlayerInfo(onlinePlayer) + rsp.PlayerInfoList = append(rsp.PlayerInfoList, onlinePlayerInfo) + } + g.SendMsg(cmd.GetOnlinePlayerListRsp, player.PlayerId, player.ClientSeq, rsp) } func (g *Game) GetOnlinePlayerInfoReq(player *model.Player, payloadMsg pb.Message) { @@ -491,53 +505,6 @@ 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 8e567264..9a27aa2a 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, gameState: %v", stamina, player.StaminaInfo.State) + logger.Debug("player drown, curStamina: %v, state: %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 c3138306..8e01ed1e 100644 --- a/gs/game/player_world.go +++ b/gs/game/player_world.go @@ -677,6 +677,10 @@ 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 22d6311a..44f5b3c7 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 not exist, questId: %v", questId) + logger.Error("quest is not exist, questId: %v", questId) return } delete(q.QuestMap, questId) diff --git a/multi/app/app.go b/multi/app/app.go index a423484c..55cc00fe 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, discoveryClient) + _ = handle.NewHandle(messageQueue) 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 36efd21b..0fc1030b 100644 --- a/multi/handle/handle.go +++ b/multi/handle/handle.go @@ -1,37 +1,27 @@ 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 - discoveryClient *rpc.DiscoveryClient - playerAcCtxMap map[uint32]*AnticheatContext - worldStatic *WorldStatic - match *Match - minLoadGsServerAppId string + messageQueue *mq.MessageQueue + playerAcCtxMap map[uint32]*AnticheatContext + worldStatic *WorldStatic } -func NewHandle(messageQueue *mq.MessageQueue, discoveryClient *rpc.DiscoveryClient) (r *Handle) { +func NewHandle(messageQueue *mq.MessageQueue) (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 } @@ -69,48 +59,11 @@ 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 deleted file mode 100644 index c3a4f3d0..00000000 --- a/multi/handle/match.go +++ /dev/null @@ -1,351 +0,0 @@ -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) -}