Esempio n. 1
0
    def caughtPrey(self, coordinate, distance):
        message = "caught! " + str(coordinate)
        ai.talk(message)

        if distance <= 100:
            self.caughtPreyFlag = True
        else:
            # get last two messages sent
            lastMessage = self.MessageBuffer[-1]
            secLastMessage = self.MessageBuffer[-2]

            # flags for later
            caught1 = False
            caught2 = False

            split1 = lastMessage.split(" ")
            split2 = secLastMessage.split(" ")
            sender1 = ""
            sender2 = ""

            if "[" in split1[-1]:
                sender1 = split1[-1][1:-1]

            if "[" in split2[-1]:
                sender2 = split2[-1][1:-1]

            if sender1 != "" and sender2 != "" and sender1 != sender2:
                if split1[0] == "caught!" and split2[0] == "caught!":
                    self.fitness = self.fitness + 100
                    with open('fitness.txt', 'a') as inFile:
                        outString = str(self.fitness) + "\n"
                        inFile.write(outString)
                    ai.quitAI()
Esempio n. 2
0
 def __init__(self, target=None):
     self.name = "fire"
     if target is None:
         print("Fire: Target not specified!!")
         ai.quitAI()
         sys.exit(1)
     else:
         self.target = target
     if ai.selfShield():
         ai.shield()
Esempio n. 3
0
 def __init__(self, position=None):
     print("MoveAt: Initialising move at")
     if position is None:
         print("MoveAt: Target not specified!!")
         ai.quitAI()
         sys.exit(0)
     else:
         self.position = position
     self.setGains()
     self.done = False
Esempio n. 4
0
 def __init__(self, idE=None, gain=FIRE_GAIN):
     if idE is None:
         print("FireEnemy: No enemy selected! Exiting now.")
         ai.quitAI()
         sys.exit(1)
     print("Open fire to:", ai.enemyNameId(idE))
     if ai.selfShield():
         ai.shield()
     self.idE = idE
     self.K = gain
Esempio n. 5
0
 def __init__(self, position=None):
     print("MoveAt: Initialising move at")
     if position is None:
         print("MoveAt: Target not specified!!")
         ai.quitAI()
         sys.exit(0)
     else:
         self.position = position
     self.setGains()
     self.done = False
Esempio n. 6
0
 def __init__(self, idE=None, gain=FIRE_GAIN):
     if idE is None:
         print("FireEnemy: No enemy selected! Exiting now.")
         ai.quitAI()
         sys.exit(1)
     print("Open fire to:", ai.enemyNameId(idE))
     if ai.selfShield():
         ai.shield()
     self.idE = idE
     self.K = gain
Esempio n. 7
0
 def __init__(self, target=None):
     self.name = "fire"
     if target is None:
         print("Fire: Target not specified!!")
         ai.quitAI()
         sys.exit(1)
     else:
         self.target = target
     if ai.selfShield():
         ai.shield()
Esempio n. 8
0
    def checkMessage(self, message):

        splitMessage = message.split(" ")

        # Checks if message is sent by one of the predators
        if "[" in splitMessage[-1]:
            sender = splitMessage[-1][1:-1]

            # Checks if message wasn't sent by itself
            if sender != self.name:

                # Another grid coordinate checked
                if splitMessage[0] == "checked!":
                    coordinate = eval(message[message.find("(") +
                                              1:message.find(")")])
                    self.markSpotChecked(coordinate, "not me")
                    self.checkSearchComplete()

                # Checking sector of grid
                elif splitMessage[0] == "checking!":
                    coordinate = eval(message[message.find("(") +
                                              1:message.find(")")])
                    self.setChecking(coordinate)

                # Grid sweep complete - restart sweep
                elif splitMessage[0] == "clear!":
                    self.checkSearchComplete()

                # Parter found enemy
                elif splitMessage[0] == "***" or splitMessage[0] == "caught!":
                    coordinate = eval(message[message.find("(") +
                                              1:message.find(")")])
                    self.parterFoundPreyFlag = True
                    self.preyLocation = coordinate

                # Partner lost enemy
                elif splitMessage[0] == "---":
                    self.parterFoundPreyFlag = False

                elif splitMessage[0] == "preyid":
                    self.preyID = int(splitMessage[1])

                elif splitMessage[0] == "quit!":
                    with open('fitness.txt', 'a') as inFile:
                        outString = str(self.fitness) + "\n"
                        inFile.write(outString)
                    ai.quitAI()

        self.MessageBuffer.append(message)
Esempio n. 9
0
def AI_loop():
    
    if ai.selfAlive():
        
        global loopCount,  lastLoop
        con.act()
        loopCount+=1
        con.dummyCode()
        DataMinerBD.updateInputs()
        DataMinerBD.updateOutputs()
        DataMinerBD.savePair()
        if loopCount % 100 == 0:
            print(loopCount)
        if loopCount > 1000:
            DataMinerBD.writeData()
            ai.quitAI()
        lastLoop = 1
    else:
        if lastLoop == 1:
            DataMinerBD.writeDeath()
    lastLoop = 0
