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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# -*- 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.tjgLimitCnt = config.GetTJGLimitCnt()  # ÏÞÖÆÍÑ»úÊýÁ¿
        self.offTime = config.GetPlayerOffTime()    # »ñÈ¡ÏÂÏß¶à¾ÃµÄÍæ¼Òʱ¼ä
        self.lastTime = 0   # ¿ØÖÆÈÕÖ¾Êä³öƵÂÊ
        self.badRobotCnt = 0 # ÀúÊ·Òì³£ÍÑ»ú¹Ò¸öÊý
        
        self.ProcessFindTJGTime = 5
        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:
                    logging.debug( "self.tjgLimitCnt %s " % self.tjgLimitCnt )
                    # ÏÞÖÆÍÑ»ú¹ÒµÇ¼ÊýÁ¿, Ã»ÓÐʵʱµÄÍæ¼ÒÉÏÏߺó»á²¹ÊÕÒæ
                    if self.robotMgr.GetRobotCount() > self.tjgLimitCnt:
                        self.robotMgr.dbRobot.ClearToken()
                    
                    self.lastLoginTime = nowTime
                    logoningList = self.robotMgr.GetRobotAccIDList()    # ÔڵǼµÄ»úÆ÷ÈË
                    
                    tokenList = self.robotMgr.dbRobot.GetTokenList()
                    robotList = []
                    for i in xrange(len(tokenList)):
                        tokenInfo = tokenList.pop()
                        accID = tokenInfo[1]
                        if accID in logoningList:
                            print "ÕýÔڵǼÖÐ------", accID
                            continue
                        
                        lastTime = self.robotMgr.GetNoteLastTimeByAccID(accID)   # ÉÏÒ»´Î¼ÓÈë¶ÓÁеÄʱ¼ä
                        if lastTime != 0 and nowTime - lastTime < self.offTime:
                            # µÇ¼ÓÐÎÊÌâÔò½øÈëÅŶÓ
                            continue
                        robot = self.robotMgr.AddRobot(tokenInfo)
                        robotList.append(robot)
                        if i == 10:
                            # Ò»´ÎµÇ¼10¸öÍæ¼Ò
                            break
                        
                    for robot in robotList:
                        #logging.debug( "Run AI for Index:%d", index )
                        if not robot:
                            continue
                        
                        # Á¬½Ó-µÇ¼-ÔËÐÐAI
                        if not robot.IsConnected() and robot.GetReconnectCount() < 2:
                            robot.ReCreateRobot()
                            
                    
                for index in xrange(self.robotMgr.GetRobotCount()):
                    #logging.debug( "Run AI for Index:%d", index )
                    if index >= self.robotMgr.GetRobotCount():
                        # ProcessAI¿ÉÄÜ»áÇå³ýÁËrobot
                        break
                    try:
                        robot = self.robotMgr.GetRobot( index )
                    except:
                        # ÅжÏindex·À·¶²»µ½£¬¿ÉÄܶàÏß³ÌÒýÆð£¬´Ë´¦±¨´í½áÊøÑ­»·
                        break
                    if not robot:
                        continue
                    robot.GetAIMgr().ProcessAI()
                    
                if not self.lastLoginTime:
                    self.lastLoginTime = nowTime
                time.sleep( 0.02 )   # Ãë
                
                # ¶ÓÁÐÖÐÇåÀíÎÞЧµÄÍÑ»ú¹Ò, Ò»´ÎÖ»ÇåÀíÒ»¸ö
                for index in xrange(self.robotMgr.GetRobotCount()):
                    #logging.debug( "Run AI for Index:%d", index )
                    try:
                        robot = self.robotMgr.GetRobot( index )
                    except:
                        # ÅжÏindex·À·¶²»µ½£¬¿ÉÄܶàÏß³ÌÒýÆð£¬´Ë´¦±¨´í½áÊøÑ­»·
                        break
                    if not robot:
                        print "====ûÓлúÆ÷ÈË"
                        self.robotMgr.Remove(robot)
                        self.badRobotCnt += 1
                        break
 
                    if robot.GetNeedDestroy():
                        print "++++++±»´Ý»Ù"
                        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.__robotAccIDs = []
        self.dbRobot = dbRobot
        self.TeamMgr = {}
        
        self.LoginHistory = {}  # ¼Ç¼ÀúÊ·Ìí¼Óʱ¼ä {Õ˺Å:ʱ¼ä} µÇ¼ʧ°ÜÐè3·ÖÖӺ󷽿ɳ¢ÊÔ
        
        #Æô¶¯AIÏ̠߳   
        #config =  ConfigurationReader.ConfigIniReader.GetConfig()
        #AI_THREAD_NUM = config.GetAIThreadNum()
 
        th = AIThread(self, 0)
        th.start()
 
 
    def NoteHistory(self, accID):
        self.LoginHistory[accID] = time.time()
        
    def GetNoteLastTimeByAccID(self, accID):
        return self.LoginHistory.get(accID, 0)
 
 
    def GetRobotAccIDList(self):
        self.__robotAccIDs = []
        for robot in self.__robots:
            self.__robotAccIDs.append(robot.GetRobotConfig()[1])
        return self.__robotAccIDs
 
    def AddRobot(self, tokenInfo):
        
        self.LoginHistory[tokenInfo[1]] = time.time()   # Õ˺żÇ¼
        
        #´´½¨RobotʵÀý£¬¾ßÌåÏîĿʵÏÖÏàÓ¦µÄRobotBaseµÄ×ÓÀ࣬ÔÚÕâÀï´´½¨×ÓÀàµÄʵÀý
        logging.debug( "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 GetRobot(self, index ):
        #logging.debug( "GetRobot for %d" % index )
        
        return self.__robots[index]
        
    def Remove(self, robot):
        self.__robots.remove(robot)
        logging.info( "Remove robot Ê£Óà: %s"%len(self.__robots) )
        
        
    def DisconnectServer(self, robot ):
        
        accID = robot.GetPlayerInfo().GetAccID()
        logging.debug( "DisconnectServer for %s" % accID )
        
        #¶Ï¿ª·þÎñÆ÷
        robot.DestroyRobot()
        if robot in self.__robots:
            self.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