Esempio n. 1
0
    def get_flanking_coordinates(self, reference_position, flanked_position,
                                 firing_distance, action):
        """ Caluclate bot, left and rught flanking coordiantes. """
        distance = (reference_position - flanked_position)
        right_normalized = Vector2(-distance.y, distance.x).normalized()
        left_normalized = Vector2(distance.y, -distance.x).normalized()
        front_normalized = Vector2(distance.x, distance.y).normalized()
        # calcualte flanked distance

        front = front_normalized * (distance.length() -
                                    (firing_distance *
                                     (action.kwargs["flanking_distance"])))
        # always a little bit on the left/right than in front so + 0.1
        right = right_normalized * (firing_distance *
                                    (0.2 + action.kwargs["flanking_distance"]))
        left = left_normalized * (firing_distance *
                                  (0.2 + action.kwargs["flanking_distance"]))

        if action.action_type == Action.ActionType.PREPARE_FLANKING_RIGHT:
            return [
                reference_position - front * 0.75 - right,
                reference_position - front - right
            ]
        elif action.action_type == Action.ActionType.PREPARE_FLANKING_LEFT:
            return [
                reference_position - front * 0.75 - left,
                reference_position - front - left
            ]
        return None
Esempio n. 2
0
    def createShortFlankingPath(self,botPos,target):
        # if they have same x then they differ in the y coordinate thus the one is up and the other is down :P
        if(abs(botPos.x - target.x)<=abs(botPos.y - target.y)):
            # relative positions between bot and target
            # its either up and down or right and left, depending on that the capper
            # approaches in a different way
            upDown = True
            # 1 or -1 depending on the scoring pos and enemy flag spawn pos
            # want to know if we are going up or down the x or y coords when going to flag or back
            # in order to build the path
            middlesign = self.getSign(botPos.y,target.y)
        else:
            upDown = False
            middlesign = self.getSign(botPos.x,target.x)
        middle = botPos.midPoint(target)
        if (not upDown):
            # find closest side
            if self.level.height - botPos.y > self.level.height/2:
                path = [
                        self.commander.level.findNearestFreePosition(Vector2(middle.x - (middlesign*middle.x)/2,5)),
                         self.commander.level.findNearestFreePosition(Vector2(middle.x,5)),
                         self.commander.level.findNearestFreePosition(Vector2(middle.x + (middlesign*middle.x)/2,5)),
                         target,
                         self.commander.level.findRandomFreePositionInBox([target-2.5,target+2.5])
                         ]
            else:
                path = [ self.commander.level.findNearestFreePosition(Vector2(middle.x - (middlesign*middle.x)/2,self.level.height-5)),
                         self.commander.level.findNearestFreePosition(Vector2(middle.x,self.level.height-5)),
                         self.commander.level.findNearestFreePosition(Vector2(middle.x + (middlesign*middle.x)/2,self.level.height-5)),
                         target,
                         self.commander.level.findRandomFreePositionInBox([target-2.5,target+2.5])
                        ]
        else:
            # find closest side
            if self.level.width - botPos.x > self.level.width/2:
                    path = [ self.commander.level.findNearestFreePosition(Vector2(5,middle.y - (middlesign*middle.y)/2)),
                         self.commander.level.findNearestFreePosition(Vector2(5,middle.y)),
                         self.commander.level.findNearestFreePosition(Vector2(5,middle.y + (middlesign*middle.y)/2)),
                         target,
                         self.commander.level.findRandomFreePositionInBox([target-2.5,target+2.5])
                    ]
            else:
                path = [self.commander.level.findNearestFreePosition(Vector2(self.level.width-5,middle.y - (middlesign*middle.y)/2)),
                         self.commander.level.findNearestFreePosition(Vector2(self.level.width-5,middle.y)),
                         self.commander.level.findNearestFreePosition(Vector2(self.level.width-5,middle.y + (middlesign*middle.y)/2)),
                         target,
                         self.commander.level.findRandomFreePositionInBox([target-2.5,target+2.5])
                    ]
        # in case the capper has picked the flag from a fallen capper and the flag is near
        # the scoring base then it is better to approach straight away
        while True:
            if botPos.squaredDistance(path[0]) > botPos.squaredDistance(path[-1]):
                path = [path[-1]]
                break
            elif len(path) > 2 and Vector2.distance(botPos,path[-1]) < Vector2.distance(path[0],path[-1]):
                path.pop(0)
            else:
                break

        return path