Esempio n. 10
0
    def AI_loop(self):

        # Release keys
        ai.thrust(0)
        ai.turnLeft(0)
        ai.turnRight(0)

        if self.quitFlag == True:
            with open('fitness.txt', 'a') as inFile:
                outString = str(self.fitness) + "\n"
                inFile.write(outString)
            ai.quitAI()

        if ai.selfAlive() == 0 or self.frames > 3000:
            self.foundPreyFlag = False
            self.parterFoundPreyFlag = False
            self.checking = False

        if self.foundPreyFlag == True and self.parterFoundPreyFlag == True:
            self.fitness = self.fitness + 2

        #-------------------- Set variables --------------------#
        heading = int(ai.selfHeadingDeg())
        tracking = int(ai.selfTrackingDeg())
        frontWall = ai.wallFeeler(500, heading)
        leftWall = ai.wallFeeler(500, heading + 45)
        rightWall = ai.wallFeeler(500, heading - 45)
        leftWallStraight = ai.wallFeeler(500, heading + 90)
        rightWallStraight = ai.wallFeeler(500, heading - 90)
        leftBack = ai.wallFeeler(500, heading + 135)
        rightBack = ai.wallFeeler(500, heading - 135)
        backWall = ai.wallFeeler(500, heading - 180)
        trackWall = ai.wallFeeler(500, tracking)
        R = (heading - 90) % 360
        L = (heading + 90) % 360
        aim = ai.aimdir(0)
        bullet = ai.shotAlert(0)
        speed = ai.selfSpeed()
        x = ai.selfX()
        y = ai.selfY()
        enemyX = -1
        enemyY = -1
        enemyTeam = -1

        if self.preyID != -1:
            enemyX = ai.screenEnemyXId(self.preyID)
            enemyY = ai.screenEnemyYId(self.preyID)
            enemyTeam = ai.enemyTeamId(self.preyID)
        else:
            enemyX = ai.screenEnemyXId(ai.closestShipId())
            enemyY = ai.screenEnemyYId(ai.closestShipId())
            enemyTeam = ai.enemyTeamId(ai.closestShipId())

        myTeam = ai.selfTeam()
        coordinate = self.grid[self.counter][1]
        message = ai.scanMsg(0)

        # Continually check messages
        if message != self.MessageBuffer[-1]:
            self.checkMessage(message)

        # Check if enemy is on screen
        # If it is: broadcast location of enemy
        if enemyX != -1 and enemyY != -1 and enemyTeam != 2:
            coordinate = (enemyX, enemyY)
            self.foundPreyFlag = True
            self.foundPrey(coordinate)
            self.fitness += 1
        elif self.foundPreyFlag == True:
            self.foundPreyFlag = False
            ai.talk("--- " + "Lost prey!")

        if self.parterFoundPreyFlag == True:
            coordinate = self.preyLocation

        # Calculate most efficient way to turn to get where we want to
        targetX = coordinate[0]
        targetY = coordinate[1]
        toTurn = self.angleToPoint(x, y, targetX, targetY, heading)
        distance = self.distance(x, targetX, y, targetY)

        if self.checking == False and self.foundPreyFlag == False:
            ai.talk("checking! " + str(coordinate))
            self.checking = True

        # If speed is too fast, turn around and thrust to negate velocity
        if speed > self.gene0:
            turning = ai.angleDiff(heading, tracking)
            if abs(turning) > self.gene1 and abs(turning) <= self.gene2:
                ai.turnLeft(0)
                ai.turnRight(0)
                if self.frames % self.gene3 == 0:
                    ai.thrust(1)
            elif turning <= self.gene4 and turning > self.gene5:
                ai.turnRight(1)
            else:
                ai.turnLeft(1)

            if self.foundPreyFlag == True and distance <= 150:
                self.caughtPrey(coordinate, distance)

        else:

            #-------------------- Go to coordinate / enemy --------------------#
            if abs(toTurn) < self.gene6 and distance > self.gene7:
                ai.turnLeft(0)
                ai.turnRight(0)
                if self.frames % self.gene8 == 0:
                    ai.thrust(1)
            elif toTurn >= self.gene9:
                ai.turnLeft(1)
            elif toTurn <= -self.gene10:
                ai.turnRight(1)

            if self.foundPreyFlag == True and distance <= 150:
                self.caughtPrey(coordinate, distance)
            elif self.foundPreyFlag == True and distance > 150:
                self.foundPrey(coordinate)
            elif distance < 150:
                self.markSpotChecked(coordinate, "me")

        #-------------------- Old turn and thrust rules --------------------#
        if speed <= self.gene14 and frontWall >= self.gene15:
            ai.thrust(1)
        elif trackWall < self.gene16:
            ai.thrust(1)
        elif backWall < self.gene17:
            ai.thrust(1)
        if (backWall < self.gene18) and (rightWallStraight < self.gene19):
            ai.turnLeft(1)
        elif backWall < self.gene20 and (leftWallStraight < self.gene21):
            ai.turnRight(1)
        elif leftWallStraight < rightWallStraight and trackWall < self.gene22:
            ai.turnRight(1)
        elif leftWallStraight > rightWallStraight and trackWall < self.gene23:
            ai.turnLeft(1)

        self.frames = self.frames + 1

        if self.caughtPreyFlag == True and self.quitFlag == False:
            ai.talk("quit!")
            self.quitFlag = True

        if ai.selfAlive() == 0 or self.frames > 1800:
            self.quitFlag = True
