From b58e4e28b5e38d31185c9d0bf105a700373aa892 Mon Sep 17 00:00:00 2001
From: hxp <ale99527@vip.qq.com>
Date: 星期四, 28 三月 2024 16:46:12 +0800
Subject: [PATCH] 9946 【砍树】【港台】【越南】【主干】仙盟BOSS修改(修复当副本有盟友在打时,其他盟友进入偶发统计时长异常bug;)

---
 ServerPython/CoreServerGroup/GameServer/Script/GameWorldLogic/CrossRealmPK.py |  864 ++++++++++++++++++++++++++++++++++++++------------------
 1 files changed, 581 insertions(+), 283 deletions(-)

diff --git a/ServerPython/CoreServerGroup/GameServer/Script/GameWorldLogic/CrossRealmPK.py b/ServerPython/CoreServerGroup/GameServer/Script/GameWorldLogic/CrossRealmPK.py
index 6a9ef00..58ef254 100644
--- a/ServerPython/CoreServerGroup/GameServer/Script/GameWorldLogic/CrossRealmPK.py
+++ b/ServerPython/CoreServerGroup/GameServer/Script/GameWorldLogic/CrossRealmPK.py
@@ -58,12 +58,13 @@
         self.serverGroupID = 0 # 所属服务器ID,一个服务器ID由多个服组成
         self.pkZoneID = 0 # 所属赛区ID,一个赛区由多个服务器ID组成
         self.seasonID = 0 # 赛季ID
+        self.notifyMatchRobotTick = 0 # 通知匹配到机器人的tick
         return
     
     def GetDRInfo(self):
         ## 流向记录信息
-        return {"accID":self.accID, "playerID":self.playerID, "fightPower":self.fightPower, "pkScore":self.pkScore, 
-                "danLV":self.danLV, "matchTick":self.matchTick, "prepareOKTick":self.prepareOKTick, "cWinCount":self.cWinCount, 
+        return {"accID":self.accID, "playerID":self.playerID, "fightPower":self.fightPower, "pkScore":self.pkScore,
+                "danLV":self.danLV, "matchTick":self.matchTick, "prepareOKTick":self.prepareOKTick, "cWinCount":self.cWinCount,
                 "ondayScore":self.ondayScore, "serverGroupID":self.serverGroupID, "ondayScore":self.ondayScore}
     
 class CrossPKRoom():
@@ -83,7 +84,7 @@
         return
     
     def GetDRInfo(self):
-        return {"zoneID":self.pkZoneID, "seasonID":self.seasonID, "roomID":self.roomID, "mapID":self.mapID, "openTick":self.openTick, 
+        return {"zoneID":self.pkZoneID, "seasonID":self.seasonID, "roomID":self.roomID, "mapID":self.mapID, "openTick":self.openTick,
                 "readyTick":self.readyTick, "roomPlayerIDList":self.roomPlayerIDList, "mapFBOpenTick":self.mapFBOpenTick}
         
 #跨服PK排行榜管理,注意该类只处理数据逻辑,功能相关逻辑不要写在该类,不然重读脚本不会生效
@@ -199,7 +200,7 @@
                 cnt += 1
                 savaData += billboardData.getBuffer()
                 
-        GameWorld.Log("SaveCrossPKBillboard cnt :%s" % cnt)
+        GameWorld.Log("SaveCrossPKBillboard cnt :%s len=%s" % (cnt, len(savaData)))
         return CommFunc.WriteDWORD(cntData, cnt) + savaData
     
     # 从数据库载入数据
@@ -225,7 +226,7 @@
             
         return pos
     
-def UpdateCrossPKBillboard(zoneID, seasonID, winner, loser):
+def UpdateCrossPKBillboard(zoneID, seasonID, winner, loser, syncClientServer=False):
     ## 更新跨服PK排行榜,跨服服务器结算调用,子服不调用
     
     curZoneSeasonID = GameWorld.GetGameWorld().GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonID % zoneID)
@@ -241,14 +242,16 @@
         return
     maxCount = min(2000, maxCount)
     upBillboardList = []
-    if winner.danLV >= danLVLimit:
-        upBillboardList.append(winner)
-    else:
-        GameWorld.DebugLog("    段位不足,无法上榜! winnerDanLV=%s < danLVLimit=%s" % (winner.danLV, danLVLimit), winner.playerID)
-    if loser.danLV >= danLVLimit:
-        upBillboardList.append(loser)
-    else:
-        GameWorld.DebugLog("    段位不足,无法上榜! loserDanLV=%s < danLVLimit=%s" % (loser.danLV, danLVLimit), loser.playerID)
+    if winner:
+        if winner.danLV >= danLVLimit:
+            upBillboardList.append(winner)
+        else:
+            GameWorld.DebugLog("    段位不足,无法上榜! winnerDanLV=%s < danLVLimit=%s" % (winner.danLV, danLVLimit), winner.playerID)
+    if loser:
+        if loser.danLV >= danLVLimit:
+            upBillboardList.append(loser)
+        else:
+            GameWorld.DebugLog("    段位不足,无法上榜! loserDanLV=%s < danLVLimit=%s" % (loser.danLV, danLVLimit), loser.playerID)
     if not upBillboardList:
         return
     
@@ -307,12 +310,15 @@
     matchState = GameWorld.GetGameWorld().GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossDailyActionState % ShareDefine.DailyActionID_CrossReamPK)
     if not matchState and not PyGameData.g_crossPKRoomDict:
         GameWorld.Log("匹配已结束,且当前没有PK中的房间了!主动广播子服最新榜单! ")
-        zoneIpyData = IpyGameDataPY.GetIpyGameData("CrossRealmPKZone", zoneID)
+        syncClientServer = True
+    if syncClientServer:
+        crossZoneName = GameWorld.GetCrossZoneName()
+        zoneIpyData = IpyGameDataPY.GetIpyGameData("CrossZonePK", crossZoneName, zoneID)
         if zoneIpyData:
             serverGroupIDList = zoneIpyData.GetServerGroupIDList()
             SyncPKSyncBillboardToClientServer(zoneID, seasonID, serverGroupIDList)
             
-    return
+    return True
 
 #// C0 01 查看跨服竞技场赛季排行榜 #tagCGViewCrossPKBillboard
 #
@@ -366,7 +372,8 @@
         serverTime = GameWorld.GetServerTime()
         curSeasonID = 0
         seasonState = 0
-        seasonList = IpyGameDataPY.GetIpyGameDataList("CrossRealmPKSeason", zoneID)
+        crossZoneName = GameWorld.GetCrossZoneName()
+        seasonList = IpyGameDataPY.GetIpyGameDataList("CrossRealmPKSeason", crossZoneName, zoneID)
         seasonList = [] if not seasonList else seasonList
         for seasonIpyData in seasonList:
             startDateStr = seasonIpyData.GetStartDate()
@@ -433,6 +440,9 @@
 
 def ClientServerMsg_PKBillboard(serverGroupID, msgData):
     ## 收到子服请求查询PK排行榜信息
+    if "GMSetCrossPK" in msgData:
+        _GMSetCrossPK(serverGroupID, msgData)
+        return
     zoneID = msgData["ZoneID"]
     seasonID = msgData["SeasonID"]
     exData = msgData.get("ExData", {}) # 原数据返回子服
@@ -442,7 +452,7 @@
 def SyncPKSyncBillboardToClientServer(zoneID, seasonID, serverGroupIDList, exData={}):
     ## 同步赛区赛季榜单到子服
     crossPKBillboardMgr = PyDataManager.GetCrossPKBillboardManager()
-    billboardList, orderDict  = crossPKBillboardMgr.GetCrossPKBillboardInfo(zoneID, seasonID, True) # 同步子服前需触发排序
+    billboardList, orderDict = crossPKBillboardMgr.GetCrossPKBillboardInfo(zoneID, seasonID, True) # 同步子服前需触发排序
     isFinalBillboardData = False # 是否最终的榜单数据
     gameWorld = GameWorld.GetGameWorld()
     curZoneSeasonID = gameWorld.GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonID % zoneID)
@@ -535,18 +545,19 @@
     
     zoneSeasonTimeDict = {}
     serverTime = GameWorld.GetServerTime()
-    ipyDataMgr = IpyGameDataPY.IPY_Data()
-    for index in xrange(ipyDataMgr.GetCrossRealmPKZoneCount()):
-        zoneIpyData = ipyDataMgr.GetCrossRealmPKZoneByIndex(index)
+    crossZoneName = GameWorld.GetCrossZoneName()
+    crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+    if not crossZoneList:
+        return zoneSeasonTimeDict
+    
+    for zoneIpyData in crossZoneList:
         zoneID = zoneIpyData.GetZoneID()
         
         # 规定每个赛区的赛季时间需按顺序配置