Esempio n. 3
0
    def moveOrFace(self, bot):
        enemyFlagLocation = self.game.enemyTeam.flag.position

        # defend the flag!
        targetPosition = self.game.team.flagScoreLocation
        targetMin = targetPosition - Vector2(8.0, 8.0)
        targetMax = targetPosition + Vector2(8.0, 8.0)
        if bot.flag:
            #bring it hooome
            targetLocation = self.game.team.flagScoreLocation
            self.issue(commands.Charge,
                       bot,
                       targetLocation,
                       description='returning enemy flag!')
        else:
            if (targetPosition - bot.position).length() > 9.0 and (
                    targetPosition - bot.position).length() > 3.0:
                while True:
                    position = self.level.findRandomFreePositionInBox(
                        (targetMin, targetMax))
                    if position and (targetPosition - position).length() > 3.0:
                        #self.issue(commands.Move, bot, position, description = 'defending around flag')
                        self.issue(commands.Attack,
                                   bot,
                                   position,
                                   description='defending around flag',
                                   lookAt=enemyFlagLocation)
                        break
            else:
                self.issue(commands.Defend,
                           bot, (enemyFlagLocation - bot.position),
                           description='defending facing flag')
Esempio n. 4
0
def getPathWithPathDistanceMap(start, end, mapData, finishWhenFoundPath = True):
    sq2 = math.sqrt(2)
    w = len(mapData)
    h = len(mapData[0])
    distance =[ [(0) for y in range(h)] for x in range(w)]
    parent =[ [None for y in range(h)] for x in range(w)]
    queue = PriorityQueue()
    xstart = int(start.x)
    ystart = int(start.y)
    xend = int(end.x)
    yend = int(end.y)

    def heuristic(x0,y0, x1,y1):
        return math.sqrt((x0-x1)*(x0-x1)+(y0-y1)*(y0-y1))

    def checkPos(d, x, y, dx ,dy, delta):
        x1 =x+dx
        y1 = y+dy
        result = False
        if (x1<0  or x1>=w or y1<0 or y1>=h):
            return False
        fullDistance = d+delta*(mapData[x][y])
        if (mapData[x1][y1]!=-1) and (parent[x1][y1]==None or distance[x1][y1]>fullDistance):
            parent[x1][y1] = (x,y)
            distance[x1][y1] = fullDistance
            heursticD = fullDistance+heuristic(x,y,x1,y1)
            queue._put((heursticD, (x1,y1)))

            if ((x1==xend) and (y1==yend)):
                result = True
        return result

    pathFounded = False
    if checkPos(0, xstart,ystart, 0,0, 0) and finishWhenFoundPath:
        return [Vector2(x+0.5,y+0.5)], distance, parent
    while queue._qsize()>0:
        prior,pos = queue._get()
        x,y=pos
        d = distance[x][y]
        if (checkPos(d, x,y, 1,0, 1) or checkPos(d, x,y, -1,0, 1) or checkPos(d, x,y, 0,1, 1) or checkPos(d, x,y, 0,-1, 1) or
            checkPos(d, x,y, 1,1, sq2) or checkPos(d, x,y, -1,1, sq2) or checkPos(d, x,y, 1,-1, sq2) or checkPos(d, x,y, -1,-1, sq2)):
            pathFounded = True
            if (finishWhenFoundPath):
                break
    result = []
    if pathFounded:
        x = xend
        y = yend
            
        while (parent[x][y]!=(x,y)):
            result.append(Vector2(x+0.5,y+0.5))
            x,y = parent[x][y]
        result.reverse()

    savePath('path',result, mapData)
    return result, distance, parent