Esempio n. 11
0
def AI_loop():

    #Inserted Code
    if ai.selfAlive():
        DataMinerBD.updateInputs()
        DataMinerBD.updateOutputs()
        DataMinerBD.savePair()
        print(DataMinerBD.length())
        if DataMinerBD.length() > 10000:
            DataMinerBD.writeData()
            print("Finished")
            ai.quitAI()
    
    global lastTurn
    #Release keys
    DataMinerBD.tthrust(0)
    DataMinerBD.tturnLeft(0)
    DataMinerBD.tturnRight(0)
    ai.setTurnSpeed(45)
    #Set variables"""
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackWall = ai.wallFeeler(500,  tracking)
    trackLWall = ai.wallFeeler(500,  tracking+3)
    trackRWall = ai.wallFeeler(500,  tracking - 3)
    frontWall = ai.wallFeeler(500,heading)
    flWall = ai.wallFeeler(500,  heading + 10)
    frWall = ai.wallFeeler(500,  heading - 10)
    leftWall = ai.wallFeeler(500,heading+90)
    rightWall = ai.wallFeeler(500,heading-90)
    trackWall = ai.wallFeeler(500,tracking)
    backWall = ai.wallFeeler(500, heading - 180)
    backLeftWall = ai.wallFeeler(500,  heading - 185)
    backRightWall = ai.wallFeeler(500,  heading - 175)
    speed = ai.selfSpeed()
   
    closest = min(frontWall, leftWall, rightWall, backWall)
    def closestWall(x): #Find the closest Wall
        return {
            frontWall : 1, 
            leftWall : 2, 
            rightWall : 3, 
            backWall : 4, 
            flWall : 5, 
            frWall : 6, 
        }[x]
    wallNum = closestWall(closest)
    
    #Code for finding the angle to the closest ship
    target = ai.closestShipId()
    targetX,  targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)
    calcDir = 0
    
    if targetX- ai.selfX() != 0:
        calcDir = (math.degrees(math.atan2((targetY - ai.selfY()), (targetX- ai.selfX()))) + 360)%360
    targetDir = calcDir
    crashWall = min(trackWall,  trackLWall,  trackRWall) #The wall we are likely to crash into if we continue on our current course
    #Rules for turning
    if crashWall > 25*speed and closest > 30 and targetX != -1:  #If we are far enough away from a predicted crash and no closer than 25 pixels to a wall, and there isn't a wall between us and the closest enemy
        #print("Aiming",  targetDir,  " Current",  heading)
        diff = (calcDir - heading)
        if ai.shotAlert(0) > -1 and ai.shotAlert(0) < 35:
            DataMinerBD.tturnRight(1)
            DataMinerBD.tthrust(1)
        elif diff >= 0:
            if diff >= 180:
                a = 0
                DataMinerBD.tturnRight(1)     #If the target is to our right- turn right
            elif diff != 0 :              
                a = 0
                
                DataMinerBD.tturnLeft(1)      #If the target is to our left - turn left
        else :
            if diff > -180:
                a = 0
                DataMinerBD.tturnRight(1)     #If the target is to our right - turn right
            else :
                a = 0
                DataMinerBD.tturnLeft(1)      #If the target is to our left - turn left
    else : #Rules for avoiding death
       # if crashWall/ai.selfSpeed() > ai.closestShot() :
       #We find a target heading using our current trajectory and the closest wall then turn in it's direction
        targetHeading = heading
        print(heading)
        if wallNum == 1or wallNum == 6 or wallNum == 5:    #Front Wall is Closest
            if lastTurn == 1:
                targetHeading += 270
                targetHeading = (targetHeading)%360
            else :
                targetHeading +=90
                targetHeading = targetHeading%360
            
            print("front")
        elif wallNum == 2  :  # Left Wall is Closest
            targetHeading += 270
            targetHeading = (targetHeading)%360
            lastTurn = 1
            print("leftwall")
        elif wallNum == 3  :
            targetHeading = targetHeading + 90
            targetHeading = (targetHeading)%360
            lastTurn = 2
            print("rightWall")
        else :
            if backLeftWall < backRightWall:
                lastTurn = 2
                targetHeading += 5
                targetHeading = (targetHeading)%360
            if backLeftWall > backRightWall:
                lastTurn = 1
                targetHeading -= 5
                targetHeading = (targetHeading)%360
       
        speedConcern = ai.selfSpeed() - 4
        
        if speedConcern < 0:
            speedConcern = 0
        elif speedConcern > 5:
            speedConcern = 5
        
        #targetHeading = (targetHeading*(1-(speedConcern/5))) + (((tracking+170)%360)*(speedConcern/5))
        if speedConcern > 2:
            targetHeading = (tracking + 180)%360
        
        diff = (targetHeading - heading)
        print("targetHEading : ", targetHeading,  " heading : ",  heading)
        if diff >= 0:
            if diff >= 180:
                DataMinerBD.tturnRight(1)     #If the targetHEading is to our right- turn right
                
                print("right")
            elif diff != 0 :                       
                DataMinerBD.tturnLeft(1)      #If the targeHeadingt is to our left - turn left
                print("left")
        else :
            if diff > -180:
                print("right")
                DataMinerBD.tturnRight(1)     #If the targetHeading is to our right - turn right
                #print("right")
            else :
                print("left")
                DataMinerBD.tturnLeft(1)      #If the targetHeading is to our left - turn left
            #print("nice")
    
    #Rules for thrusting
    
    if speed < 5 and frontWall > 200:   #If we are moving slowly and we won't ram into anything, accelerate
        DataMinerBD.tthrust(1)
    elif crashWall < 25*speed  and (abs(tracking - heading) > 120):  #If we are getting close to a wall, and we can thrust away from it, do so
        DataMinerBD.tthrust(1)
    elif backWall < 30: #If there is a wall very close behind us, get away from it
        DataMinerBD.tthrust(1)
    
    if abs(calcDir - heading) < 15 : #If we are close to the current proper trajectory for a shot then fire
        DataMinerBD.tshoot()