-        seasonIpyDataList = []
-        for sIndex in xrange(ipyDataMgr.GetCrossRealmPKSeasonCount()):
-            seasonIpyData = ipyDataMgr.GetCrossRealmPKSeasonByIndex(sIndex)
-            if zoneID == seasonIpyData.GetZoneID():
-                seasonIpyDataList.append(seasonIpyData)
-                
+        seasonIpyDataList = IpyGameDataPY.GetIpyGameDataList("CrossRealmPKSeason", crossZoneName, zoneID)
+        if not seasonIpyDataList:
+            continue
+        
         for i, seasonIpyData in enumerate(seasonIpyDataList):
             seasonID = seasonIpyData.GetSeasonID()
             startDateStr = seasonIpyData.GetStartDate()
@@ -604,8 +615,9 @@
     
     gameWorld = GameWorld.GetGameWorld()
     serverTime = GameWorld.GetServerTime()
+    crossZoneName = GameWorld.GetCrossZoneName()
     for zoneID, seasonTimeInfo in zoneSeasonTimeDict.items():
-        zoneIpyData = IpyGameDataPY.GetIpyGameData("CrossRealmPKZone", zoneID)
+        zoneIpyData = IpyGameDataPY.GetIpyGameData("CrossZonePK", crossZoneName, zoneID)
         if not zoneIpyData:
             continue
         
@@ -664,12 +676,18 @@
     if not preState and isOpen:
         PyGameData.g_crossPKPlayerDict = {}
         PyGameData.g_crossPKZoneMatchPlayerDict = {}
+        PyGameData.g_crossPKZoneMatchRobotPlayerDict = {}
         PyGameData.g_crossPKRoomDict = {}
+        PyGameData.g_crossPKTodayPKRecordInfo = {}
+        PyGameData.g_crossPKBesureMatchRobotInfo = {}
         GameWorld.Log("跨服PK匹配状态开启,重置相关匹配数据!")
         
-    ipyDataMgr = IpyGameDataPY.IPY_Data()
-    for index in xrange(ipyDataMgr.GetCrossRealmPKZoneCount()):
-        zoneIpyData = ipyDataMgr.GetCrossRealmPKZoneByIndex(index)
+    crossZoneName = GameWorld.GetCrossZoneName()
+    crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+    if not crossZoneList:
+        return
+    
+    for zoneIpyData in crossZoneList:
         zoneID = zoneIpyData.GetZoneID()
         
         # 广播当前赛区的所有子服跨服PK赛季状态变更
@@ -682,87 +700,109 @@
         
     return
 
-def ClientServerMsg_ServerInitOK(serverGroupID, tick):
-    ## 子服启动成功
-    GameWorld.Log("子服启动成功,同步给子服对应的赛季信息: serverGroupID=%s" % (serverGroupID))
-    zoneID = GetCrossPKServerGroupZoneID(serverGroupID)
-    if not zoneID:
-        GameWorld.Log("    该子服没有分配赛区,不同步!")
+def Sync_CrossPKInitDataToClientServer(tick, serverGroupID=0):
+    ''' 同步跨服PK活动数据到子服务器
+    @param serverGroupID: 为0时同步所有子服
+    '''
+    
+    GameWorld.Log("同步给子服对应的赛季信息: syncServerGroupID=%s" % (serverGroupID))
+    if serverGroupID:
+        ipyData = GetCrossPKServerGroupZone(serverGroupID)
+        if not ipyData:
+            return
+        crossZoneList = [ipyData]
+    else:
+        crossZoneName = GameWorld.GetCrossZoneName()
+        crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+    if not crossZoneList:
         return
     gameWorld = GameWorld.GetGameWorld()
-    seasonID = gameWorld.GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonID % zoneID)
-    seasonState = gameWorld.GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonState % zoneID)
-    matchState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossDailyActionState % ShareDefine.DailyActionID_CrossReamPK)
-    seasonInfo = {"ZoneID":zoneID, "SeasonID":seasonID, "SeasonState":seasonState, "MatchState":matchState}
-    CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKSeasonInfo, seasonInfo, [serverGroupID])
+    for zoneIpyData in crossZoneList:
+        zoneID = zoneIpyData.GetZoneID()
+        seasonID = gameWorld.GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonID % zoneID)
+        seasonState = gameWorld.GetDictByKey(ChConfig.Def_WorldKey_CrossPKZoneSeasonState % zoneID)
+        matchState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossDailyActionState % ShareDefine.DailyActionID_CrossReamPK)
+        seasonInfo = {"ZoneID":zoneID, "SeasonID":seasonID, "SeasonState":seasonState, "MatchState":matchState}
+        serverGroupIDList = [serverGroupID] if serverGroupID else zoneIpyData.GetServerGroupIDList()
+        CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKSeasonInfo, seasonInfo, serverGroupIDList)
+        
     return
 
-def GetCrossPKServerGroupZoneID(serverGroupID):
+def GetCrossPKServerGroupZone(serverGroupID):
     ## 获取服务器组ID对应的跨服PK所属赛区,返回0代表该服务器没有分配赛区
-    ipyDataMgr = IpyGameDataPY.IPY_Data()
-    for index in xrange(ipyDataMgr.GetCrossRealmPKZoneCount()):
-        zoneIpyData = ipyDataMgr.GetCrossRealmPKZoneByIndex(index)
+    crossZoneName = GameWorld.GetCrossZoneName()
+    crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+    if not crossZoneList:
+        return
+    
+    for zoneIpyData in crossZoneList:
         for groupInfo in zoneIpyData.GetServerGroupIDList():
             if (isinstance(groupInfo, int) and serverGroupID == groupInfo) \
                 or (isinstance(groupInfo, tuple) and len(groupInfo) == 2 and groupInfo[0] <= serverGroupID <= groupInfo[1]):
-                return zoneIpyData.GetZoneID()
-    return 0
+                return zoneIpyData
+    return
+
+def OnPlayerLoginCrossServer(curPlayer):
+    # 跨服登录处理
+    
+    mapID = curPlayer.GetMapID()
+    mapIDList = IpyGameDataPY.GetFuncCfg("CrossRealmPKMatch", 4)
+    if mapID not in mapIDList:
+        return
+    
+    GameWorld.Log("玩家登录跨服PK地图, mapID=%s" % mapID, curPlayer.GetPlayerID())
+    if not __CheckCanLoginCrossServerPKMap(curPlayer):
+        CrossRealmPlayer.PlayerExitCrossServer(curPlayer)
+        return
+    
+    return
 
 def OnPlayerLogin(curPlayer):
-    
     # 本服登录处理