Esempio n. 5
0
    def getFlankingPositionBot(self, bot, target):
        # Now figure out the flanking directions, assumed perpendicular.
        d = (bot.position - target)
        left = Vector2(-d.y, d.x).normalized()
        right = Vector2(d.y, -d.x).normalized()
        front = Vector2(d.x, d.y).normalized()

        flanks = [target + f * 26.0 for f in [left, right]]
        options = map(lambda f: self.level.findNearestFreePosition(f), flanks)
        return sorted(options, key=lambda p: (bot.position - p).length())[0]
Esempio n. 6
0
 def findNearestFreePosition(self, target):
     """
     Find a free position near 'target' for a character to move to.
     None is returned if no position could be found.
     """
     for r in range(1, 100):
         areaMin = Vector2(target.x - r, target.y - r)
         areaMax = Vector2(target.x + r, target.y + r)
         position = self.findRandomFreePositionInBox((areaMin, areaMax))
         if position:
             return position
     return None
Esempio n. 7
0
    def tick(self):
        if self.attacker and self.attacker.health <= 0:
            self.attacker = None

        for bot in self.game.bots_available:
            if (not self.attacker or self.attacker == bot
                    or bot.flag) and len(self.game.bots_alive) > 1:
                self.attacker = bot

                if bot.flag:
                    # Return the flag home relatively quickly!
                    targetLocation = self.game.team.flagScoreLocation
                    self.issue(commands.Move,
                               bot,
                               targetLocation,
                               description='returning enemy flag!')

                else:
                    # Find the enemy team's flag position and run to that.
                    enemyFlagLocation = self.game.enemyTeam.flag.position
                    self.issue(commands.Charge,
                               bot,
                               enemyFlagLocation,
                               description='getting enemy flag!')

            else:
                if self.attacker == bot:
                    self.attacker = None

                # defend the flag!
                targetPosition = self.game.team.flag.position
                targetMin = targetPosition - Vector2(8.0, 8.0)
                targetMax = targetPosition + Vector2(8.0, 8.0)

                if (targetPosition - bot.position).length() > 9.0 and (
                        targetPosition - bot.position).length() > 3.0:
                    while True:
                        position = self.level.findRandomFreePositionInBox(
                            (targetMin, targetMax))
                        if position and (targetPosition -
                                         position).length() > 3.0:
                            self.issue(commands.Charge,
                                       bot,
                                       position,
                                       description='defending around flag')
                            break
                else:
                    self.issue(commands.Defend,
                               bot, (targetPosition - bot.position),
                               description='defending facing flag')
Esempio n. 8
0
    def initialize(self):
        self.attacker = None
        self.defender = None
        self.verbose = False

        # Calculate flag positions and store the middle.
        ours = self.game.team.flag.position
        theirs = self.game.enemyTeam.flag.position
        self.middle = (theirs + ours) / 2.0

        # Now figure out the flaking directions, assumed perpendicular.
        d = (ours - theirs)
        self.left = Vector2(-d.y, d.x).normalized()
        self.right = Vector2(d.y, -d.x).normalized()
        self.front = Vector2(d.x, d.y).normalized()
Esempio n. 9
0
 def area(self):
     """
     Return the full area of the world.
     This can be used with findRandomFreePositionInBox to find a random position in the world.
     eg levelInfo.findRandomFreePositionInBox(levelInfo.area)
     """
     return (Vector2.ZERO, Vector2(self.width, self.height))
Esempio n. 10
0
def Command_AttackPathSmartStart(commander, bot, path):
    #pos = commander.freePos(commander.game.enemyTeam.flag.position)
    if len(path) <= 1:
        return False
    lookAt = None

    if len(path) > commander.level.firingDistance + 2:
        d = int(commander.level.firingDistance)
        path = path[:d]
        points = commander.levelAnalysis.getAllVisiblePoints(
            path[d - 1], commander.level.firingDistance * 2, -1, 0, False)
        _, lookP = min([(commander.enemyDistMap[x][y] if
                         commander.enemyDistMap[x][y] > 0 else 10000, (x, y))
                        for (x, y) in points],
                       key=lambda pair: pair[0])
        lookAt = Vector2(lookP[0] + 0.5, lookP[1] + 0.5)
    else:
        lookAt = None
    command = commands.Attack
    commander.issue(command,
                    bot,
                    path,
                    lookAt,
                    description='Go smart at start')
    return True