Esempio n. 12
0
def AI_loop():

    #Inserted Code
    lastLoop = 0
    if ai.selfAlive():
        lastLoop = 1
        DataMinerBD.updateInputs()
        DataMinerBD.updateOutputs()
        DataMinerBD.savePair()
        if DataMinerBD.length() % 100 == 0:
            print(DataMinerBD.length())
        if DataMinerBD.length() > 1000:
            DataMinerBD.writeData()
            print("Finished")
            ai.quitAI()
    else:
        if lastLoop == 1:
            DataMinerBD.writeDeath()
    global maxSpeed, shotAngle, wallClose, dead, previousScore
    global turnedLeft, turnedRight, thrusted, shot

    #Release keys
    DataMinerBD.tthrust(0)
    DataMinerBD.tturnLeft(0)
    DataMinerBD.tturnRight(0)
    ai.setTurnSpeed(45)
    #Set variables"""
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())

    trackWall = ai.wallFeeler(500, tracking)
    trackLWall = ai.wallFeeler(500, tracking + 3)
    trackRWall = ai.wallFeeler(500, tracking - 3)

    frontWall = ai.wallFeeler(500, heading)
    flWall = ai.wallFeeler(500, heading + 10)
    frWall = ai.wallFeeler(500, heading - 10)

    leftWall = ai.wallFeeler(500, heading + 90)
    llWall = ai.wallFeeler(500, heading + 100)
    rlWall = ai.wallFeeler(500, heading + 80)

    rightWall = ai.wallFeeler(500, heading - 90)
    lrWall = ai.wallFeeler(500, heading - 80)
    rrWall = ai.wallFeeler(500, heading - 100)

    trackWall = ai.wallFeeler(500, tracking)
    backWall = ai.wallFeeler(500, heading - 180)
    backLeftWall = ai.wallFeeler(500, heading - 190)
    backRightWall = ai.wallFeeler(500, heading - 170)
    speed = ai.selfSpeed()

    closest = min(frontWall, leftWall, rightWall, backWall, flWall, frWall)

    def closestWall(x):  #Find the closest Wall
        return {
            frontWall: 1,
            leftWall: 2,
            rightWall: 3,
            backWall: 4,
            flWall: 5,
            frWall: 6,
        }[x]

    wallNum = closestWall(closest)

    #Code for finding the angle to the closest ship
    targetX, targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)

    #baseString = "["+str(flWall/500)+","+str(frontWall/500)+","+str(frWall/500) + "," + str(backLeftWall/500) + "," + str(backWall/500) + "," + str(backRightWall/500) + ","+str(leftWall/500)+","+str(rightWall/500)+","+str(trackLWall/500) + "," + str(trackWall/500) + ","+str(trackRWall/500) + "," + str(speed/10)

    calcDir = -1
    if targetX - ai.selfX() != 0:
        calcDir = (math.degrees(
            math.atan2((targetY - ai.selfY()),
                       (targetX - ai.selfX()))) + 360) % 360
    crashWall = min(
        trackWall, trackLWall, trackRWall
    )  #The wall we are likely to crash into if we continue on our current course
    #Rules for turning
    if crashWall > wallClose * speed and closest > 25 and targetX != -1:  #If we are far enough away from a predicted crash and no closer than 25 pixels to a wall we can try and aim and kill them
        diff = (calcDir - heading)
        #if ai.shotAlert(0) > -1 and ai.shotAlert(0) < 35:   #If we are about to get shot
        #    tturnRight(1)                                                     #Screw aiming and turn right and thrust
        #    tthrust(1)                                                            #This is arguably a horrible strategy because our sideways profile is much larger, but it's required for the grade
        if diff >= 0:
            if diff >= 180:
                DataMinerBD.tturnRight(
                    1)  #If the target is to our right- turn right

            else:
                DataMinerBD.tturnLeft(
                    1)  #If the target is to our left - turn left

        else:
            if diff > -180:
                DataMinerBD.tturnRight(
                    1)  #If the target is to our right - turn right

            else:
                DataMinerBD.tturnLeft(
                    1)  #If the target is to our left - turn left

    else:  #Rules for avoiding death
        # if crashWall/ai.selfSpeed() > ai.closestShot() :
        if wallNum == 1 or wallNum == 5 or wallNum == 6:  #Front Wall is Closest (Turn Away From It)
            DataMinerBD.tturnLeft(1)

        elif wallNum == 2:  # Left Wall is Closest (Turn Away From It)
            DataMinerBD.tturnRight(1)

        elif wallNum == 3:  #Right Wall is Closest (Turn Away From It)
            DataMinerBD.tturnLeft(1)

        else:  #Back Wall is closest- turn so that we are facing directly away from it
            if backLeftWall < backRightWall:
                DataMinerBD.tturnRight(
                    1
                )  #We need to turn right to face more directly away from it

            if backLeftWall > backRightWall:  # We need to turn left to face more directly away from it
                DataMinerBD.tturnLeft(1)

    #Rules for thrusting

    if speed < maxSpeed and frontWall > 100:  #If we are moving slowly and we won't ram into anything, accelerate
        DataMinerBD.tthrust(1)
    elif trackWall < 200 and (
            ai.angleDiff(heading, tracking) > 120
    ):  #If we are getting close to a wall, and we can thrust away from it, do so
        DataMinerBD.tthrust(1)
    elif backWall < 20:  #If there is a wall very close behind us, get away from it
        DataMinerBD.tthrust(1)

    if abs(
            calcDir - heading
    ) < shotAngle and calcDir != -1:  #If we are close to the current proper trajectory for a shot then fire
        DataMinerBD.tshoot()

    previousScore = ai.selfScore()