-    if not GameWorld.IsCrossServer():
-        # 本服没有分配赛区不处理
-        if not GameWorld.GetGameWorld().GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKZoneID):
-            return
-        __OnLoginNotifyPKOverInfo(curPlayer)
-        
-        # 同步所有赛区赛季信息
-        zoneSeasonInfo = ChPyNetSendPack.tagGCCrossRealmPKSeasonInfo()
-        zoneSeasonInfo.ZoneList = []
-        ipyDataMgr = IpyGameDataPY.IPY_Data()
-        for index in xrange(ipyDataMgr.GetCrossRealmPKZoneCount()):
-            zoneIpyData = ipyDataMgr.GetCrossRealmPKZoneByIndex(index)
-            zoneID = zoneIpyData.GetZoneID()
-            zoneInfo = ChPyNetSendPack.tagGCCrossRealmPKZone()
-            zoneInfo.ZoneID = zoneID
-            zoneInfo.ZoneName = zoneIpyData.GetZoneName().decode(ShareDefine.Def_Game_Character_Encoding).encode(GameWorld.GetCharacterEncoding())
-            zoneInfo.ZoneNameLen = len(zoneInfo.ZoneName)
-            zoneInfo.SeasonList = []
-            seasonList = IpyGameDataPY.GetIpyGameDataList("CrossRealmPKSeason", zoneID)
-            seasonList = [] if not seasonList else seasonList
-            for seasonIpyData in seasonList:
-                seasonInfo = ChPyNetSendPack.tagGCCrossRealmPKSeason()
-                seasonInfo.SeasonID = seasonIpyData.GetSeasonID()
-                seasonInfo.StartDate = seasonIpyData.GetStartDate()
-                seasonInfo.EndDate = seasonIpyData.GetEndDate()
-                seasonInfo.EndTime = seasonIpyData.GetEndTime()
-                zoneInfo.SeasonList.append(seasonInfo)
-            zoneInfo.SeasonCount = len(zoneInfo.SeasonList)
-            zoneSeasonInfo.ZoneList.append(zoneInfo)
-        zoneSeasonInfo.ZoneCount = len(zoneSeasonInfo.ZoneList)
-        NetPackCommon.SendFakePack(curPlayer, zoneSeasonInfo)
-        
-        # 同步本服赛季状态
-        gameWorld = GameWorld.GetGameWorld()
-        seasonStatePack = ChPyNetSendPack.tagGCCrossRealmPKSeasonState()
-        seasonStatePack.ZoneID = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKZoneID)
-        seasonStatePack.SeasonID = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonID)
-        seasonStatePack.SeasonState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonState)
-        seasonStatePack.MatchState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossDailyActionState % ShareDefine.DailyActionID_CrossReamPK)
-        NetPackCommon.SendFakePack(curPlayer, seasonStatePack)
-        
-    # 跨服登录处理
-    else:
-        mapID = curPlayer.GetMapID()
-        mapIDList = IpyGameDataPY.GetFuncCfg("CrossRealmPKMatch", 4)
-        if mapID not in mapIDList:
-            return
-        
-        GameWorld.Log("玩家登录跨服PK地图, mapID=%s" % mapID, curPlayer.GetPlayerID())
-        if not __CheckCanLoginCrossServerPKMap(curPlayer):
-            CrossRealmPlayer.PlayerExitCrossServer(curPlayer)
-            return
+    
+    # 本服没有分配赛区不处理
+    if not GameWorld.GetGameWorld().GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKZoneID):
+        return
+    __OnLoginNotifyPKOverInfo(curPlayer)
+    
+    crossZoneName = GameWorld.GetCrossZoneName()
+    crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+    if not crossZoneList:
+        return
+    # 同步所有赛区赛季信息
+    zoneSeasonInfo = ChPyNetSendPack.tagGCCrossRealmPKSeasonInfo()
+    zoneSeasonInfo.ZoneList = []
+    for zoneIpyData in crossZoneList:
+        zoneID = zoneIpyData.GetZoneID()
+        zoneInfo = ChPyNetSendPack.tagGCCrossRealmPKZone()
+        zoneInfo.ZoneID = zoneID
+        zoneInfo.ZoneName = zoneIpyData.GetZoneName().decode(ShareDefine.Def_Game_Character_Encoding).encode(GameWorld.GetCharacterEncoding())
+        zoneInfo.ZoneNameLen = len(zoneInfo.ZoneName)
+        zoneInfo.SeasonList = []
+        seasonList = IpyGameDataPY.GetIpyGameDataList("CrossRealmPKSeason", crossZoneName, zoneID)
+        seasonList = [] if not seasonList else seasonList
+        for seasonIpyData in seasonList:
+            seasonInfo = ChPyNetSendPack.tagGCCrossRealmPKSeason()
+            seasonInfo.SeasonID = seasonIpyData.GetSeasonID()
+            seasonInfo.StartDate = seasonIpyData.GetStartDate()
+            seasonInfo.EndDate = seasonIpyData.GetEndDate()
+            seasonInfo.EndTime = seasonIpyData.GetEndTime()
+            zoneInfo.SeasonList.append(seasonInfo)
+        zoneInfo.SeasonCount = len(zoneInfo.SeasonList)
+        zoneSeasonInfo.ZoneList.append(zoneInfo)
+    zoneSeasonInfo.ZoneCount = len(zoneSeasonInfo.ZoneList)
+    NetPackCommon.SendFakePack(curPlayer, zoneSeasonInfo)
+    
+    # 同步本服赛季状态
+    gameWorld = GameWorld.GetGameWorld()
+    seasonStatePack = ChPyNetSendPack.tagGCCrossRealmPKSeasonState()
+    seasonStatePack.ZoneID = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKZoneID)
+    seasonStatePack.SeasonID = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonID)
+    seasonStatePack.SeasonState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonState)
+    seasonStatePack.MatchState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossDailyActionState % ShareDefine.DailyActionID_CrossReamPK)
+    seasonStatePack.CrossZoneName = GameWorld.GetCrossZoneName()
+    seasonStatePack.CrossZoneNameLen = len(seasonStatePack.CrossZoneName)
+    NetPackCommon.SendFakePack(curPlayer, seasonStatePack)
         
     return
 
@@ -816,7 +856,7 @@
 #        return
 
     vsRoomID = curPlayer.GetVsRoomId()
-    if vsRoomID and PlayerControl.GetCrossRealmState(curPlayer) == 1:
+    if vsRoomID and PlayerControl.GetCrossMapID(curPlayer) == ChConfig.Def_FBMapID_CrossRealmPK:
         GameWorld.DebugLog("玩家跨服PK状态,不能取消匹配!vsRoomID=%s" % vsRoomID, curPlayer.GetPlayerID())
         return
     
@@ -852,20 +892,25 @@
     playerLV = playerInfoDict["playerLV"] # 职业
     maxHP = playerInfoDict["maxHP"] # 职业
     maxProDef = playerInfoDict["maxProDef"] # 护盾
-    fightPower = playerInfoDict["fightPower"] # 战斗力
+    fightPower = min(playerInfoDict["fightPower"], ChConfig.Def_UpperLimit_DWord) # 战斗力,暂无用,限制不超过20E
     realmLV = playerInfoDict["realmLV"] # 境界
     pkScore = playerInfoDict["pkScore"] # 当前积分
     danLV = playerInfoDict["danLV"] # 当前段位
     cWinCount = playerInfoDict["cWinCount"] # 连胜次数
+    cLoseCount = playerInfoDict["cLoseCount"] # 连败次数
     ondayScore = playerInfoDict["ondayScore"] # 过天时的积分
     
+    if playerID in PyGameData.g_crossPKZoneMatchRobotPlayerDict:
+        GameWorld.Log("玩家已匹配机器人,无法重复发起匹配! playerID=%s,accID=%s" % (playerID, accID))
+        CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 2], [serverGroupID])
+        return
     zoneMatchPlayerList = PyGameData.g_crossPKZoneMatchPlayerDict.get(pkZoneID, [])
     if playerID in zoneMatchPlayerList:
-        GameWorld.Log("玩家正在匹配中,无法重复发起匹配!playerID=%s,accID=%s" % (playerID, accID))
+        GameWorld.Log("玩家正在匹配中,无法重复发起匹配! playerID=%s,accID=%s" % (playerID, accID))
         CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 1], [serverGroupID])
         return
     if playerID in PyGameData.g_crossPKPlayerDict:
-        GameWorld.Log("玩家正在战斗中,无法重复发起匹配!playerID=%s,accID=%s" % (playerID, accID))
+        GameWorld.Log("玩家正在战斗中,无法重复发起匹配! playerID=%s,accID=%s" % (playerID, accID))
         CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, -2], [serverGroupID])
         return
     
@@ -887,16 +932,100 @@
     pkPlayer.serverGroupID = serverGroupID
     pkPlayer.pkZoneID = pkZoneID
     pkPlayer.seasonID = seasonID
+    
+    # 判断是否匹配机器人
+    matchRobotRate = 0
+    danIpyData = IpyGameDataPY.GetIpyGameData("CrossRealmPKDan", danLV)
+    if danIpyData:
+        matchRobotRate = danIpyData.GetMatchRobotRate() + danIpyData.GetMatchRobotRateEx() * cLoseCount
+    
+    # 判断是否必定匹配机器人: 连输X局必定连续匹配机器人Y局
+    cLoseCount = 0
+    todayPKRecordList = PyGameData.g_crossPKTodayPKRecordInfo.get(playerID, [])
+    for pkRecord in todayPKRecordList[::-1]:
+        _, winnerID = pkRecord
+        if playerID == winnerID:
+            break
+        cLoseCount += 1
+    cLoseBesureMatchRobot, besureMatchRobotCount = IpyGameDataPY.GetFuncEvalCfg("CrossRealmPKRobot", 2)
+    if cLoseCount >= cLoseBesureMatchRobot:
+        PyGameData.g_crossPKBesureMatchRobotInfo[playerID] = besureMatchRobotCount
+        GameWorld.DebugLog("连输X局必定连续匹配机器人Y局! playerID=%s,cLoseCount(%s) >= X(%s),Y(%s)" 
+                           % (playerID, cLoseCount, cLoseBesureMatchRobot, besureMatchRobotCount))
+        
+    matchRobotMaxRate = 100
+    
+    # 还有必定匹配机器人次数
+    nowBesureMatchRobotCount = PyGameData.g_crossPKBesureMatchRobotInfo.get(playerID, 0)
+    if nowBesureMatchRobotCount > 0:
+        matchRobotRate = matchRobotMaxRate
+        PyGameData.g_crossPKBesureMatchRobotInfo[playerID] = nowBesureMatchRobotCount - 1
+        GameWorld.DebugLog("玩家必定匹配机器人! playerID=%s,nowBesureMatchRobotCount=%s" % (playerID, nowBesureMatchRobotCount))
+        
+    if matchRobotRate and GameWorld.CanHappen(matchRobotRate, matchRobotMaxRate):
+        pkPlayer.notifyMatchRobotTick = tick + random.randint(3, 5) * 1000
+        PyGameData.g_crossPKZoneMatchRobotPlayerDict[playerID] = pkPlayer
+        GameWorld.DebugLog("玩家加入匹配: seasonID=%s,pkZoneID=%s,serverGroupID=%s,accID=%s,playerID=%s,pkScore=%s,fightPower=%s,cWinCount=%s" 
+                           % (seasonID, pkZoneID, serverGroupID, accID, playerID, pkScore, fightPower, cWinCount))
+        GameWorld.DebugLog("    本次匹配到机器人: danLV=%s,cLoseCount=%s,概率=%s" % (danLV, cLoseCount, matchRobotRate), playerID)
+        #这里优化下暂通知开始匹配,实际匹配到机器人做延迟通知
+        CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 1], [serverGroupID])
+        return
+        
     PyGameData.g_crossPKPlayerDict[playerID] = pkPlayer
     
     # 加入赛区匹配列表
     zoneMatchPlayerList.append(playerID)
     PyGameData.g_crossPKZoneMatchPlayerDict[pkZoneID] = zoneMatchPlayerList
     