Esempio n. 11
0
def Command_AttackDangerEvent(commander, bot):
    e = bot.investigateEvent
    pos = e.instigator.position if e.instigator != None else e.subject.position
    if (bot.position - pos).length() > commander.level.firingDistance * 1.5:
        return False
    visiblePoints = commander.levelAnalysis.getAllVisiblePoints(
        bot.position, commander.level.firingDistance)
    minPos = min(visiblePoints,
                 key=lambda p: (pos - Vector2(p[0], p[1])).length())
    lookPos = Vector2(minPos[0], minPos[1])
    #dir = lookPos - bot.position
    commander.issue(commands.Attack,
                    bot,
                    lookPos,
                    lookPos,
                    description='Attack danger event')
Esempio n. 12
0
 def issue_moves(self, move):
     move_index = 0
     for bot in self.game.bots_available:
         pos = self.corridor_graph.node[move[move_index]]["position"]
         pos = Vector2(pos[0], pos[1])
         self.issue(orders.Charge, bot, pos)
         move_index += 1
Esempio n. 13
0
    def lastTickEventsAnalyze(self):
        self.dangerEvents = [e for e in self.dangerEvents if (self.game.match.timePassed-e.time)<self.eventInvalidationTime]
 
        for event in self.lastTickEvents:

            if event.type==MatchCombatEvent.TYPE_RESPAWN:
                bot = event.subject
                if bot in self.game.enemyTeam.members:
                    bot.position = self.level.findRandomFreePositionInBox(self.game.enemyTeam.botSpawnArea)
                    bot.seenLast = 0
                    bot.health = 100
                    bot.facingDirection = Vector2((random()-0.5),random()-0.5)

                if  self.enemyBotsAlive!=self.countBot:
                    self.updateDangerAtRespawn()
                    self.enemyBotsAlive=self.countBot
                #print "Alive enemies: %d"%self.enemyBotsAlive
            elif event.type==MatchCombatEvent.TYPE_KILLED:
                if event.subject.team.name!=self.game.team.name:
                    self.enemyBotsAlive-=1
                    #print "Alive enemies: %d"%self.enemyBotsAlive
                else:
                    self.dangerEvents.append(event)
                    #pos = e.instigator.position if e.instigator!=None else e.subject.position
                    pos = event.subject.position
                    self.levelAnalysis.updateDangerStatic(pos, 4, 196)
                    self.botInit(event.subject)
            elif event.type == MatchCombatEvent.TYPE_FLAG_PICKEDUP and event.subject.team.name==self.game.team.name:
                self.dangerEvents.append(event)
Esempio n. 14
0
 def getCornerPointInVisibility(self, pos, r):
     points = self.getAllVisiblePoints(pos,r)
     for p in points:
         x,y = p[0], p[1]
         if self.isCorner(x,y):
             return Vector2(x+0.5, y+0.5)
     return None
