hxp
3 天以前 388823edfe6308cba6f76ca6dc4f20022c5cb2be
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
# -*- coding: GBK -*-
# ÓÃÓÚ¹ÜÀíËùÓлúÆ÷ÈË
# author: Alee
# Date: 2011.9.1
# history:  2011.9.1     Created
 
import logging
from ProjectBinding.ProjectRobot import ProjectRobot
import ConfigurationReader.RobotsConfigReader
import ConfigurationReader.ConfigIniReader 
from threading import Thread
import traceback
 
import time
 
class AIThread(Thread):
    def __init__(self, robotMgr, index):
        Thread.__init__(self, None, None, "AIThreadPy_%s"%index)
        self.robotMgr = robotMgr
        self.AIList = []
        #config =  ConfigurationReader.ConfigIniReader.GetConfig()
 
        self.lastTime = 0
        self.badRobotCnt = 0 # ÀúÊ·Òì³£ÍÑ»ú¹Ò¸öÊý
        
        config =  ConfigurationReader.ConfigIniReader.GetConfig()
        self.ProcessFindTJGTime = config.GetProcessFindTJGTime() #²éѯÊý¾Ý¿â¼ä¸ô
        self.lastLoginTime = 0
        
        
    def runThread(self):   
        logging.info( "thread %s start" % self.getName() )
 
        while True:
            try:
                nowTime = time.time()
                if self.lastLoginTime and nowTime - self.lastLoginTime > self.ProcessFindTJGTime:
                    self.lastLoginTime = nowTime
                    tokenList = self.robotMgr.dbRobot.GetTokenList()
                    robotList = []
                    for i in xrange(len(tokenList)):
                        tokenInfo = tokenList.pop()
                        robot = self.robotMgr.AddRobot(tokenInfo)
                        robotList.append(robot)
                        if i == 20:
                            # Ò»´ÎµÇ¼10¸öÍæ¼Ò
                            break
                        
                    for robot in robotList:
                        #logging.debug( "Run AI for Index:%d", index )
                        if not robot:
                            continue
                        
                        # Á¬½Ó-µÇ¼-ÔËÐÐAI
                        if not robot.IsConnected():
                            robot.ReCreateRobot()
                            
                if not self.lastLoginTime:
                    self.lastLoginTime = nowTime
                        
                for index in xrange(self.robotMgr.GetRobotCount()):
                    #logging.debug( "Run AI for Index:%d", index )
                    robot = self.robotMgr.GetRobot( index )
                    if not robot:
                        continue
                    robot.GetAIMgr().ProcessAI()
     
     
                time.sleep( 0.01 )   # Ãë
                
                # ¶ÓÁÐÖÐÇåÀíÎÞЧµÄÍÑ»ú¹Ò, Ò»´ÎÖ»ÇåÀíÒ»¸ö
                for index in xrange(self.robotMgr.GetRobotCount()):
                    #logging.debug( "Run AI for Index:%d", index )
                    robot = self.robotMgr.GetRobot( index )
                    if not robot:
                        self.robotMgr.Remove(robot)
                        self.badRobotCnt += 1
                    if robot.GetNeedDestroy():
                        logging.debug( "++++ GetNeedDestroy __peer:0x%08X " % (robot.GetPeerValue()) )
                        self.robotMgr.Remove(robot)
                        self.badRobotCnt += 1
                    break
                
                    # Á¬½Ó-µÇ¼-ÔËÐÐAI
                nowTime = time.time()  
                if nowTime - self.lastTime > 12:
                    print "ÍÑ»ú¹ÒÍæ¼ÒÊýÁ¿: %s - %s"%(self.robotMgr.GetRobotCount(), self.robotMgr.GetLoginOKRobotCount())
                    self.lastTime = nowTime
                    if self.badRobotCnt:
                        print "²Î¿¼-ÀúÊ·Òì³£ÍÑ»ú¹Ò´ÎÊý£º%s"%self.badRobotCnt
                    
            except Exception, e:
                logging.error( "AIThread: %s"%str(e) )
                logging.error( "AIThread: %s"%traceback.print_exc() )
                
    def run(self):
        runM = self.runThread
 
        runM()
 
        
 
