def find_enemy_in_view(): # work through who we can see, looking for an enemy OurTeam = self.agent.Bot.botinfo["Team"] print "OurTeam:", print OurTeam Players = self.agent.Bot.view_players.values() for CurrentPlayer in Players: if CurrentPlayer["Team"] != OurTeam: # Turned KeepFocusOnID in to a tuple with the current_time as a timestamp FA self.CombatInfo.KeepFocusOnID = (CurrentPlayer["Id"], current_time()) self.CombatInfo.KeepFocusOnLocation = ( CurrentPlayer["Location"], current_time()) return 1
def was_hit(self): lsec = 2 # How many seconds to look back to isec = 0 # Number of seconds to inhibit consecutive was_hits now = current_time() def timefilter(item): (timestamp, command, value) = item if timestamp > now - lsec: return 1 else: return 0 # Filter the events from the last lsec seconds lastevents = filter(timefilter, self.events) if self.hit_timestamp > now - isec: # Update the last hit timestamp return 0 else: # Update the last hit timestamp self.hit_timestamp = now if len(lastevents) > 0: return 1 else: return 0
def driver(self, drive_collection = None, timestamp = current_time()): # The main loop that runs the agent if drive_collection == None: drive_collection = self.drive_collection if drive_collection.goal.ready(): return "drive_won" # Simple routine to test frequency def time_test(element, timestamp): if (element.frequency <= 0) or \ (element.frequency < (timestamp - element.last_fired)): ########################################################## # timestamp was just time, but this crashed (Sam, 14/2/5) # after the change it didn't crash but the things which # used it never fired! So changed > to < ########################################################## self.log.debug("Timetest 1") # print "Timetest 1" return 1 else: self.log.debug("Timetest 0") # print "Timetest 0" return 0 for element_list in drive_collection.elements: for element in element_list: self.log.debug( \ "Processing Drive Element - %s" % str(element.drive_name)) if time_test(element, timestamp) and element.ready(): self.log.debug( \ "Drive - %s is ready to run" % str(element.drive_name)) if self.schedule.run_drive(element.drive_name): self.log.debug("Drive - %s has 1+ items on the sched." % \ str(element.drive_name)) element.last_fired = timestamp else: self.log.debug("Drive - %s has no items on the sched." % \ str(element.drive_name)) self.log.debug("Adding drive_root to the sched.") element.drive_root.send( \ content = element.drive_root.make_content(), timestamp = timestamp) # print element.drive_root.make_content() # print vars(element.drive_root.make_content()) return 1 else: # We should put some debug stuff here self.log.debug( \ "Drive - %s inhibited or not ready" % \ str(element.drive_name)) # print element # If nothing happened, we have a problem self.log.error("All drives lost focus - ended or will not run") return "drive_lost"
def send(self, timestamp, content, timeout_interval = DEFAULT_VIEWTIME): self.agent.blackboard.add_item( content.make_bbitem(drive_name = self.drive_name, timeout = current_time() + DEFAULT_VIEWTIME, timestamp = timestamp))
def driver(self, drive_collection=None, timestamp=current_time()): # The main loop that runs the agent if drive_collection == None: drive_collection = self.drive_collection if drive_collection.goal.ready(): return "drive_won" # Simple routine to test frequency def time_test(element, timestamp): if (element.frequency <= 0) or \ (element.frequency < (timestamp - element.last_fired)): ########################################################## # timestamp was just time, but this crashed (Sam, 14/2/5) # after the change it didn't crash but the things which # used it never fired! So changed > to < ########################################################## self.log.debug("Timetest 1") # print "Timetest 1" return 1 else: self.log.debug("Timetest 0") # print "Timetest 0" return 0 for element_list in drive_collection.elements: for element in element_list: self.log.debug( \ "Processing Drive Element - %s" % str(element.drive_name)) if time_test(element, timestamp) and element.ready(): self.log.debug( \ "Drive - %s is ready to run" % str(element.drive_name)) if self.schedule.run_drive(element.drive_name): self.log.debug("Drive - %s has 1+ items on the sched." % \ str(element.drive_name)) element.last_fired = timestamp else: self.log.debug("Drive - %s has no items on the sched." % \ str(element.drive_name)) self.log.debug("Adding drive_root to the sched.") element.drive_root.send( \ content = element.drive_root.make_content(), timestamp = timestamp) # print element.drive_root.make_content() # print vars(element.drive_root.make_content()) return 1 else: # We should put some debug stuff here self.log.debug( \ "Drive - %s inhibited or not ready" % \ str(element.drive_name)) # print element # If nothing happened, we have a problem self.log.error("All drives lost focus - ended or will not run") return "drive_lost"
def make_bbitem(self, command, timeout, timestamp=None): if timestamp == None: timestamp = current_time() return bbitem(command=command, tag=self.tag, action=self.action, timestamp=timestamp, drive_name=self.drive_name, timeout=timeout, agent=self.agent)
def set_attacker(self): print "in set_attacker" #if self.CombatInfo.DamageDetails != None and has_damage_info_expired(): self.CombatInfo.DamageDetails = None def find_enemy_in_view(): # work through who we can see, looking for an enemy OurTeam = self.agent.Bot.botinfo["Team"] print "OurTeam:", print OurTeam Players = self.agent.Bot.view_players.values() for CurrentPlayer in Players: if CurrentPlayer["Team"] != OurTeam: # Turned KeepFocusOnID in to a tuple with the current_time as a timestamp FA self.CombatInfo.KeepFocusOnID = (CurrentPlayer["Id"], current_time()) self.CombatInfo.KeepFocusOnLocation = ( CurrentPlayer["Location"], current_time()) return 1 if len( self.agent.Bot.view_players ) == 0 or self.agent.Bot.botinfo == {}: #if botinfo is {}, we can't yet set anything return 1 else: # expire damage info if necessary FA if self.CombatInfo.DamageDetails != None and self.CombatInfo.has_damage_info_expired( ): self.CombatInfo.expire_damage_info() if self.CombatInfo.DamageDetails != None and self.CombatInfo.DamageDetails.has_key( "Instigator"): InstID = self.CombatInfo.DamageDetails["Instigator"] if self.agent.Bot.view_players.has_key(InstID): # set variables so that other commands will keep him in view # Turned KeepFocusOnID in to a tuple with the current_time as a timestamp FA self.CombatInfo.KeepFocusOnID = (InstID, current_time()) self.CombatInfo.KeepFocusOnLocation = ( self.agent.Bot.view_players[InstID]["Location"], current_time()) else: find_enemy_in_view() else: find_enemy_in_view() return 1
def followDrive(self): """Performes one loop through the drive collection. """ if (self.result != "drive_lost") and (self.result != "drive_won"): self.timestamp = current_time() self.blackboard.check_bb() self.result = self.driver(drive_collection=self.drive_collection, timestamp=self.timestamp) else: self.log.error("followDrive() called even though agent is done")
def followDrive(self): """Performes one loop through the drive collection. """ if (self.result != "drive_lost") and (self.result != "drive_won"): self.timestamp = current_time() self.blackboard.check_bb() self.result = self.driver(drive_collection = self.drive_collection, timestamp = self.timestamp) else: self.log.error("followDrive() called even though agent is done")
def proc_item(self, string): (cmd, varstring) = re.compile('\s+').split( string, 1 ) #\s is a special escape character, which matches any white-space, varstring will hold flags returned from regular expression creation (see sre.py) vars = re.compile('\{(.*?)\}').findall(varstring) var_dict = {} for var in vars: (attr, value) = re.compile('\s+').split(var, 1) var_dict[attr] = value if cmd == "DAM" or cmd == "PRJ": var_dict["timestamp"] = current_time() return (cmd, var_dict)
def make_bbitem(self, command, timeout, timestamp = None): if timestamp == None: timestamp = current_time() return bbitem(command = command, tag = self.tag, action = self.action, timestamp = timestamp, drive_name = self.drive_name, timeout = timeout, agent = self.agent)
def check_bb(self, timeout_interval = DEFAULT_VIEWTIME): now = current_time() # Get and store the time now temp_stack = [] # The temp stack to put items self.__bb.sort() # Sorting the bb pretty much reverses it self.__bb_rp.sort() # This cleans expired items the normal bb deleted = 0 for i in range(len(self.__bb)): try: itemtimeout = self.__bb[i][0] if itemtimeout > 0 and itemtimeout < now: #pass del(self.__bb[i + deleted]) deleted += 1 elif itemtimeout >= now: break except: pass #Should raise error deleted = 0 # This cleans expired items the request/pending bb for i in range(len(self.__bb_rp)): try: (itemtimeout, item) = self.__bb_rp[i] if itemtimeout > 0 and itemtimeout < now: self.add_item(Bbitem(command = "cancel", action = item.action, drive_name = item.drive_name, value = item.value, timeout = now + timeout_interval, agent = item.agent)) del(self.__bb_rp[i + deleted]) deleted += 1 elif itemtimeout >= now: break except: pass # Should raise error # Now process each request/pending item for (itemtimeout, item) in self.__bb_rp: item.schedule_item(timestamp = now) # And reset the request/pending board self.__bb_rp = [] # Now everything is done. Reverse the bb to make searching # prereqs faster self.__bb.reverse()
def check_bb(self, timeout_interval=DEFAULT_VIEWTIME): now = current_time() # Get and store the time now temp_stack = [] # The temp stack to put items self.__bb.sort() # Sorting the bb pretty much reverses it self.__bb_rp.sort() # This cleans expired items the normal bb deleted = 0 for i in range(len(self.__bb)): try: itemtimeout = self.__bb[i][0] if itemtimeout > 0 and itemtimeout < now: #pass del (self.__bb[i + deleted]) deleted += 1 elif itemtimeout >= now: break except: pass #Should raise error deleted = 0 # This cleans expired items the request/pending bb for i in range(len(self.__bb_rp)): try: (itemtimeout, item) = self.__bb_rp[i] if itemtimeout > 0 and itemtimeout < now: self.add_item( Bbitem(command="cancel", action=item.action, drive_name=item.drive_name, value=item.value, timeout=now + timeout_interval, agent=item.agent)) del (self.__bb_rp[i + deleted]) deleted += 1 elif itemtimeout >= now: break except: pass # Should raise error # Now process each request/pending item for (itemtimeout, item) in self.__bb_rp: item.schedule_item(timestamp=now) # And reset the request/pending board self.__bb_rp = [] # Now everything is done. Reverse the bb to make searching # prereqs faster self.__bb.reverse()
def receive_pth_details(self, ValuesDict): if not ValuesDict.has_key("ID"): return elif ValuesDict["ID"] == self.PathHomeID: self.PosInfo.PathHome = utilityfns.nav_point_dict_to_ordered_list( ValuesDict) elif ValuesDict["ID"] == self.PathToEnemyBaseID: self.PosInfo.PathToEnemyBase = utilityfns.nav_point_dict_to_ordered_list( ValuesDict) # if there's no 0 key we're being given an empty path, so set TooCloseForPath to the current time # so that we can check how old the information is later on if not ValuesDict.has_key("0"): self.PosInfo.TooCloseForPath = current_time() else: self.PosInfo.TooCloseForPath = 0
def proc_sync(self, command, values): if command == "SLF": #info about bot's state self.s_botinfo = values # Keep track of orientation so we can tell when we are moving # Yeah, we only need to know the Yaw self.rotation_hist.append( int(re.search(',(.*?),', values['Rotation']).group(1))) # Trim list to 3 entries if len(self.rotation_hist) > 3: del (self.rotation_hist[0]) # Keep track of velocity so we know when we are stuck self.velocity_hist.append(self.calculate_velocity( \ values['Velocity'])) # Trim it to 20 entries if len(self.velocity_hist) > 20: del (self.velocity_hist[0]) elif command == "GAM": #info about the game self.s_gameinfo = values elif command == "PLR": #another character visible # For some reason, this doesn't work in ut2003 self.s_view_players[values["Id"]] = values elif command == "NAV": #a path marker # Neither does this #print "We have details about a nav point at " + values["Location"] self.s_nav_points[values["Id"]] = values elif command == "INV": #an object on the ground that can be picked up #print values self.s_view_items[values["Id"]] = values elif command == "FLG": #info about a flag #pass these details to the movement behaviour as that stores details of locations etc and may need them values["timestamp"] = current_time() print "\n".join(["%s=%s" % (k, v) for k, v in values.items()]) self.agent.Movement.receive_flag_details(values) # inform the combat behaviour as well self.agent.Combat.receive_flag_details(values) #print("We have details about a flag. Its values is: " + values["State"]); else: pass
def has_too_close_for_path_expired(self, lsecs=10): if self.TooCloseForPath < current_time() - lsecs: return 1 return 0
def _loop_thread(self): if self.checkError(300) > 0: self.log.error( \ "Agent behavior is not ready and timed out. Stop execute.") return False ### For profiling # counter2 = 0 ### For Hertz Counter ### counter = 0 last_sec = int(current_time()) if self.drive_collection.realtime: # Real-Time timestamps result = None # self.log.error("here!") while (result != "drive_lost") and (result != "drive_won") and \ self._exec_loop and self.checkError(0) == 0: # check for pause if self._loop_pause: # check ever 10th of a second while self._loop_pause: time.sleep(0.1) # check if stopLoop was called if not self._exec_loop: break timestamp = current_time() ################################ #counter2 += 1 #if counter2 > 10000: # For Profiling # self.exit() ################################ # For Hz Counter counter += 1 if int(timestamp) != last_sec: last_sec = int(timestamp) hertz = counter counter = 0 self.log.debug("RT Hertz (Approx.)- %s" % repr(hertz)) self.log.debug("BB Length - %s" % \ str(len(self.blackboard._Blackboard__bb))) self.log.debug("Sched Length - %s" % \ str(len(self.schedule._Schedule__schedule))) ################################ self.log.debug( \ "New RT Execute Run at - %s" % repr(timestamp)) self.blackboard.check_bb() result = self.driver(drive_collection = self.drive_collection, timestamp = timestamp) ### To limit Hz if self.driver_delay and self.delay_multiplier: if not (counter % self.delay_multiplier): time.sleep(self.driver_delay) else: # Incremented Timestamps timestamp = 0 result = None while (result != "drive_lost") and (result != "drive_won") and \ self._exec_loop and self.checkError(0) == 0: # check for pause if self._loop_pause: # check ever 10th of a second while self._loop_pause: time.sleep(0.1) # check if stopLoop was called if not self._exec_loop: break #self._exec_loop and self.bot.conn_ready: # was and timestamp = timestamp + 1 ################################ #counter2 += 1 #if counter2 > 10000: # For Profiling # self.exit() ################################ # For Hz Counter now = current_time() counter += 1 if int(now) != last_sec: last_sec = int(now) hertz = counter counter = 0 self.log.debug("Iter. Hertz (Approx.)- %s" % repr(hertz)) self.log.debug("BB Length - %s" % \ str(len(self.blackboard._Blackboard__bb))) self.log.debug("Sched Length - %s" % \ str(len(self.schedule._Schedule__schedule))) ################################ self.log.debug( \ "New Iterative Execute Run at - %s" % repr(timestamp)) self.blackboard.check_bb() result = self.driver(drive_collection = self.drive_collection, timestamp = timestamp) ### To limit Hz if self.driver_delay and self.delay_multiplier: if not (counter % self.delay_multiplier): time.sleep(self.driver_delay) self.log.info("Life Ended: Result - %s" % str(result)) return result
def send(self, timestamp, content, timeout_interval=DEFAULT_VIEWTIME): self.agent.blackboard.add_item( content.make_bbitem(drive_name=self.drive_name, timeout=current_time() + DEFAULT_VIEWTIME, timestamp=timestamp))
def trigger(self): return self.fire(current_time())
def _loop_thread(self): if self.checkError(300) > 0: self.log.error( \ "Agent behavior is not ready and timed out. Stop execute.") return False ### For profiling # counter2 = 0 ### For Hertz Counter ### counter = 0 last_sec = int(current_time()) if self.drive_collection.realtime: # Real-Time timestamps result = None # self.log.error("here!") while (result != "drive_lost") and (result != "drive_won") and \ self._exec_loop and self.checkError(0) == 0: # check for pause if self._loop_pause: # check ever 10th of a second while self._loop_pause: time.sleep(0.1) # check if stopLoop was called if not self._exec_loop: break timestamp = current_time() ################################ #counter2 += 1 #if counter2 > 10000: # For Profiling # self.exit() ################################ # For Hz Counter counter += 1 if int(timestamp) != last_sec: last_sec = int(timestamp) hertz = counter counter = 0 self.log.debug("RT Hertz (Approx.)- %s" % repr(hertz)) self.log.debug("BB Length - %s" % \ str(len(self.blackboard._Blackboard__bb))) self.log.debug("Sched Length - %s" % \ str(len(self.schedule._Schedule__schedule))) ################################ self.log.debug( \ "New RT Execute Run at - %s" % repr(timestamp)) self.blackboard.check_bb() result = self.driver(drive_collection=self.drive_collection, timestamp=timestamp) ### To limit Hz if self.driver_delay and self.delay_multiplier: if not (counter % self.delay_multiplier): time.sleep(self.driver_delay) else: # Incremented Timestamps timestamp = 0 result = None while (result != "drive_lost") and (result != "drive_won") and \ self._exec_loop and self.checkError(0) == 0: # check for pause if self._loop_pause: # check ever 10th of a second while self._loop_pause: time.sleep(0.1) # check if stopLoop was called if not self._exec_loop: break #self._exec_loop and self.bot.conn_ready: # was and timestamp = timestamp + 1 ################################ #counter2 += 1 #if counter2 > 10000: # For Profiling # self.exit() ################################ # For Hz Counter now = current_time() counter += 1 if int(now) != last_sec: last_sec = int(now) hertz = counter counter = 0 self.log.debug("Iter. Hertz (Approx.)- %s" % repr(hertz)) self.log.debug("BB Length - %s" % \ str(len(self.blackboard._Blackboard__bb))) self.log.debug("Sched Length - %s" % \ str(len(self.schedule._Schedule__schedule))) ################################ self.log.debug( \ "New Iterative Execute Run at - %s" % repr(timestamp)) self.blackboard.check_bb() result = self.driver(drive_collection=self.drive_collection, timestamp=timestamp) ### To limit Hz if self.driver_delay and self.delay_multiplier: if not (counter % self.delay_multiplier): time.sleep(self.driver_delay) self.log.info("Life Ended: Result - %s" % str(result)) return result
def trigger(self): return self.fire(current_time()) #
def has_projectile_details_expired(self, lsecs=2): if self.ProjectileDetails != None and self.ProjectileDetails[ "timestamp"] < (current_time() - lsecs): return 1 return 0
def has_focus_location_expired(self, lsecs=15): if self.KeepFocusOnLocation != None: (location, timestamp) = self.KeepFocusOnLocation if timestamp < (current_time() - lsecs): return 1 return 0
def has_focus_id_expired(self, lsecs=15): if self.KeepFocusOnID != None: (ID, timestamp) = self.KeepFocusOnID if timestamp < (current_time() - lsecs): return 1 return 0
def has_damage_info_expired(self, lsecs=5): if self.DamageDetails != None and self.DamageDetails["timestamp"] < ( current_time() - lsecs): return 1 return 0
def connect_thread(self): self.kill_connection = 0 try: self.sockobj = socket(AF_INET, SOCK_STREAM) self.sockobj.connect((self.ip, int(self.port))) self.sockin = self.sockobj.makefile('r') self.sockout = self.sockobj.makefile('w') except: self.log.error("Connection to server failed") self.kill_connection = 1 # Skip the read loops else: self.log.error("Connected to server") self.kill_connection = 0 # This loop waits for the first NFO message while not self.kill_connection: try: x = self.sockin.readline() except: self.log.error("Connection Error on readline()") self.kill_connection = 1 break if not x: self.log.error("Connection Closed from Remote End") self.kill_connection = 1 break #print x (cmd, dict) = self.proc_item(x) if cmd == "NFO": # Send INIT message self.conninfo = dict self.send_message("INIT", { "Name": self.botname, "Team": self.team }) self.conn_ready = 1 # Ready to send messages break # Now the main loop # Not everything is implemented. Just some basics while not self.kill_connection: try: x = self.sockin.readline() except: self.log.error("Connection Error on readline()") break if not x: self.log.error("Connection Closed from Remote End") break #print "R>> " + str(self) + x (cmd, dict) = self.proc_item(x) sync_states = ("SLF", "GAM", "PLR", "NAV", "MOV", "DOM", "FLG", "INV") events = ("WAL", "BMP") self.msg_log.append((cmd, dict)) if cmd == "BEG": # When a sync batch is arriving, make sure the shadow # states are cleared self.s_gameinfo = {} self.s_view_players = {} self.s_view_items = {} self.s_nav_points = {} self.s_botinfo = {} elif cmd in sync_states: # These are sync. messages, handle them with another method self.proc_sync(cmd, dict) elif cmd == "END": # When a sync batch ends, we want to make the shadow # states that we were writing to to be the real one self.gameinfo = self.s_gameinfo self.view_players = self.s_view_players self.view_items = self.s_view_items self.nav_points = self.s_nav_points self.botinfo = self.s_botinfo # Also a good time to trim the events list # Only keep the last 50 events self.events = self.events[-50:] self.msg_log = self.msg_log[-1000:] elif cmd in events: # The bot hit a wall or an actor, make a note # of it in the events list with timestamp self.events.append((current_time(), cmd, dict)) elif cmd == "SEE": # Update the player positions self.view_players[dict["Id"]] = dict elif cmd == "PTH": # pass the details to the movement behaviour self.agent.Movement.receive_pth_details(dict) elif cmd == "RCH": self.agent.Movement.receive_rch_details(dict) elif cmd == "PRJ": # incoming projectile self.agent.Combat.receive_prj_details(dict) elif cmd == "DAM": # damage taken self.agent.Combat.receive_dam_details(dict) elif cmd == "KIL": # some other player died self.agent.Combat.receive_kil_details(dict) elif cmd == "DIE": # this player died self.agent.Combat.receive_die_details(dict) else: pass self.log.info("Closing Sockets and Cleaning Up...") try: self.sockout.flush() self.sockout.close() self.sockin.close() self.sockobj.close() except: self.log.error("Error closing files and sockets") self.thread_active = 0 self.conn_ready = 0 self.conn_thread_id = None self.log.info("Connection Thread Terminating...")
def has_our_flag_info_expired(self, lsecs=10): if self.OurFlagInfo != {} and self.OurFlagInfo.has_key("Reachable"): if self.OurFlagInfo["timestamp"] < current_time() - lsecs: return 1 return 0