Esempio n. 13
0
    def AI_loop(self):

        if self.team == False:
            ai.talk("/team 2")
            self.team = True

        # Release keys
        ai.thrust(0)
        ai.turnLeft(0)
        ai.turnRight(0)

        #-------------------- Set variables --------------------#
        heading = int(ai.selfHeadingDeg())
        tracking = int(ai.selfTrackingDeg())
        frontWall = ai.wallFeeler(500, heading)
        leftWall = ai.wallFeeler(500, heading + 45)
        rightWall = ai.wallFeeler(500, heading - 45)
        leftWallStraight = ai.wallFeeler(500, heading + 90)
        rightWallStraight = ai.wallFeeler(500, heading - 90)
        leftBack = ai.wallFeeler(500, heading + 135)
        rightBack = ai.wallFeeler(500, heading - 135)
        backWall = ai.wallFeeler(500, heading - 180)
        trackWall = ai.wallFeeler(500, tracking)
        R = (heading - 90) % 360
        L = (heading + 90) % 360
        aim = ai.aimdir(0)
        bullet = ai.shotAlert(0)
        speed = ai.selfSpeed()
        x = ai.selfX()
        y = ai.selfY()
        enemyX1 = ai.screenEnemyXId(0)
        enemyY1 = ai.screenEnemyYId(0)
        enemyX2 = ai.screenEnemyXId(1)
        enemyY2 = ai.screenEnemyYId(1)
        enemyTeam1 = ai.enemyTeamId(0)
        enemyTeam2 = ai.enemyTeamId(1)
        myTeam = ai.selfTeam()
        coordinate = self.grid[self.counter][1]
        message = ai.scanMsg(0)

        # print(enemyX1, enemyY1, enemyX2, enemyY2)
        # print(myTeam, enemyTeam1, enemyTeam2)

        # Continually check messages
        if message != self.MessageBuffer[-1]:
            self.checkMessage(message)

        # Check if enemy is on screen
        # If it is: broadcast location of enemy
        # If it is not: send message that we lost enemy
        if enemyX1 != -1 and enemyY1 != -1:
            print("enemy 1")
            enemyCoordinate = (enemyX1, enemyY1)
            self.foundPrey(enemyCoordinate)
            coordinate = enemyCoordinate
        elif enemyX2 != -1 and enemyY2 != -1:
            print("enemy 2")
            enemyCoordinate = (enemyX2, enemyY2)
            self.foundPrey(enemyCoordinate)
            coordinate = enemyCoordinate
        elif self.foundPreyFlag == True:
            print("lost prey")
            self.lostPrey()

        targetX = coordinate[0]
        targetY = coordinate[1]
        toTurn = self.angleToPoint(x, y, targetX, targetY, heading)
        distance = self.distance(x, targetX, y, targetY)

        if self.foundPreyFlag == False and self.checking == False:
            ai.talk("checking! " + str(coordinate))
            self.checking = True

        # If speed is too fast, turn around and thrust to negate velocity
        if speed > 5:
            turning = ai.angleDiff(heading, tracking)
            if abs(turning) > 165 and abs(turning) <= 180:
                ai.turnLeft(0)
                ai.turnRight(0)
                if self.frames % 10 == 0:
                    ai.thrust(1)
            elif turning <= 165 and turning > 0:
                ai.turnRight(1)
            else:
                ai.turnLeft(1)

        else:

            #-------------------- Go to coordinate / enemy --------------------#
            if abs(toTurn) < 10 and distance > 100:
                ai.turnLeft(0)
                ai.turnRight(0)
                if self.frames % 3 == 0:
                    ai.thrust(1)
            elif toTurn >= 10:
                ai.turnLeft(1)
            elif toTurn <= -10:
                ai.turnRight(1)

            if self.foundPreyFlag == True and distance < 150:
                print("Caught enemy!")
                ai.quitAI()

            elif distance < 150:
                self.markSpotChecked(coordinate, "me")

        #-------------------- Old turn and thrust rules --------------------#
        if speed <= 3 and frontWall >= 200:
            ai.thrust(1)
        elif trackWall < 50:
            ai.thrust(1)
        elif backWall < 40:
            ai.thrust(1)

        # Figures out what corner we are in and turns the right directon
        if (backWall < 30) and (rightWallStraight < 200):
            ai.turnLeft(1)
        elif backWall < 30 and (leftWallStraight < 200):
            ai.turnRight(1)

        # Walls along our periphery (90 degree feelers)
        elif leftWallStraight < rightWallStraight and trackWall < 75:
            ai.turnRight(1)
        elif leftWallStraight > rightWallStraight and trackWall < 75:
            ai.turnLeft(1)

        self.frames = self.frames + 1