-    GameWorld.DebugLog("玩家加入匹配: seasonID=%s,pkZoneID=%s,serverGroupID=%s,accID=%s,playerID=%s,pkScore=%s,fightPower=%s,cWinCount=%s,len(zoneMatchPlayerList)=%s" 
-                       % (seasonID, pkZoneID, serverGroupID, accID, playerID, pkScore, fightPower, cWinCount, len(zoneMatchPlayerList)))
+    GameWorld.DebugLog("玩家加入匹配: seasonID=%s,pkZoneID=%s,serverGroupID=%s,accID=%s,playerID=%s,pkScore=%s,fightPower=%s,cWinCount=%s,cLoseCount=%s,概率=%s,len(zoneMatchPlayerList)=%s" 
+                       % (seasonID, pkZoneID, serverGroupID, accID, playerID, pkScore, fightPower, cWinCount, cLoseCount, matchRobotRate, len(zoneMatchPlayerList)))
     
     CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 1], [serverGroupID])
+    return
+
+def __DelayNotifyMatchRobot(tick):
+    ## 做体验,延迟通知匹配到机器人
+    for playerID, pkPlayer in PyGameData.g_crossPKZoneMatchRobotPlayerDict.items():
+        if pkPlayer.notifyMatchRobotTick == -1:
+            #GameWorld.DebugLog("已通知过玩家匹配到机器人", playerID)
+            continue
+        if tick < pkPlayer.notifyMatchRobotTick:
+            continue
+        pkPlayer.notifyMatchRobotTick = -1
+        serverGroupID = pkPlayer.serverGroupID
+        GameWorld.DebugLog("延迟通知玩家匹配到机器人: serverGroupID=%s" % (serverGroupID), playerID)
+        CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 2], [serverGroupID])
+        
+    return
+
+def __DoTimeOutPlayerMatchRobot(matchTickSortList, matchPlayerIDList, tick):
+    ## 超时很久很久的玩家系统匹配机器人
+    if not matchPlayerIDList:
+        return
+    
+    matchRobotTimeoutInfo = IpyGameDataPY.GetFuncEvalCfg("CrossRealmPKRobot", 1)
+    if len(matchRobotTimeoutInfo) != 2:
+        return
+    matchRobotTick = random.randint(matchRobotTimeoutInfo[0], matchRobotTimeoutInfo[1]) * 1000 # 超时匹配机器人时间tick
+    
+    for matchPlayer in matchTickSortList:
+        
+        playerID = matchPlayer.playerID
+        if playerID not in matchPlayerIDList:
+            continue
+        
+        if tick - matchPlayer.matchTick < matchRobotTick:
+            #GameWorld.DebugLog("    i=%s,玩家未满足超时匹配机器人时间条件!" % (i))
+            break
+        
+        matchPlayerIDList.remove(playerID) # 这个列表为分区对应匹配中的玩家列表 PyGameData.g_crossPKZoneMatchPlayerDict[pkZoneID]
+        
+        PyGameData.g_crossPKZoneMatchRobotPlayerDict[playerID] = matchPlayer
+        matchPlayer.notifyMatchRobotTick = -1
+        serverGroupID = matchPlayer.serverGroupID
+        GameWorld.DebugLog("直接通知超时玩家匹配到机器人: serverGroupID=%s" % (serverGroupID), playerID)
+        CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKMatchReqRet, [playerID, 2], [serverGroupID])
     return
 
 def ClientServerMsg_PKCancel(playerInfoDict, tick):
@@ -958,6 +1087,9 @@
         DR_CrossReamlPK("CancelRoom", dataDict)
         break
     
+    if playerID in PyGameData.g_crossPKZoneMatchRobotPlayerDict:
+        PyGameData.g_crossPKZoneMatchRobotPlayerDict.pop(playerID)
+        GameWorld.DebugLog("    从匹配机器人队列中移除!")
     return
 
 def ClientServerMsg_PKPrepareOK(playerInfoDict, tick):
@@ -1036,7 +1168,8 @@
         
     return
 #
-#def TestAddMatch(tick, addCount, maxDanLV=None, isClear=False):
+#def TestAddMatch(addCount, maxDanLV=None, isClear=False):
+#    tick = GameWorld.GetGameWorld().GetTick()
 #    if isClear:
 #        PyGameData.g_crossPKPlayerDict = {}
 #        PyGameData.g_crossPKZoneMatchPlayerDict = {}
@@ -1046,8 +1179,11 @@
 #    ipyDataMgr = IpyGameDataPY.IPY_Data()
 #    if maxDanLV == None:
 #        maxDanLV = ipyDataMgr.GetCrossRealmPKDanCount() - 1
-#    for index in xrange(ipyDataMgr.GetCrossRealmPKZoneCount()):
-#        zoneIpyData = ipyDataMgr.GetCrossRealmPKZoneByIndex(index)
+#    crossZoneName = GameWorld.GetCrossZoneName()
+#    crossZoneList = IpyGameDataPY.GetIpyGameDataByCondition("CrossZonePK", {"CrossZoneName":crossZoneName}, True)
+#    if not crossZoneList:
+#        return
+#    for zoneIpyData in crossZoneList:
 #        pkZoneID = zoneIpyData.GetZoneID()
 #        
 #        addPlayerList = []
@@ -1096,6 +1232,8 @@
         return
     GameWorld.GetGameWorld().SetDict(processTickKey, tick)
     
+    # 延迟通知匹配到机器人的
+    __DelayNotifyMatchRobot(tick)
     # 处理超时的房间
     __DoCheckRoomTimeout(tick)
     # 通知已准备好的房间玩家可进入跨服
@@ -1106,10 +1244,13 @@
     
     # 每个赛区单独匹配
     for pkZoneID, matchPlayerIDList in PyGameData.g_crossPKZoneMatchPlayerDict.items():
-        matchPlayerCount = len(matchPlayerIDList)
-        if matchPlayerCount < 2:
-            #GameWorld.Log("匹配PK人数不足,不处理!pkZoneID=%s, 总人数:%s" % (pkZoneID, matchPlayerCount))
+        if not matchPlayerIDList:
+            #GameWorld.Log("没有玩家匹配PK,不处理!pkZoneID=%s" % (pkZoneID))
             continue
+        matchPlayerCount = len(matchPlayerIDList)
+#        if matchPlayerCount < 2:
+#            #GameWorld.Log("匹配PK人数不足,不处理!pkZoneID=%s, 总人数:%s" % (pkZoneID, matchPlayerCount))
+#            continue
         
         GameWorld.DebugLog("★★★★★★★★★★开始跨服PK匹配(pkZoneID=%s, 总人数:%s)★★★★★★★★★★" % (pkZoneID, matchPlayerCount))
         
@@ -1120,16 +1261,16 @@
             matchPlayerList.append(PyGameData.g_crossPKPlayerDict[matchPlayerID])
         # 按匹配时间、积分升序排序
         matchTickSortList = sorted(matchPlayerList, key=operator.attrgetter("matchTick"))
-        scoreSortList = sorted(matchPlayerList, key=operator.attrgetter("pkScore"))
+        #scoreSortList = sorted(matchPlayerList, key=operator.attrgetter("pkScore")) # 新匹配规则暂时用不到积分排序的
         
         matchPlayerVSList = [] # 成功匹配玩家对战列表
         
         # 优先匹配等待超时玩家
-        __DoMatch_OutTimePlayer(matchTickSortList, scoreSortList, outTimeTick, matchPlayerVSList, tick)
+        __DoMatchPlayer(matchTickSortList, matchPlayerVSList, maxGroupCnt, tick, outTimeTick)
         
         if len(matchPlayerVSList) < maxGroupCnt:
             # 再按积分段匹配玩家
-            __DoMatch_DanScorePlayer(scoreSortList, maxGroupCnt, matchPlayerVSList)
+            __DoMatchPlayer(matchTickSortList, matchPlayerVSList, maxGroupCnt, tick)
             
         # 给成功匹配的玩家非配对战房间
         matchPlayerVSList = matchPlayerVSList[:maxGroupCnt]
@@ -1137,185 +1278,153 @@
         GameWorld.DebugLog("==========匹配结束(总匹配队伍:%s)==========" % len(matchPlayerVSList))
         #GameWorld.DebugLog("crossPlayerIDList=%s" % PyGameData.g_crossPKPlayerDict.keys())
         #GameWorld.DebugLog("matchPlayerIDList=%s" % PyGameData.g_crossPKZoneMatchPlayerDict[pkZoneID])