Esempio n. 15
0
    def __init__(self, map):
        self.map = map
        self.w = len(self.map)
        self.h = len(self.map[0])
        self.visibleSectors = self.buildLOS()
      

        self.averageMin = [ [(self.visibleSectors[0][x][y][0]
                                     +self.visibleSectors[1][x][y][0]
                                     +self.visibleSectors[2][x][y][0]
                                     +self.visibleSectors[3][x][y][0]
                                     +self.visibleSectors[4][x][y][0]
                                     +self.visibleSectors[5][x][y][0]
                                     +self.visibleSectors[6][x][y][0]
                                     +self.visibleSectors[7][x][y][0]
                                     +7)/8.0 for y in range(self.h)] for x in range(self.w)] 
        self.distanceField = [ [min([self.visibleSectors[0][x][y][0],
                                     self.visibleSectors[1][x][y][0],
                                     self.visibleSectors[2][x][y][0],
                                     self.visibleSectors[3][x][y][0],
                                     self.visibleSectors[4][x][y][0],
                                     self.visibleSectors[5][x][y][0],
                                     self.visibleSectors[6][x][y][0],
                                     self.visibleSectors[7][x][y][0]])
                                     for y in range(self.h)] for x in range(self.w)]

        self.maxField = [ [max([self.visibleSectors[0][x][y][0],
                                     self.visibleSectors[1][x][y][0],
                                     self.visibleSectors[2][x][y][0],
                                     self.visibleSectors[3][x][y][0],
                                     self.visibleSectors[4][x][y][0],
                                     self.visibleSectors[5][x][y][0],
                                     self.visibleSectors[6][x][y][0],
                                     self.visibleSectors[7][x][y][0]])
                                     for y in range(self.h)] for x in range(self.w)]
      

        self.directions =[Vector2(1,0), Vector2(1,-1).normalized(), Vector2(0,-1), Vector2(-1,-1).normalized(), 
                          Vector2(-1,0), Vector2(-1,1).normalized(), Vector2(0,1), Vector2(1,1).normalized()]
        angle = math.pi/8
        self.directions=[rotateVector2(x,angle) for x in self.directions]

        self.dangerMap =[ [(0) for y in range(self.h)] for x in range(self.w)]
        self.pathMap = self.createMapForPathFinding()
        self.dangerMapStatic =[ [ -1 if self.map[x][y]>0 else 1 for y in range(self.h)] for x in range(self.w)]
        self.visibleSafeToCharge = self.generateVisibleSafeMap()
        self.mergeDangerStaticWith(self.visibleSafeToCharge)
        self.cornerPoints = []
        for y in range(self.h):
            for x in range(self.w):
                if self.isCorner(x,y):
                    self.cornerPoints.append(Vector2(x+0.5,y+0.5))
Esempio n. 16
0
    def postWorldHook(self, visualizer):
        """
        Will draw a graphical representation of the corridor map on to the
        visualisation window.
        """
        for s, f in self.corridor_graph.edges():
            visualizer.drawLine(self.corridor_graph.node[s]["position"],
                                self.corridor_graph.node[f]["position"],
                                QtGui.qRgb(255, 255, 255))

        for n in self.corridor_graph.nodes():
            #visualizer.drawCircle(self.corridor_graph.node[n]["position"],
            #                      QtGui.qRgb(255, 255, 255))
            pos = self.corridor_graph.node[n]["position"]
            pos = Vector2(pos[0], pos[1])
            visualizer.drawText(pos, QtGui.qRgb(255, 255, 255), unicode(n))
            #if self.explored[n]:
            #visualizer.drawCircle(self.corridor_graph.node[n]["position"],
            # QtGui.qRgb(0, 0, 0), scale=0.8)

        height_separator = self.level.height / 2
        width_separator = self.level.width / 2

        graph_one = []
        graph_two = []
        graph_three = []
        graph_four = []
        for n in self.corridor_graph.nodes():
            position = self.corridor_graph.node[n]["position"]
            position = Vector2(position[0], position[1])
            if position.y > height_separator:
                if position.x > width_separator:
                    graph_one.append(n)
                else:
                    graph_two.append(n)
            else:
                if position.x > width_separator:
                    graph_three.append(n)
                else:
                    graph_four.append(n)

        graph_one = self.corridor_graph.subgraph(graph_one)
        for n in graph_one.nodes():
            visualizer.drawCircle(self.corridor_graph.node[n]["position"],
                                  QtGui.qRgb(255, 0, 0),
                                  scale=0.8)
 def issue_moves(self, move):
     move_index = 0
     for bot in self.game.bots_alive:
         if bot.state == bot.STATE_IDLE:
             pos = self.corridor_graph.node[move[move_index]]["position"]
             pos = Vector2(pos[0], pos[1])
             self.issue(orders.Charge, bot, pos)
         move_index += 1
 def test_get_flaking_coordinates(self):
     reference_position = Vector2(0, 0)
     flanked_position = Vector2(0, 10)
     firing_distance = 5
     action_left = Action(Action.ActionType.PREPARE_FLANKING_LEFT,
                          flanking_distance=1.0)
     action_rigth = Action(Action.ActionType.PREPARE_FLANKING_RIGHT,
                           flanking_distance=1.0)
     flanking_left = self.coordinates_calculator.get_flanking_coordinates(
         reference_position, flanked_position, firing_distance, action_left)
     flanking_rigth = self.coordinates_calculator.get_flanking_coordinates(
         reference_position, flanked_position, firing_distance,
         action_rigth)
     self.assertEqual(flanking_rigth[0].x, -flanking_left[0].x)
     self.assertEqual(flanking_rigth[1].x, -flanking_left[1].x)
     self.assertEqual(flanking_rigth[0].y, flanking_left[0].y)
     self.assertEqual(flanking_rigth[1].y, flanking_left[1].y)