Esempio n. 14
0
    def AI_loop(self):
        # print("AI_LOOP")

        if ai.selfAlive() == 0:
            outputFile = open("fitness.txt", "a")
            # outputFile.write(str((self.totalDists/self.counter))+"\t")
            outputFile.write(str(int((self.fitness**1.2))) + "\t")
            [
                print(str("%.5f" % g) + "\t", end="", file=outputFile)
                for g in self.chromosome
            ]
            print("\n", end="", file=outputFile)
            outputFile.close()

        # Release keys
        ai.thrust(0)
        ai.turnLeft(0)
        ai.turnRight(0)
        ai.setTurnSpeed(55)

        # Heuristics
        frontFeelerOffset = 45
        perpFeelerOffset = 90
        rearFeelerOffset = 135
        # turnSpeedMin = 15       # learn     range: 4 - 24
        turnSpeedMax = 55
        speedLimit = 5  # learn     range: 2-6
        lowSpeedLimit = 2
        targetingAccuracy = 4  # 1/2 tolerance in deg for aiming accuracy
        shotIsDangerous = 130

        # Acquire information
        heading = int(ai.selfHeadingDeg())
        tracking = int(ai.selfTrackingDeg())

        ###=== ENEMY FEELERS ===###

        # gets angle to enemy
        enemyDeg = self.angleToPointDeg(
            (ai.selfX(), ai.selfY()), (ai.screenEnemyX(0), ai.screenEnemyY(0)))
        enemyWallDistances = []

        # maxAngleOffset = 90     # learn     range: 30 - 120
        # resolution = 5          # learn     range: 2 - 10
        distAngleTuples = []

        # creates tuples of degrees and wallFeelers
        for m in (0, self.maxAngleOffset, self.resolution):
            distAngleTuples.append(
                (enemyDeg - m, ai.wallFeeler(500, int(enemyDeg - m))))
            distAngleTuples.append(
                (enemyDeg + m, ai.wallFeeler(500, int(enemyDeg + m))))

        # gets furthest feeler
        maxFeelerAngle = max(distAngleTuples, key=self.returnSecond)
        angleToOpenSpace = self.headingDiff(ai.selfHeadingDeg(),
                                            maxFeelerAngle[0])

        ###=== WALL FEELERS ===###

        frontWall = ai.wallFeeler(
            self.genericFeelerDist,
            heading)  # wall feeler for wall directly ahead
        leftFrontWall = ai.wallFeeler(
            self.genericFeelerDist, heading +
            frontFeelerOffset)  # wall feeler for wall 45 degrees to the left
        rightFrontWall = ai.wallFeeler(
            self.genericFeelerDist, heading -
            frontFeelerOffset)  # wall feeler for wall 45 degrees to the right
        leftWall = ai.wallFeeler(
            self.genericFeelerDist, heading +
            perpFeelerOffset)  # wall feeler for wall 90 degrees to the left
        rightWall = ai.wallFeeler(
            self.genericFeelerDist, heading -
            perpFeelerOffset)  # wall feeler for wall 90 degrees to the right
        backWall = ai.wallFeeler(self.genericFeelerDist, heading -
                                 180)  # wall feeler for wall straight back
        leftBackWall = ai.wallFeeler(
            self.genericFeelerDist, heading +
            rearFeelerOffset)  # wall feeler for wall 135 degrees to the left
        rightBackWall = ai.wallFeeler(
            self.genericFeelerDist, heading -
            rearFeelerOffset)  # wall feeler for wall 135 degrees to the right
        trackWall = ai.wallFeeler(
            self.genericFeelerDist,
            tracking)  # wall in front of where ship is moving

        # Keep track of all the feeler distances
        feelers = [
            frontWall, leftFrontWall, rightFrontWall, leftWall, rightWall,
            backWall, leftBackWall, rightBackWall, trackWall
        ]

        # Aim assist
        leftDir = (heading +
                   90) % 360  # angle 90 degrees to the left of current heading
        rightDir = (heading - 90
                    ) % 360  # angle 90 degrees to the right of current heading
        aimer = ai.aimdir(
            0
        )  #  direction that the ship needs to turn to in order to face the enemy in degrees
        shot = ai.shotAlert(
            0
        )  # returns a danger rating of a shot, the smaller the number the more likely the shot is to hit the ship
        enemyX = ai.screenEnemyX(0)  # returns the closest enemy's x-coord
        enemyY = ai.screenEnemyY(0)  # returns the closest enemy's y-coord
        selfX = ai.selfX()  # returns the ship's x-coord
        selfY = ai.selfY()  # returns the ship's x-coord

        # Fuzzy variable declaration
        trackRisk = riskEval(trackWall,
                             ai.selfSpeed())  #risk of running into trackWall
        frontRisk = riskEval(frontWall,
                             ai.selfSpeed())  #risk of running into frontWall
        leftRisk = riskEval(leftWall,
                            ai.selfSpeed())  #risk of running into leftWall
        rightRisk = riskEval(rightWall,
                             ai.selfSpeed())  #risk of running into rightWall
        LFRisk = riskEval(leftFrontWall,
                          ai.selfSpeed())  #risk of running into leftFrontWall
        RFRisk = riskEval(rightFrontWall,
                          ai.selfSpeed())  #risk of running into rightFrontWall
        LBRisk = riskEval(leftBackWall,
                          ai.selfSpeed())  #risk of running into leftBackWall
        RBRisk = riskEval(rightBackWall,
                          ai.selfSpeed())  #risk of running into rightBackWall
        backRisk = riskEval(backWall,
                            ai.selfSpeed())  #risk of running into backWall

        # Compress some wall feelers
        sTrack = self.squisher(trackWall)
        sLeft = self.squisher(leftFrontWall)
        sRight = self.squisher(rightFrontWall)
        sLeftStraight = self.squisher(leftWall)
        sRightStraight = self.squisher(rightWall)

        # output from neural network that tells how much to turn and which direction
        turn = self.trainedNeuralNetwork(sTrack, sLeft, sRight, sLeftStraight,
                                         sRightStraight)

        ###=== THRUST POWER ADJUSTMENT ===#

        # Power levels

        mfS = self.mfSpeed(ai.selfSpeed())
        mfD = self.mfDanger(ai.shotAlert(0))

        # if S is high and D is moderate or high:
        p1 = max(mfS[2], min(mfD[1], mfD[2]))
        # if S is moderate and D is moderate:
        p2 = max(mfS[1], mfD[1])
        # if S is low and D is high:
        p3 = max(mfS[0], mfD[2])
        # if S is moderate and D is moderate:
        p4 = max(mfS[1], mfD[1])
        # if S is low and D is moderate:
        p5 = max(mfS[0], mfD[1])
        # if S is high and D is low:
        p6 = max(mfS[2], mfD[0])
        # if S is moderate and D is low:
        p7 = max(mfS[1], mfD[0])
        # if S is low and D is low:
        p8 = max(mfS[0], mfD[0])

        consequents = [55, 45, 55, 36, 36, 28, 24, 30]
        memberships = [p1, p2, p3, p4, p5, p6, p7, p8]
        ai.setPower(self.crispify(memberships, consequents))

        if ai.enemyDistance(0) > self.lastDist and ai.enemyDistance(
                0) < self.enemyClose:
            ai.thrust(1)

        elif ai.selfSpeed(
        ) <= 3 and frontWall >= 200:  # if speed is slow and front wall is far away, thrust
            ai.thrust(1)
        elif trackWall < 60 and frontWall >= 200:  # if the track wall is close, thrust
            ai.thrust(1)
        elif backWall < 20:  # if the back wall is close, thrust
            ai.thrust(1)

        ###=== TURNING RULES ===###

        # Escape shots
        if shot > 0 and shot < 70:
            # if a shot is closeby, turn and thrust to avoid
            if self.angleDif(rightDir, ai.shotX(0)) < self.angleDif(
                    leftDir, ai.shotX(0)
            ) or self.angleDif(rightDir, ai.shotY(0)) < self.angleDif(
                    leftDir, ai.shotY(0)
            ):  # if shot is coming from the right, turn away and thrust
                # print("Turning: avoiding shot")#debug
                ai.turnLeft(1)
                ai.thrust(1)
            elif self.angleDif(leftDir, ai.shotX(0)) < self.angleDif(
                    rightDir, ai.shotX(0)
            ) or self.angleDif(leftDir, ai.shotY(0)) < self.angleDif(
                    rightDir, ai.shotY(0)
            ):  # if shot is coming from the left, turn away and shoot ------> change this shot is just a number
                # print("Turning: avoiding shot")#debug
                ai.turnRight(1)
                ai.thrust(1)

        # Turn towards unoccluded enemy
        elif aimer >= 0 and self.angleDif(rightDir, aimer) < self.angleDif(
                leftDir, aimer) and not self.enemyBehindWall(
                    0):  # if an enemy to the right, turn and shoot it
            if ai.screenEnemyX(0) >= 0:
                enemyDeg = self.angleToPointDeg(
                    (ai.selfX(), ai.selfY()),
                    (ai.screenEnemyX(0), ai.screenEnemyY(0)))
                ai.setTurnSpeed(
                    self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin,
                                  turnSpeedMax))
            else:
                enemyDeg = self.angleToPointDeg(
                    (ai.selfRadarX(), ai.selfRadarY()),
                    (ai.closestRadarX(), ai.closestRadarY()))
                ai.setTurnSpeed(
                    self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin,
                                  turnSpeedMax))
            # print("Turning: aiming right")#debug
            ai.turnRight(1)
        elif aimer >= 0 and self.angleDif(leftDir, aimer) < self.angleDif(
                rightDir, aimer) and not self.enemyBehindWall(
                    0):  # if an enemy to the left, turn and shoot it
            if ai.screenEnemyX(0) >= 0:
                enemyDeg = self.angleToPointDeg(
                    (ai.selfX(), ai.selfY()),
                    (ai.screenEnemyX(0), ai.screenEnemyY(0)))
                ai.setTurnSpeed(
                    self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin,
                                  turnSpeedMax))
            else:
                enemyDeg = self.angleToPointDeg(
                    (ai.selfRadarX(), ai.selfRadarY()),
                    (ai.closestRadarX(), ai.closestRadarY()))
                ai.setTurnSpeed(
                    self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin,
                                  turnSpeedMax))
            # print("Turning: aiming left")#debug
            ai.turnLeft(1)

        #fuzzy avoid walls ahead
        elif leftRisk > rightRisk and trackRisk > 0.5:  # and min(feelers) < self.nearLimit: #if the left wall and track walls are close, turn right
            #if enemyX >=0 and enemyY >= 0 and ai.wallBetween(selfX, selfY, enemyX, enemyY) == -1:
            ai.turnRight(1)
            # print("Turning: fuzzy right")#debug
        elif rightRisk > leftRisk and trackRisk > 0.5:  # and min(feelers) < self.nearLimit: #if the right wall and track walls are close, turn left
            # if enemyX >=0 and enemyY >= 0 and ai.wallBetween(selfX, selfY, enemyX, enemyY) == -1:
            ai.turnLeft(1)
            # print("Turning: fuzzy left")#debug

        # Turn to open space nearest the angle to the enemy
        elif self.enemyBehindWall(0) and min(feelers) > self.nearLimit:
            if angleToOpenSpace < 0:
                # print("Turning: open space left")#debug
                ai.turnLeft(1)
            elif angleToOpenSpace > 0:
                # print("Turning: open space right")#debug
                ai.turnRight(1)

        # if neural net value is not between 0.48 and 0.52 then we have to turn right or left
        elif not (turn >= 0.43 and turn <= 0.57):
            if turn < 0.43:  # turn right if value is below 0.43
                # print("Turning: neural net right")#debug
                ai.turnRight(1)
            elif turn > 0.57:  # turn left if value is below 0.57
                # print("Turning: neural net left")#debug
                ai.turnLeft(1)

        ###=== FIRING RULES ===###

        # Restrict firing to reasonably accurate attempts:
        # accurate range, enemy not behind wall and enemy close enough
        if self.headingDiff(
                heading,
                ai.aimdir(0)) < targetingAccuracy and not self.enemyBehindWall(
                    0) and ai.enemyDistance(0) < self.enemyFireDist:
            ai.fireShot()
            # print("Shot Fired")#debug
        # print("Firing Dist: ", self.enemyFireDist)#debug

        self.counter += 1

        ###=== How did we die? and other Fitness Calculations ===###

        # Fitness function information
        self.totalDists += ai.enemyDistance(0)

        if ai.enemyDistance(0) > 0:
            self.currentDist = ai.enemyDistance(0)

        if self.currentDist < self.lastDist:
            self.fitness += 1
            self.lastDist = self.currentDist
        self.fitness += 1

        alive = ai.selfAlive()
        message = ai.scanGameMsg(1)
        # print(message)#debug
        if alive == 0:
            self.framesDead += 1
            # print(self.framesDead, message)#debug

            if self.framesDead == 2:
                # print("dead now")#debug
                # Ran into wall
                if message.find("Beal-Morneault") != -1 and message.find(
                        "wall") != -1:
                    print("End of match: wall collision.")  #debug
                    self.fitness -= self.wallPenalty
                # Crashed into player
                elif message.find("crashed.") != -1:
                    print("End of match: player collision.")  #debug
                    self.fitness -= self.crashPenalty
                # Killed by bullet
                elif message.find("Beal-Morneault was") != -1:
                    print("End of match: killed by opponent.")  #debug
                    self.fitness -= self.killedPenalty
                # Killed the opponent
                elif message.find("by a shot from Beal-Morneault") != -1:
                    print("End of match: killed the opponent!")  #debug
                    self.fitness += self.killerBonus

                else:
                    print("End of match: enemy died.")

                self.fitness += (ai.selfScore() - ai.enemyScoreId(0)
                                 ) * self.scoreDiffBonusFactor
                ai.quitAI()
        else:
            self.framesDead = 0