+        
+        __DoTimeOutPlayerMatchRobot(matchTickSortList, matchPlayerIDList, tick)
     return
 
-
-def __DoMatch_OutTimePlayer(matchTickSortList, scoreSortList, outTimeTick, matchPlayerVSList, tick):
-    '''匹配超时玩家
-        匹配中的玩家按积分排序,最后一个默认匹配上一个,第一个默认匹配下一个,其他匹配前后积分差绝对值较小的一个
+def __DoMatchPlayer(matchTickSortList, matchPlayerVSList, maxGroupCnt, tick, outTimeTick=0):
+    ''' 匹配玩家
+    @param matchTickSortList: 按匹配时间升序排序后的匹配玩家列表
+    @param maxGroupCnt: 最大匹配组数
+    @param matchPlayerVSList: 已经匹配的PK组列表
+    @param outTimeTick: 超时tick设定,0为匹配非超时玩家
     '''
-    GameWorld.DebugLog(" ==优先匹配超时等待玩家==最大等待时间:%s, tick=%s" % (outTimeTick, tick))
-    GameWorld.DebugLog(" scoreSortListLen=%s" % len(scoreSortList))
-    for i, matchPlayer in enumerate(matchTickSortList):        
-        # 只有一个玩家
-        if len(scoreSortList) <= 1:
-            #GameWorld.DebugLog("    当前玩家数%s<=1,不再匹配!" % len(scoreSortList))
+    
+    matchPlayerCount = 0
+    danPlayerListDict = {}
+    for matchPlayer in matchTickSortList:
+        if outTimeTick and tick - matchPlayer.matchTick < outTimeTick:
+            # 未超时,不再匹配,因为只有一个玩家
             break
-        
-        if tick - matchPlayer.matchTick < outTimeTick:
-            #GameWorld.DebugLog("    i=%s,玩家未超时,不再匹配!" % (i))
-            break
-        
-        GameWorld.DebugLog("    i=%s,超时玩家, %s-%s=%s >= outTimeTick(%s)" 
-                           % (i, tick, matchPlayer.matchTick, tick - matchPlayer.matchTick, outTimeTick))
-        # 已经被匹配走了
-        if matchPlayer not in scoreSortList:
-            GameWorld.DebugLog("        已经被匹配走了!")
-            continue
-        
-        outTimeIndex = scoreSortList.index(matchPlayer)
-        # 最后一个默认匹配上一个
-        if outTimeIndex == len(scoreSortList) - 1: 
-            vsIndex = outTimeIndex - 1
-            GameWorld.DebugLog("        超时玩家积分排序索引%s,最后一个,默认匹配上一个索引%s!" % (outTimeIndex, vsIndex))
-        # 第一个默认匹配下一个
-        elif outTimeIndex == 0:
-            vsIndex = outTimeIndex + 1
-            GameWorld.DebugLog("        超时玩家积分排序索引%s,第一个,默认匹配下一个索引%s!" % (outTimeIndex, vsIndex))
-        # 其他情况匹配积分较近的一个
-        else:
-            preIndex = outTimeIndex - 1
-            nextIndex = outTimeIndex + 1
-            prePlayer = scoreSortList[preIndex]
-            nextPlayer = scoreSortList[nextIndex]
-            preDiff = abs(prePlayer.pkScore - matchPlayer.pkScore)
-            nextDiff = abs(matchPlayer.pkScore - nextPlayer.pkScore)
-            vsIndex = preIndex if preDiff <= nextDiff else nextIndex
-            GameWorld.DebugLog("        超时玩家积分排序索引-积分(%s-%s),上一个(%s-%s),下一个(%s-%s),preDiff=%s,nextDiff=%s,vsIndex=%s" 
-                               % (outTimeIndex, matchPlayer.pkScore, preIndex, prePlayer.pkScore, 
-                                  nextIndex, nextPlayer.pkScore, preDiff, nextDiff, vsIndex))
-            
-        if outTimeIndex > vsIndex: 
-            scoreSortList.pop(outTimeIndex)
-            vsPlayer = scoreSortList.pop(vsIndex)
-        elif outTimeIndex < vsIndex:
-            vsPlayer = scoreSortList.pop(vsIndex)
-            scoreSortList.pop(outTimeIndex)
-        else:
-            continue
-        
-        # 加入成功匹配列表
-        matchPlayerVSList.append([matchPlayer, vsPlayer])
-        
-    return
-
-def __DoMatch_DanScorePlayer(scoreSortList, maxGroupCnt, matchPlayerVSList):
-    ''' 匹配积分分段玩家
-            匹配中的玩家按段位积分归组,归组后,随机段位顺序,每个段位组中的玩家随机两两PK
-    '''
-    GameWorld.DebugLog(" ==匹配积分分段玩家== maxGroupCnt=%s,scoreSortListLen=%s" % (maxGroupCnt, len(scoreSortList)))
-    danPlayerListDict = {} # 按积分分段列表分散玩家
-    for matchPlayer in scoreSortList:
         danLV = matchPlayer.danLV
         danPlayerList = danPlayerListDict.get(danLV, [])
         danPlayerList.append(matchPlayer)
         danPlayerListDict[danLV] = danPlayerList
+        matchPlayerCount += 1
         
-    # 按分段玩家随机匹配
+    if outTimeTick:
+        GameWorld.DebugLog(" ==优先匹配超时等待玩家==最大等待时间:%s, matchPlayerCount=%s" % (outTimeTick, matchPlayerCount))
+    else:
+        GameWorld.DebugLog(" ==常规段位玩家== maxGroupCnt=%s,matchPlayerCount=%s" % (maxGroupCnt, matchPlayerCount))
+        
+    if matchPlayerCount < 2:
+        #GameWorld.DebugLog("    匹配玩家不足!不处理!matchPlayerCount=%s" % matchPlayerCount)
+        return
+    
     danList = danPlayerListDict.keys()
-    random.shuffle(danList) # 打乱段位顺序
+    random.shuffle(danList) # 打乱段位处理顺序
     
-    GameWorld.DebugLog("    积分分段个数: %s, %s" % (len(danList), danList))
+    matchProtectRound = IpyGameDataPY.GetFuncCfg("CrossRealmPKMatch2", 1) # 几局内不能匹配到同一个玩家
+    matchDanDiffList = IpyGameDataPY.GetFuncEvalCfg("CrossRealmPKMatch2", 2) # 初始匹配段位差|超时匹配段位差
+    matchDanDiff = matchDanDiffList[1] if outTimeTick else matchDanDiffList[0]
     
-    # 优先匹配相同段位
-    doCount = 0
-    while len(matchPlayerVSList) < maxGroupCnt and doCount < maxGroupCnt:
-        doCount += 1
-        isMatchOK = False
-#        # 日志输出分组明细
-#        GameWorld.DebugLog("    -------------")
-#        for danLV in danList:
-#            strList = []
-#            for player in danPlayerListDict[danLV]:
-#                strList.append((player.playerID, player.pkScore, player.fightPower))
-#            GameWorld.DebugLog("    积分段组, danLV=%s, %s" % (danLV, str(strList)))
-#        # -------------------------------
-        
-        for danLV in danList:
-            danPlayerList = danPlayerListDict[danLV]
-            danPlayerCount = len(danPlayerList)
-            if danPlayerCount < 2:
-                #GameWorld.DebugLog("    段位人数少于2个,不处理!doCount=%s,danLV=%s" % (doCount, danLV))
+    #GameWorld.DebugLog(" 匹配玩家数=%s,同对手匹配保护局数=%s,匹配段位差=%s,danList=%s" 
+    #                   % (matchPlayerCount, matchProtectRound, matchDanDiff, danList))
+    
+    for danLV in danList:
+        danPlayerList = danPlayerListDict[danLV]
+        lowDanPlayerList, highDanPlayerList = [], [] # 相对danLV的高低段位玩家需要分开处理,如果一起处理的话可能导致匹配到不应该匹配到的段位
+        for vsDanLV in xrange(max(0, danLV - matchDanDiff), danLV + matchDanDiff + 1):
+            if danLV == vsDanLV:
                 continue
-            
-            vsIndexList = random.sample(xrange(danPlayerCount), 2) # 随机取两个索引对战
-            vsIndexList.sort()
-            aPlayer = danPlayerList.pop(vsIndexList[1])
-            bPlayer = danPlayerList.pop(vsIndexList[0])
-            
-            matchPlayerVSList.append([aPlayer, bPlayer])
-            isMatchOK = True
-            GameWorld.DebugLog("    成功匹配相同段位玩家: aPlayerID=%s,aDanLV=%s VS bPlayerID=%s,bDanLV=%s" % (aPlayer.playerID, aPlayer.danLV, bPlayer.playerID, bPlayer.danLV))
-            
-            if len(matchPlayerVSList) >= maxGroupCnt:
-                GameWorld.DebugLog("    已经达到最大匹配数! 已匹配对战数=%s, 不再匹配!doCount=%s" % (len(matchPlayerVSList), doCount))
-                break
-            
-        if not isMatchOK:
-            GameWorld.DebugLog("    已经没有满足匹配条件的玩家! 不再匹配!doCount=%s" % (doCount))
-            break
-        
-    # 不足再匹配范围段位
-    doCount = 0
-    while len(matchPlayerVSList) < maxGroupCnt and doCount < maxGroupCnt:
-        doCount += 1
-        isMatchOK = False
-#        # 日志输出分组明细
-#        GameWorld.DebugLog("    -------------")
-#        for danLV in danList:
-#            strList = []
-#            for player in danPlayerListDict[danLV]:
-#                strList.append((player.playerID, player.pkScore, player.fightPower))
-#            GameWorld.DebugLog("    积分段组, danLV=%s, %s" % (danLV, str(strList)))
-#        # -------------------------------
-        
-        for danLV in danList:
-            danMatchRange = []
-            danMatchPlayerList = []
-            danIpyData = IpyGameDataPY.GetIpyGameData("CrossRealmPKDan", danLV)
-            matchDanRange = [] if not danIpyData else danIpyData.GetMatchRange()
-            if matchDanRange and len(matchDanRange) == 2:
-                danMatchRange = range(matchDanRange[0], matchDanRange[1] + 1)
-                
-            if danLV not in danMatchRange:
-                danMatchRange.append(danLV)
-                
-            for matchDanLV in danMatchRange:
-                if matchDanLV not in danPlayerListDict:
-                    continue
-                danMatchPlayerList += danPlayerListDict[matchDanLV]
-                
-            #matchPlayerIDList = [matchPlayer.playerID for matchPlayer in danMatchPlayerList]
-            #GameWorld.DebugLog("danLV=%s,danMatchRange=%s,matchPlayerIDList=%s" % (danLV, danMatchRange, matchPlayerIDList))
-            matchPlayerCount = len(danMatchPlayerList)
-            if matchPlayerCount < 2:
-                #GameWorld.DebugLog("    段位范围人数少于2个,不处理!doCount=%s,danLV=%s,danMatchRange=%s" % (doCount, danLV, danMatchRange))
+            if vsDanLV not in danPlayerListDict:
                 continue
-            
-            vsIndexList = random.sample(xrange(matchPlayerCount), 2) # 随机取两个索引对战
-            aPlayer, bPlayer = danMatchPlayerList[vsIndexList[0]], danMatchPlayerList[vsIndexList[1]]
-            
-            aDanPlayerList = danPlayerListDict.get(aPlayer.danLV, [])
-            bDanPlayerList = danPlayerListDict.get(bPlayer.danLV, [])
-            if aPlayer in aDanPlayerList and bPlayer in bDanPlayerList:
-                aDanPlayerList.remove(aPlayer)
-                bDanPlayerList.remove(bPlayer)
+            if vsDanLV < danLV:
+                lowDanPlayerList += danPlayerListDict[vsDanLV]
             else:
+                highDanPlayerList += danPlayerListDict[vsDanLV]
+                
+        #GameWorld.DebugLog(" danLV=%s,danPlayerCount=%s,lowPlayerCount=%s,highPlayerCount=%s" 
+        #                   % (danLV, len(danPlayerList), len(lowDanPlayerList), len(highDanPlayerList)))
+        
+        # 非超时的,优先匹配同段位玩家
+        if not outTimeTick:
+            __MatchDanPlayerList(matchTickSortList, matchPlayerVSList, danPlayerList, danPlayerListDict, matchProtectRound, maxGroupCnt)
+            
+        # 分别匹配低段位、高段位
+        __MatchDanPlayerList(matchTickSortList, matchPlayerVSList, danPlayerList + lowDanPlayerList, danPlayerListDict, matchProtectRound, maxGroupCnt)
+        __MatchDanPlayerList(matchTickSortList, matchPlayerVSList, danPlayerList + highDanPlayerList, danPlayerListDict, matchProtectRound, maxGroupCnt)
+        
+    return
+
+def __MatchDanPlayerList(matchTickSortList, matchPlayerVSList, matchPlayerList, danPlayerListDict, matchProtectRound, maxGroupCnt):
+    ## 执行匹配段位玩家列表
+    
+    matchPlayerCount = len(matchPlayerList)
+    if matchPlayerCount < 2:
+        return
+    random.shuffle(matchPlayerList) # 打乱匹配顺序,相当于随机两两分组,然后下面直接按顺序处理即可
+    #GameWorld.DebugLog("    总未匹配人数=%s,已匹配组数=%s,待匹配人数=%s" % (len(matchTickSortList), len(matchPlayerVSList), len(matchPlayerList)))
+    #for i, mPlayer in enumerate(matchPlayerList):
+    #    GameWorld.DebugLog("    i=%s,playerID=%s,danLV=%s" % (i, mPlayer.playerID, mPlayer.danLV))
+    #maxGroupCnt = 99999 # 测试批量匹配用
+    
+    nextIndex = 0
+    doCount = matchPlayerCount
+    # 至少需要两个  且 未达到最大成功匹配组数 且 限制最大可循环次数大于0
+    while nextIndex < len(matchPlayerList) - 1 and len(matchPlayerVSList) < maxGroupCnt and doCount > 0:
+        doCount -= 1
+        i = nextIndex
+        aPlayer = matchPlayerList[i]
+        nextIndex += 1
+        
+        aPlayerID = aPlayer.playerID
+        aDanLV = aPlayer.danLV
+        #if maxGroupCnt == 99999 and random.randint(1, 10) > 5:
+        #    GameWorld.DebugLog("        i=%s,aPlayerID=%s,aDanLV=%s 测试随机不匹配" % (i, aPlayerID, aDanLV))
+        #    continue
+        if aPlayer not in matchTickSortList:
+            #GameWorld.DebugLog("        i=%s,aPlayerID=%s,aDanLV=%s 已经被匹配走了" % (i, aPlayerID, aDanLV))
+            continue
+        aTodayPKRecordList = PyGameData.g_crossPKTodayPKRecordInfo.get(aPlayerID, [])
+        aMatchProtectPlayerIDList = [pkRecord[0] for pkRecord in aTodayPKRecordList[:-matchProtectRound - 1:-1]] # 最近X局匹配的玩家ID
+        #GameWorld.DebugLog("        i=%s,aPlayerID=%s,aMatchProtectPlayerIDList=%s" % (i, aPlayerID, aMatchProtectPlayerIDList))
+        
+        isMatchOK = False
+        for j, bPlayer in enumerate(matchPlayerList[nextIndex:], nextIndex):
+            bPlayerID = bPlayer.playerID
+            bDanLV = bPlayer.danLV
+            #if maxGroupCnt == 99999 and random.randint(1, 10) > 5:
+            #    GameWorld.DebugLog("            j=%s,bPlayerID=%s,bDanLV=%s 测试随机不匹配" % (j, bPlayerID, bDanLV))
+            #    continue
+            if bPlayer not in matchTickSortList:
+                #GameWorld.DebugLog("            j=%s,bPlayerID=%s,bDanLV=%s 已经被匹配走了" % (j, bPlayerID, bDanLV))
+                continue
+            if bPlayerID in aMatchProtectPlayerIDList:
+                GameWorld.DebugLog("            j=%s,bPlayerID=%s,bDanLV=%s %s局内不匹配同对手! bPlayerID=%s in aMatchProtectPlayerIDList=%s" 
+                                   % (j, bPlayerID, bDanLV, matchProtectRound, bPlayerID, aMatchProtectPlayerIDList))
                 continue
             
-            matchPlayerVSList.append([aPlayer, bPlayer])
+            bTodayPKRecordList = PyGameData.g_crossPKTodayPKRecordInfo.get(bPlayerID, [])
+            bMatchProtectPlayerIDList = [pkRecord[0] for pkRecord in bTodayPKRecordList[:-matchProtectRound - 1:-1]] # 最近X局匹配的玩家ID
+            if aPlayerID in bMatchProtectPlayerIDList:
+                GameWorld.DebugLog("            j=%s,bPlayerID=%s,bDanLV=%s %s局内不匹配同对手! aPlayerID=%s in bMatchProtectPlayerIDList=%s" 
+                                   % (j, bPlayerID, bDanLV, matchProtectRound, aPlayerID, bMatchProtectPlayerIDList))
+                continue
+            
+            matchTickSortList.remove(aPlayer)
+            matchTickSortList.remove(bPlayer)
+            
+            matchPlayerList.remove(aPlayer)
+            matchPlayerList.remove(bPlayer)
+            
+            aDanPlayerList = danPlayerListDict.get(aDanLV, [])
+            if aPlayer in aDanPlayerList:
+                aDanPlayerList.remove(aPlayer)
+            bDanPlayerList = danPlayerListDict.get(bDanLV, [])
+            if bPlayer in bDanPlayerList:
+                bDanPlayerList.remove(bPlayer)
+                
+            # 加入成功匹配列表
             isMatchOK = True
-            GameWorld.DebugLog("    成功匹配范围段位玩家: aPlayerID=%s,aDanLV=%s VS bPlayerID=%s,bDanLV=%s | danLV=%s,danMatchRange=%s" 
-                               % (aPlayer.playerID, aPlayer.danLV, bPlayer.playerID, bPlayer.danLV, danLV, danMatchRange))
-            
-            if len(matchPlayerVSList) >= maxGroupCnt:
-                GameWorld.DebugLog("    已经达到最大匹配数! 已匹配对战数=%s, 不再匹配!doCount=%s" % (len(matchPlayerVSList), doCount))
-                break
-            
-        if not isMatchOK:
-            GameWorld.DebugLog("    已经没有满足匹配条件的玩家! 不再匹配! doCount=%s" % (doCount))
+            matchPlayerVSList.append([aPlayer, bPlayer])
+            GameWorld.DebugLog("            i=%s,j=%s,aPlayerID=%s(danLV:%s) VS bPlayerID=%s(danLV:%s) 匹配成功!" 
+                               % (i, j, aPlayerID, aDanLV, bPlayerID, bDanLV))
             break
         
+        if isMatchOK:
+            nextIndex -= 1
+            
     return
 
 def __DoSetVSRoom(pkZoneID, matchPlayerVSList, tick):
@@ -1526,6 +1635,18 @@
     # 更新排行榜
     UpdateCrossPKBillboard(zoneID, seasonID, winner, loser)
     
+    # 更新今日PK记录
+    if winnerID not in PyGameData.g_crossPKTodayPKRecordInfo:
+        PyGameData.g_crossPKTodayPKRecordInfo[winnerID] = []
+    winnerPKRecordList = PyGameData.g_crossPKTodayPKRecordInfo[winnerID]
+    winnerPKRecordList.append([loserID, winnerID])
+    
+    if loserID not in PyGameData.g_crossPKTodayPKRecordInfo:
+        PyGameData.g_crossPKTodayPKRecordInfo[loserID] = []
+    loserPKRecordList = PyGameData.g_crossPKTodayPKRecordInfo[loserID]
+    loserPKRecordList.append([winnerID, winnerID])
+    #GameWorld.DebugLog("PyGameData.g_crossPKTodayPKRecordInfo=%s" % PyGameData.g_crossPKTodayPKRecordInfo)
+    
     timeStr = GameWorld.GetCurrentDataTimeStr()
     playerOverDict = {}
     # 通知客户端战斗结果
@@ -1574,6 +1695,165 @@
     DR_CrossReamlPK("PKOverRoom", dataDict)
     return
 
+def UpdatePKPlayerScore(roomID, pkPlayer, isWin):
+    ## 更新PK玩家积分
+    
+    playerID = pkPlayer.playerID
+    cWinCount = pkPlayer.cWinCount
+    pkScore = pkPlayer.pkScore
+    danLV = pkPlayer.danLV
+    dayScore = max(0, pkScore - pkPlayer.ondayScore)# 今日已获得积分,正积分
+    
+    GameWorld.DebugLog("roomID=%s,playerID=%s,isWin=%s,dayScore=%s,pkScore=%s,danLV=%s,cWinCount=%s" 
+                       % (roomID, playerID, isWin, dayScore, pkScore, danLV, cWinCount))
+    
+    pkDanIpyData = IpyGameDataPY.GetIpyGameData("CrossRealmPKDan", danLV)
+    if not pkDanIpyData:
+        GameWorld.ErrLog("跨服PK房间段位数据异常! roomID=%s,playerID=%s,danLV=%s" % (roomID, playerID, danLV))
+    
+    baseScoreList = IpyGameDataPY.GetFuncEvalCfg("CrossRealmPKScore", 2) # 胜负保底分
+    wBaseScore = baseScoreList[0] if len(baseScoreList) > 0 else 0
+    lBaseScore = baseScoreList[1] if len(baseScoreList) > 1 else 0
+    wExScore = eval(IpyGameDataPY.GetFuncCompileCfg("CrossRealmPKScore", 3)) # 胜方附加分
+    lExScore = 0
+    
+    if isWin:
+        addScore = wBaseScore + wExScore
+        pkPlayer.cWinCount += 1
+    else:
+        addScore = lBaseScore + lExScore
+        pkPlayer.cWinCount = 0
+        
+    dayMaxScore = IpyGameDataPY.GetFuncCfg("CrossRealmPKScore", 1) # 每日获得积分上限,0为不限制
+    if dayMaxScore and addScore:
+        addScore = min(dayMaxScore - dayScore, addScore)
+    pkPlayer.pkScore += addScore
+    
+    if pkDanIpyData and pkDanIpyData.GetLVUpScore() and pkPlayer.pkScore >= pkDanIpyData.GetLVUpScore():
+        pkPlayer.danLV += 1
+        
+    return addScore
+
+def ClientServerMsg_PKRobotOver(serverGroupID, playerInfoDict, tick):
+    ## 收到子服同步的PK机器人结算
+    
+    if not GameWorld.IsCrossServer():
+        GameWorld.ErrLog("非跨服服务器不处理跨服PK匹配请求!")
+        return
+    
+    playerID = playerInfoDict["playerID"] # 角色ID
+    isWinner = playerInfoDict["isWinner"] # 是否获胜
+    
+    if playerID not in PyGameData.g_crossPKZoneMatchRobotPlayerDict:
+        GameWorld.DebugLog("玩家没有匹配到机器人,无法结算PK机器人奖励!", playerID)
+        return
+    pkPlayer = PyGameData.g_crossPKZoneMatchRobotPlayerDict.pop(playerID)
+    if playerID in PyGameData.g_crossPKPlayerDict:
+        PyGameData.g_crossPKPlayerDict.pop(playerID)
+    zoneID = pkPlayer.pkZoneID
+    seasonID = pkPlayer.seasonID
+    
+    GameWorld.Log("机器人跨服PK结算: isWinner=%s,zoneID=%s,seasonID=%s,pkScore=%s,danLV=%s,cWinCount=%s" 
+                  % (isWinner, zoneID, seasonID, pkPlayer.pkScore, pkPlayer.danLV, pkPlayer.cWinCount), playerID)
+    
+    roomID = 0
+    addScore = UpdatePKPlayerScore(roomID, pkPlayer, isWinner)
+    pkScore = pkPlayer.pkScore
+    danLV = pkPlayer.danLV
+    cWinCount = pkPlayer.cWinCount
+    
+    GameWorld.Log("    更新: addScore=%s,pkScore=%s,danLV=%s,cWinCount=%s" % (addScore, pkScore, danLV, cWinCount), playerID)
+    
+    if isWinner:
+        winner, loser = pkPlayer, None
+    else:
+        winner, loser = None, pkPlayer
+        
+    # 更新排行榜
+    UpdateCrossPKBillboard(zoneID, seasonID, winner, loser)
+    
+    # PK机器人默认结果数据
+    overType = 0
+    roundWinnerIDList = []
+    notifyState = False
+    winnerID = winner.playerID if winner else 0
+    tagPlayerID = 0
+    tagPlayerName = ""
+    
+    timeStr = GameWorld.GetCurrentDataTimeStr()
+    playerOverDict = {}
+    playerOverDict[playerID] = [roomID, zoneID, seasonID, timeStr, overType, winnerID, roundWinnerIDList] \
+                                + [serverGroupID, pkScore, danLV, cWinCount, addScore, tagPlayerID, tagPlayerName, notifyState]
+                                
+    serverGroupIDList = [pkPlayer.serverGroupID]
+    GameWorld.DebugLog("同步子服战斗结果: seasonID=%s,timeStr=%s,roomID=%s,overType=%s,winnerID=%s,roundWinnerIDList=%s" 
+                       % (seasonID, timeStr, roomID, overType, winnerID, roundWinnerIDList))
+    # 同步子服
+    CrossRealmMsg.SendMsgToClientServer(ShareDefine.CrossServerMsg_PKOverInfo, playerOverDict, serverGroupIDList)
+    
+    if playerID not in PyGameData.g_crossPKTodayPKRecordInfo:
+        PyGameData.g_crossPKTodayPKRecordInfo[playerID] = []
+    pkRecordList = PyGameData.g_crossPKTodayPKRecordInfo[playerID]
+    pkRecordList.append([0, winnerID])
+    #GameWorld.DebugLog("PyGameData.g_crossPKTodayPKRecordInfo=%s" % PyGameData.g_crossPKTodayPKRecordInfo)
+    
+    # 记录流向
+    dataDict = {"zoneID":zoneID, "seasonID":seasonID, "pkPlayer":pkPlayer.GetDRInfo()}
+    DR_CrossReamlPK("PKOverRobot", dataDict)
+    return
+
+def _GMSetCrossPK(serverGroupID, msgData):
+    ## 收到子服GM同步的设置跨服PK数据
+    
+    if not GameWorld.IsCrossServer():
+        GameWorld.ErrLog("GMSetCrossPK非跨服服务器不处理该跨服GM请求!")
+        return
+    
+    zoneID = msgData["ZoneID"]
+    seasonID = msgData["SeasonID"]
+    playerInfoDict = msgData["PlayerInfo"]
+    
+    accID = playerInfoDict["accID"]
+    playerID = playerInfoDict["playerID"]
+    playerName = playerInfoDict["playerName"]
+    playerJob = playerInfoDict["playerJob"]
+    fightPower = playerInfoDict["fightPower"]
+    realmLV = playerInfoDict["realmLV"]
+    pkScore = playerInfoDict["pkScore"]
+    danLV = playerInfoDict["danLV"]
+    cWinCount = playerInfoDict["cWinCount"]
+    ondayScore = playerInfoDict["ondayScore"]
+    
+    zoneMatchPlayerList = PyGameData.g_crossPKZoneMatchPlayerDict.get(zoneID, [])
+    if playerID in zoneMatchPlayerList or playerID in PyGameData.g_crossPKZoneMatchRobotPlayerDict or playerID in PyGameData.g_crossPKZoneMatchRobotPlayerDict:
+        GameWorld.ErrLog("GMSetCrossPK玩家正在匹配中,无法设置该GM请求数据! playerID=%s,accID=%s" % (playerID, accID))
+        return
+    
+    pkPlayer = CrossPKPlayer()
+    pkPlayer.accID = accID
+    pkPlayer.playerID = playerID
+    pkPlayer.playerName = playerName
+    pkPlayer.playerJob = playerJob
+    pkPlayer.pkScore = pkScore
+    pkPlayer.danLV = danLV
+    pkPlayer.fightPower = fightPower
+    pkPlayer.realmLV = realmLV
+    pkPlayer.cWinCount = cWinCount
+    pkPlayer.ondayScore = ondayScore
+    pkPlayer.serverGroupID = serverGroupID
+    pkPlayer.pkZoneID = zoneID
+    pkPlayer.seasonID = seasonID
+    
+    # 更新排行榜
+    isOK = UpdateCrossPKBillboard(zoneID, seasonID, pkPlayer, None, True)
+    GameWorld.Log("GMSetCrossPK设置跨服PK榜单玩家数据成功: isOK=%s,zoneID=%s,seasonID=%s,pkScore=%s,danLV=%s,cWinCount=%s,accID=%s" 
+                  % (isOK, zoneID, seasonID, pkScore, danLV, cWinCount, accID), playerID)
+    
+    # 记录流向
+    dataDict = {"zoneID":zoneID, "seasonID":seasonID, "pkPlayer":pkPlayer.GetDRInfo()}
+    DR_CrossReamlPK("GMSet", dataDict)
+    return
+    
 ##================================== 以下是子服逻辑 ==========================================
 
 def OnGameServerInitOK():
@@ -1627,7 +1907,12 @@
     GameWorld.Log("    zoneID=%s,seasonID=%s,seasonState=%s,matchState=%s" % (zoneID, seasonID, seasonState, matchState))
     if not zoneID:
         return
-    
+    if not seasonID:
+        dbSeasonID = PlayerDBGSEvent.GetDBGSTrig_ByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonID)
+        if dbSeasonID:
+            GameWorld.ErrLog("    已经有分配赛季ID的暂定不能被置为0! dbSeasonID=%s" % dbSeasonID)
+            return
+        
     gameWorld = GameWorld.GetGameWorld()
     curSeasonState = gameWorld.GetDictByKey(ShareDefine.Def_Notify_WorldKey_CrossPKSeasonState)
     
@@ -1666,6 +1951,8 @@
     seasonStatePack.SeasonID = seasonID
     seasonStatePack.SeasonState = seasonState
     seasonStatePack.MatchState = matchState
+    seasonStatePack.CrossZoneName = GameWorld.GetCrossZoneName()
+    seasonStatePack.CrossZoneNameLen = len(seasonStatePack.CrossZoneName)
     playerManager = GameWorld.GetPlayerManager()
     for i in xrange(playerManager.GetPlayerCount()):
         curPlayer = playerManager.GetPlayerByIndex(i)
@@ -1681,14 +1968,23 @@
     if not curPlayer:
         return
     
+    if not result:
+        return
+    
     if result == -2:
         PlayerControl.NotifyCode(curPlayer, "CrossMatching17")
         return
     
+    startMatchPack = ChPyNetSendPack.tagGCCrossRealmPKStartMatch()
+    
     if result == 1:
         SetIsCrossPKMatching(curPlayer, 1)
-        NetPackCommon.SendFakePack(curPlayer, ChPyNetSendPack.tagGCCrossRealmPKStartMatch())
+        startMatchPack.IsRobot = 0
+    elif result == 2:
+        SetIsCrossPKMatching(curPlayer, 0)
+        startMatchPack.IsRobot = 1
         
+    NetPackCommon.SendFakePack(curPlayer, startMatchPack)    
     return
 
 ## 跨服匹配状态
@@ -1702,7 +1998,6 @@
 def CrossServerMsg_PKMatchResult(vsRoomDict):
     ## 跨服PK匹配结果
     curServerGroupID = GameWorld.GetServerGroupID()
-    actionType = ShareDefine.Def_CrossAction_PK
     mapPosList = IpyGameDataPY.GetFuncEvalCfg("CrossRealmPKMatch", 5)
     GameWorld.DebugLog("=== 收到PK匹配结果处理  === curServerGroupID=%s" % curServerGroupID)
     if not mapPosList:
@@ -1727,7 +2022,7 @@
             PlayerControl.SetVsRoomId(player, roomID, True)
             # 通知地图玩家匹配成功, 上传数据, 准备进入跨服服务器
             posX, posY = mapPosList[i] if len(mapPosList) > i else mapPosList[0]
-            CrossRealmPlayer.SendCrossRealmReg(player, actionType, mapID, mapID, 0, posX, posY)
+            CrossRealmPlayer.SendCrossRealmReg(player, ChConfig.Def_FBMapID_CrossRealmPK, mapID, mapID, 0, posX, posY)
             
     return
 
@@ -1769,11 +2064,12 @@
                     matchPlayer.NameLen = len(matchPlayer.PlayerName)
                     matchPlayer.Job = readyPlayerInfo["Job"]
                     matchPlayer.LV = readyPlayerInfo["LV"]
-                    matchPlayer.MaxHP = readyPlayerInfo["MaxHP"]
+                    matchPlayer.MaxHP = readyPlayerInfo["MaxHP"] % ShareDefine.Def_PerPointValue
+                    matchPlayer.MaxHPEx = readyPlayerInfo["MaxHP"] / ShareDefine.Def_PerPointValue
                     matchPlayer.MaxProDef = readyPlayerInfo["MaxProDef"]
                     break
                 
-            PlayerControl.SetCrossRealmState(player, 1)
+            PlayerControl.SetCrossMapID(player, ChConfig.Def_FBMapID_CrossRealmPK)
             SetIsCrossPKMatching(player, 0)
             
             # 通知匹配成功,可进入跨服
@@ -1816,7 +2112,7 @@
             GameWorld.DebugLog("    房间ID不同, playerID=%s" % (playerID))
             continue
         player.SetDict(ChConfig.Def_PlayerKey_IsLoginToMergeServer, 0)
-        PlayerControl.SetCrossRealmState(player, 0)
+        PlayerControl.SetCrossMapID(player, 0)
         
     return
 
@@ -1842,7 +2138,7 @@
             cnt += 1
             savaData += overInfoData.getBuffer()
                 
-        GameWorld.Log("SaveDBCrossPKUnNotifyOverInfo cnt :%s" % cnt)
+        GameWorld.Log("SaveDBCrossPKUnNotifyOverInfo cnt :%s len=%s" % (cnt, len(savaData)))
         return CommFunc.WriteDWORD(cntData, cnt) + savaData
     
     # 从数据库载入数据
@@ -1873,6 +2169,8 @@
         
         sendMapOverInfo = [roomID, zoneID, seasonID, timeStr, overType, winnerID, roundWinnerIDList, pkScore, danLV, cWinCount, addScore, tagPlayerID, tagPlayerName, notifyState]
         player = GameWorld.GetPlayerManager().FindPlayerByID(playerID)
+        if not player:
+            CrossRealmPlayer.DoOfflinePlayerExitCrossServer(playerID)
         if not player or PlayerControl.GetIsTJG(player):
             GameWorld.DebugLog("    玩家不在线 或脱机中,先缓存,玩家上线后再同步,playerID=%s" % (playerID))
             overInfoData = PyGameDataStruct.tagDBCrossPKUnNotifyOverInfo()
@@ -1907,7 +2205,7 @@
     overInfoData = PyDataManager.GetCrossPKUnNotifyOverInfoManager().GetPlayerUnNotifyOverInfo(playerID)
     if not overInfoData:
         return
-    PlayerControl.SetCrossRealmState(curPlayer, 0)
+    PlayerControl.SetCrossMapID(curPlayer, 0)
     PlayerControl.SetVsRoomId(curPlayer, 0)
     
     zoneID = overInfoData.ZoneID

--
Gitblit v1.8.0