Esempio n. 19
0
    def initialize(self):
        #self.attacker = None
        self.verbose = False
        self.enemyFlagLocation = self.game.enemyTeam.flag.position

        #types - def,att,scr,spa
        #spa experiment depends on '4,4' offset and kilroy start in top-right
        #2 def, 2 att, rest scramble the middle
        #FIX - the below is very hard-coded(and duplicative) and could be fixed to a more dynamic assignment function depending on the team assigned and roles needed - perhaps also as class properties rather than a dictionary also
        self.info = {'Red0': {'timeLastCommand': 0, 'role': 'att1', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': ''},\
                     'Red1': {'timeLastCommand': 0, 'role': 'att2', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': ''},\
                     'Red2': {'timeLastCommand': 0, 'role': 'attX', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Red3': {'timeLastCommand': 0, 'role': 'def1', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':2, 'flagY':2},\
                     'Red4': {'timeLastCommand': 0, 'role': 'def2', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':-2, 'flagY':-2},\
                     'Red5': {'timeLastCommand': 0, 'role': 'def3', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':2, 'flagY':-2},\
                     'Red6': {'timeLastCommand': 0, 'role': 'def4', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Red7': {'timeLastCommand': 0, 'role': 'scr4', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Red8': {'timeLastCommand': 0, 'role': 'scr5', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Red9': {'timeLastCommand': 0, 'role': 'scr6', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Blue0': {'timeLastCommand': 0, 'role': 'att1', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': ''},\
                     'Blue1': {'timeLastCommand': 0, 'role': 'att2', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': ''},\
                     'Blue2': {'timeLastCommand': 0, 'role': 'attX', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Blue3': {'timeLastCommand': 0, 'role': 'def1', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':2, 'flagY':2},\
                     'Blue4': {'timeLastCommand': 0, 'role': 'def2', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':-2, 'flagY':-2},\
                     'Blue5': {'timeLastCommand': 0, 'role': 'def3', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':2, 'flagY':-2},\
                     'Blue6': {'timeLastCommand': 0, 'role': 'def4', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Blue7': {'timeLastCommand': 0, 'role': 'scr4', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Blue8': {'timeLastCommand': 0, 'role': 'scr5', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0},\
                     'Blue9': {'timeLastCommand': 0, 'role': 'scr6', 'threshEvade': 30, 'distEvade': 4, 'botTrack': '', 'state': '', 'flagX':0, 'flagY':0}}

        #self.info['Red4']['timeLastCommand'] = 40

        # flanking setup from BalancedCommander
        # Calculate flag positions and store the middle.
        ours = self.game.team.flag.position
        theirs = self.game.enemyTeam.flag.position
        self.middle = (theirs + ours) / 2.0

        # Now figure out the flanking directions, assumed perpendicular.
        d = (ours - theirs)
        self.left = Vector2(-d.y, d.x).normalized()
        self.right = Vector2(d.y, -d.x).normalized()
        self.front = Vector2(d.x, d.y).normalized()

        self.flagRunner = ''
Esempio n. 20
0
    def initialize(self):
        self.attacker = None
        self.defenderSquad = [None, None]  #defender pair
        self.verbose = True

        # Calculate flag positions and store the middle.
        ours = self.game.team.flag.position
        theirs = self.game.enemyTeam.flag.position
        self.middle = (theirs + ours) / 2.0
        self.centre = Vector2(self.level.width, self.level.height) / 2.0

        # Now figure out the flaking directions, assumed perpendicular.
        d = (ours - theirs)
        self.left = Vector2(-d.y, d.x).normalized()
        self.right = Vector2(d.y, -d.x).normalized()
        self.front = Vector2(d.x, d.y).normalized()

        self.respawnTime = self.game.match.timeToNextRespawn
Esempio n. 21
0
 def generateFlagPoints(self):
     path, distMap, parentMap = getPathWithPathDistanceMap( self.game.enemyTeam.flag.position, self.ourSpawn, self.levelAnalysis.pathMap, False)
     d = self.level.firingDistance*2+2
     result=[]
     for y in range(self.level.height):
         for x in range(self.level.width):
             if abs(distMap[x][y]-d)<0.5:
                 result.append(Vector2(x+0.5,y+0.5))
     return result
Esempio n. 22
0
        def setVisible(x, y):
            d = (Vector2(x, y) - position).normalized()
            dp = d.dotProduct(facing_direction)

            if dp > coshalffov:
                self.game_state.visibility[x][y] = True
                node_index = self.game_state.lookup[x][y]

                if not self.game_state.seen[x][y]:
                    self.game_state.seen[x][y] = True
Esempio n. 23
0
 def IssueMoves(self, move):
     i = 0
     #  print 'Issuing orders'
     for bot in self.game.bots_available:
         #    print ' Issuing order to bot ' ,bot.name
         #   print ' Move from ', self.game_state.lookup[int(bot.position.x)][int(bot.position.y)], 'to ', move[i]
         pos = self.game_state.corridor_graph.node[move[i]]["position"]
         pos = Vector2(pos[0], pos[1])
         self.issue(orders.Charge, bot, pos)
         i = i + 1
Esempio n. 24
0
    def defenderLogic(self, bot):
        # Stand on a random position in a box of 4m around the flag.
        targetPosition = self.game.team.flagSpawnLocation
        targetMin = targetPosition - Vector2(2.0, 2.0)
        targetMax = targetPosition + Vector2(2.0, 2.0)
        goal = self.level.findRandomFreePositionInBox([targetMin, targetMax])

        if (goal - bot.position).length() > 8.0:
            self.issue(commands.Charge,
                       bot,
                       goal,
                       description='running to defend')
        else:
            if bot == self.defenderSquad[0]:
                self.issue(commands.Defend,
                           bot, (self.middle - bot.position),
                           description='turning to defend')
            else:
                self.issue(commands.Defend,
                           bot, (self.centre - bot.position),
                           description='turning to defend')
Esempio n. 25
0
    def buildDirecionMap(self, dangerPos):
        self.bestDirectionsMap =[ [(0,0) for y in range(self.h)] for x in range(self.w)]
        for x in range(0,self.w):
            for y in range(0,self.h):
                dirs =[(i, self.visibleSectors[i][x][y], self.visibleSectors[(i+7)%8][x][y]) for i in range(8)]
                delta = dangerPos-Vector2(x,y)
                dangerSector = self.getSectorIndex(delta)
                dangerSector2 = (dangerSector+1)%8

                bestI = max(dirs, key=lambda d: (d[1][0]+d[2][0]+ (d[1][1]+d[2][1])/16) * (2 if (d[0]==dangerSector or d[0]==dangerSector2) else 1) )
                bestDirection = bestI[0]
                self.bestDirectionsMap[x][y]=bestDirection
Esempio n. 26
0
def Command_RunToMiddlePerpen(commander, bot, pos):
    #pos = commander.game.enemyTeam.flag.position
    middle = (pos + bot.position) / 2
    d = pos - bot.position
    left = Vector2(-d.y, d.x).normalized()
    rnd = (random.random() - 0.5) * 2
    goalPos = middle + left * rnd * d.length() / 4
    path = [commander.freePos(goalPos), pos]
    commander.issue(commands.Charge,
                    bot,
                    path,
                    description='Charge to perpen (ATTACKER)')
    return True
Esempio n. 27
0
 def getSituation(self):
     result = None
     score = 0.0
     for i in range(10):
         p = self.level.findRandomFreePositionInBox(self.level.area)
         o = Vector2(random.uniform(-0.5, 0.5),
                     random.uniform(-0.5, 0.5)).normalized()
         s = self.evaluate(p, o, lambda x, y: 15.0 - self.getDistance(x, y))
         # - self.getDistance(int(p.x), int(p.y)) * 100
         if s > score or result == None:
             result = (p, o)
             score = s
     print score
     return result
Esempio n. 28
0
 def nearest_unexplored_root_node(self, bot_position):
     closest_node = None
     closest_distance = 1000000
     for node in self.terminal_nodes:
         if self.explored[node] == False:
             node_pos = self.corridor_graph.node[node]["position"]
             node_pos = Vector2(node_pos[0], node_pos[1])
             distance = bot_position.distance(node_pos)
             if distance < closest_distance:
                 closest_distance = distance
                 closest_node = node
     if closest_node == None:
         return 1
     return closest_node
Esempio n. 29
0
    def getMin(self, pos,r,data, key):
        minX, minY = self.clamp(int(pos.x-r), 0, self.w), self.clamp(int(pos.y-r), 0, self.h)
        maxX, maxY = self.clamp(int(pos.x+r), 0, self.w), self.clamp(int(pos.y+r), 0, self.h)    
        rangeX, rangeY = maxX - minX, maxY - minY

        if (rangeX == 0.0) or (rangeY == 0.0):
            return None 
        bestPos = None
        bestResult = 0
        for x in range(minX, maxX):
            for y in range(minY, maxY): 
                if (bestPos == None or data[x][y]<bestResult):
                    bestPos = Vector2(x+0.5,y+0.5)
                    bestResult = data[x][y]
        return bestPos
Esempio n. 30
0
    def getBestBreakingPoints(self, startPoints, end, rPrefered, rControl, n):
        pathMaxLength = 50
        tmpMap = self.createMapForPathFinding()
        result = []
        allpaths = []
        allPathData = [ [0  for y in range(self.h)] for x in range(self.w)]

        for i in range(n):
            start = startPoints[i%len(startPoints)]
            path = getPath(start, end, tmpMap)
            savePath("path_iteration"+str(i), path, tmpMap)
            if len(path)<1:
                break

            allpaths.append(path[-pathMaxLength:])

            self.MergeDataOnPath(path, rPrefered, allPathData, 1)
            breakingMap = self.getBreakingMap([path], rPrefered, allPathData)
            x,y = self.getTheBestPos(breakingMap)
            bestPoint = Vector2(x+0.5,y+0.5)

            pathMap = [ [tmpMap[x][y]  for y in range(self.h)] for x in range(self.w)]
            bestPair = None
            for p in path:
                if self.checkVisibility(bestPoint, p):
                    bestPair = (bestPoint,[p], path, pathMap, i)
                    break
            if bestPair==None:
                break
            result.append(bestPair)
            sector = self.getSectorIndexFloat(bestPair[1][0]-bestPair[0])

            visiblePoints = self.getAllVisiblePoints(bestPoint, rControl, sector, 1)
            #for p in path:
            #    x,y=int(p.x), int(p.y)               
            #    if  tmpMap[x][y] > 0:
            #        tmpMap[x][y] += 128
            #        if tmpMap[x][y]>255:
            #            tmpMap[x][y] = 255
            for x,y in visiblePoints:
                if  tmpMap[x][y] > 0:
                    tmpMap[x][y] += 128
                    if tmpMap[x][y]>255:
                        tmpMap[x][y] = 255
        savePath("allBreakingPoints", result, self.createMapForPathFinding())
        saveImage('corners', [ [ 0 if self.distanceField[x][y]<0 else 124 if self.isCorner(x,y) else 255 for x in range(self.w)] for y in range(self.h)] )
        saveImage('allPathData', allPathData)
        return result
Esempio n. 31
0
    def getBestPosition(self, pos, r):
        minX, minY = self.clamp(int(pos.x-r), 0, self.w), self.clamp(int(pos.y-r), 0, self.h)
        maxX, maxY = self.clamp(int(pos.x+r), 0, self.w), self.clamp(int(pos.y+r), 0, self.h)    
        rangeX, rangeY = maxX - minX, maxY - minY

        if (rangeX == 0.0) or (rangeY == 0.0):
            return None 
        bestPos = None
        bestResult = 255
        for x in range(minX, maxX):
            for y in range(minY, maxY): 
                if (self.averageMin[x][y]<bestResult):
                    bestPos = Vector2(x,y)
                    bestResult = self.averageMin[x][y]

        return bestPos