class RobotMgr():
    
    def __init__(self, asioMgr, dbRobot):
        self.__asioMgr = asioMgr
        self.__robotNum = 0
        self.__robots = []
        self.dbRobot = dbRobot
        self.TeamMgr = {}
        
        #Æô¶¯AIÏ̠߳   
        #config =  ConfigurationReader.ConfigIniReader.GetConfig()
        #AI_THREAD_NUM = config.GetAIThreadNum()
 
        th = AIThread(self, 0)
        th.start()
 
    def AddRobot(self, tokenInfo):
 
        #´´½¨RobotʵÀý£¬¾ßÌåÏîĿʵÏÖÏàÓ¦µÄRobotBaseµÄ×ÓÀ࣬ÔÚÕâÀï´´½¨×ÓÀàµÄʵÀý
        #logging.info( "Create Robot index:%s....." % (tokenInfo,)  )
        robot = ProjectRobot( self.__asioMgr, tokenInfo )
        self.__robots.append( robot)
        return robot
            
    #»úÆ÷È˵Ä×ÜÊý            
    def GetRobotCount(self):
        return len(self.__robots)
    
    #ÒÑÁ¬½ÓÉÏ·þÎñÆ÷µÄ»úÆ÷È˵ÄÊýÁ¿
    def GetConnectedRobotCount(self):
        n = 0
        for robot in self.__robots:
            if robot.IsConnected():
                n += 1
        return n    
    
    #ÒѾ­µÇ¼³É¹¦µÄ»úÆ÷ÈËÊýÁ¿
    def GetLoginOKRobotCount(self):
        n = 0
        for robot in self.__robots:
            if robot.GetIsLoginOK():
                n += 1
            else:
                logging.debug( "!!!not login :0x%08X", robot.GetPeerValue())
        return n     
        
        
    def ConnectServer(self, index ):
        
        robot = self.GetRobot(index)
        if not robot:
            return False
 
        logging.debug( "ConnectServer for %d" % index )
        #´´½¨ÁËʵÀýÁË£¬ÕâʱֻÐèÒªÔÙ´ÎÁ¬½Ó¼´¿É
        robot.ReCreateRobot()
        return True
        
    def GetRobot(self, index ):
        #logging.debug( "GetRobot for %d" % index )
        
        return self.__robots[index]
        
    def Remove(self, robot):
        self.__robots.remove(robot)
        
        
    def DisconnectServer(self, robot ):
        
        accID = robot.GetPlayerInfo().GetAccID()
        logging.debug( "DisconnectServer for %s" % accID )
        
        #¶Ï¿ª·þÎñÆ÷
        robot.DestroyRobot()
        self.__robots.remove(robot)
    
    def StartAI(self, index ):
        logging.debug( "StartAI for %d" % index )
        
        robot = self.GetRobot(index)
        if not robot:
            return False
        
        #robotAIList = robot.GetRobotConfig()
        #robot.SetAIActive( robotAIList, True )
        
        
        
    def StopAI(self, index ):
        logging.debug( "StopAI for %d" % index )
        
        robot = self.GetRobot(index)
        if not robot:
            return False
        
        #robotAIList = robot.GetRobotConfig()
        #robot.SetAIActive( robotAIList, False )
        
#===============================================================================
#    def CalcTeam(self):
#        self.TeamMgr = {}
#        for robot in self.__robots:
#            teamID = robot.GetTeamID()
#            mapID = robot.GetMapID()
#            #{mapID:[×é¶ÓÍæ¼ÒÊý£¬ÓÐÍÑ»ú¶Ó³¤µÄÍæ¼ÒÊý£¬Ê£ÓàÍæ¼ÒÊý]}
#            if mapID not in self.TeamMgr:
#                self.TeamMgr[mapID] = [{}, {}]
#                
#            self.TeamMgr[mapID][0][teamID] = self.TeamMgr[mapID][0].get(teamID, 0) + 1
#            if robot.GetTeamMemberLV() != 2:
#                # Ö»¹ÜÀí¶Ó³¤ÊÇÍÑ»ú¹ÒÍæ¼Ò£¬±ÜÃâ±»¾Ü¾ø×é¶ÓµÄÇé¿ö
#                continue
#            self.TeamMgr[mapID][1][teamID] = robot
#        logging.debug("CalcTeam----%s"%self.TeamMgr)
#        # ×é¶ÓÉÏÏÞ4ÈË
#        maxTeamCnt = 4
#        spaceCnt = 0  # ×é¶Ó¿Õȱλ
#        for mapID, teamsInfo in self.TeamMgr:
#            for teamID in teamsInfo[1]:
#                spaceCnt += (maxTeamCnt - teamsInfo[0][teamID])
#                
#            
#            
#        return
#===============================================================================
    
__gRobotMgr = None
 
def CreateRobotMgr( asioMgr, dbRobot ):
    global __gRobotMgr
    if not __gRobotMgr:
        __gRobotMgr =  RobotMgr( asioMgr, dbRobot )
        
        
def GetRobotMgr():
    global __gRobotMgr
    return __gRobotMgr