def getSendData(turn, thrust):
    #Metadata
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackHeadRelative = (tracking - heading) / 360
    speed = ai.selfSpeed() / 10
    #Wall Feelers
    trackWall = ai.wallFeeler(500, tracking)
    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    leftF = ai.wallFeeler(500, heading + 70)
    leftB = ai.wallFeeler(500, heading + 110)
    rightF = ai.wallFeeler(500, heading - 70)
    rightB = ai.wallFeeler(500, heading - 110)
    backL = ai.wallFeeler(500, heading - 200)
    backR = ai.wallFeeler(500, heading - 160)

    data = [trackHeadRelative, speed]
    for i in [
            trackWall, frontL, frontR, leftF, leftB, rightF, rightB, backL,
            backR
    ]:
        if i == -1:
            data.append(0)
        else:
            data.append(1 - i / 500)
    for j in [turn, thrust]:
        data.append(j)

    return data
Example #2
0
def AI_loop():
    #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 + 90)
    rightWall = ai.wallFeeler(500, heading - 90)
    trackWall = ai.wallFeeler(500, tracking)
    #Thrust rules

    if ai.selfSpeed() <= 1 and frontWall >= 20:
        ai.thrust(1)
    elif trackWall < 40:
        ai.thrust(1)
    #Turn rules
    if leftWall < rightWall:
        ai.turnRight(1)
    else:
        ai.turnLeft(1)

    #Just keep shooting
    ai.fireShot()
Example #3
0
def getSendData(turn, thrust):
    #Metadata
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackHeadRelative = (tracking - heading) / 360
    speed = ai.selfSpeed() / 10
    #Wall Feelers
    trackWall = ai.wallFeeler(500, tracking)
    trackL3 = ai.wallFeeler(500, tracking + 3)
    trackL10 = ai.wallFeeler(500, tracking + 10)
    trackR3 = ai.wallFeeler(500, tracking - 3)
    trackR10 = ai.wallFeeler(500, tracking - 10)
    frontWall = ai.wallFeeler(500, heading)
    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    leftWall = ai.wallFeeler(500, heading + 90)
    rightWall = ai.wallFeeler(500, heading - 90)
    backWall = ai.wallFeeler(500, heading - 180)
    backL = ai.wallFeeler(500, heading - 185)
    backR = ai.wallFeeler(500, heading - 175)

    data = [heading / 360, tracking / 360, trackHeadRelative, speed]
    for i in [
            trackWall, trackL3, trackL10, trackR3, trackR10, frontWall, frontL,
            frontR, leftWall, rightWall, backWall, backL, backR
    ]:
        if i == -1:
            data.append(0)
        else:
            data.append(1 - i / 500)
    for j in [turn, thrust]:
        data.append(j)

    return data
Example #4
0
def getSendData(turn,thrust,shoot):
    #make all the feelers/get current sichuation data
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackHeadRelative = (tracking-heading)/360

    trackWall = ai.wallFeeler(500, tracking)
    trackL3 = ai.wallFeeler(500, tracking + 3)
    trackL10 = ai.wallFeeler(500, tracking + 10)
    trackR3 = ai.wallFeeler(500, tracking - 3)
    trackR10 = ai.wallFeeler(500, tracking - 10)

    frontWall = ai.wallFeeler(500, heading)
    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)

    leftWall = ai.wallFeeler(500, heading+90)

    rightWall = ai.wallFeeler(500,heading-90)

    backWall = ai.wallFeeler(500, heading - 180)
    backL = ai.wallFeeler(500, heading - 185)
    backR = ai.wallFeeler(500, heading - 175)

    speed = ai.selfSpeed()/10

    #get position to enemy
    enemyX = ai.screenEnemyX(0)
    enemyY = ai.screenEnemyY(0)
    selfX = ai.selfX()
    selfY = ai.selfY()
    enemyDegrees = (heading - (math.degrees(math.atan2(enemyY-selfY,enemyX-selfX))+360)%360)/360
    #enemyDegrees = heading - math.degrees(math.atan2(enemyY-selfY,enemyX-selfX))-360
    enemySpeed =  ai.enemySpeed(0)/10
    enemyMoveDirection =  ai.enemyTrackingDeg(0)
    distanceToEnemy = 1 - math.sqrt((selfX-enemyX)**2 + (selfY-enemyY)**2)/500
    relativeTracking = (tracking-180)/360-(enemyMoveDirection-180)/360

    #get shots at us
    data = [heading/360,tracking/360,trackHeadRelative,speed]
    for i in [trackWall,trackL3,trackL10,trackR3,trackR10,frontWall,frontL,frontR,leftWall,rightWall,backWall,backL,backR]:
        if i == -1:
            data.append(0)
        else:
            data.append(1 - i/500)

    for j in [enemySpeed,enemyDegrees,relativeTracking,distanceToEnemy]:
        if not math.isnan(j):
            if enemyX == -1:
                data.append(0)
            else:
                data.append(j)
        else:
            data.append(0)
    for k in [turn,thrust,shoot]:
        data.append(k)

    #print("distToEnemy",data[20]*500,"relTrack",data[19]*360)
    return data
Example #5
0
    def updateInputs(self):
        
        #The code in config is inserted into the updateInputs function so you can pull any data you want using ai.(some xpilot-ai function) and adding it with self.addInput("Some Float")
        #You can technically also add outputs with self.addOutput if you want your neural network to predict or control something beyond normal but this might not work nicely with the autogenerated controller
        #The trainer checks the size of both the input and output datasets and will build a network to accomodate these sizes automatically

        #Until the next comment is code for pulling relevant data from the game
        heading = int(ai.selfHeadingDeg())
        tracking = int(ai.selfTrackingDeg())
        
        backWall = ai.wallFeeler(500, heading - 180)
        backLeftWall = ai.wallFeeler(500,  heading - 190)
        backRightWall = ai.wallFeeler(500,  heading - 170)
        
        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)
        
        calcDir = -1
        targetX,  targetY = ai.screenEnemyX(0), ai.screenEnemyY(0)
        if targetX- ai.selfX() != 0:
            calcDir = (math.degrees(math.atan2((targetY - ai.selfY()), (targetX- ai.selfX()))) + 360)%360
    
        speed = ai.selfSpeed()
        fFan = min(frontWall,  flWall,  frWall)
        lFan = min(leftWall,  llWall,  rlWall)
        rFan = min(rightWall,  rrWall,  lrWall)
        bFan = min(backWall,  backLeftWall,  backRightWall)
        trackWall = ai.wallFeeler(500, tracking)
        
        #Everything below here is just selecting inputs for training - play around by commenting and uncommenting different inputs, or try adding your own!
        self.addInput(frontWall)
        self.addInput(leftWall)
        self.addInput(rightWall)
        self.addInput(backWall)
        self.addInput(trackWall)
        self.addInput(backLeftWall)
        self.addInput(backRightWall)


        #self.addInput(fFan)
        #self.addInput(rFan)
        #self.addInput(lFan)
        #self.addInput(bFan)


        #self.addInput(tracking)
        self.addInput(heading)
        self.addInput(calcDir) 
        self.addInput(speed)
Example #6
0
def AI_loop():
    #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 + 90)
    rightWall = ai.wallFeeler(500, heading - 90)
    trackWall = ai.wallFeeler(500, tracking)

    #Thrust rules
    print("i am heading")
    print(heading)
    print(frontWall)
    print(leftWall)
    print(rightWall)
    print("front left right")

    if ai.selfSpeed() <= 5 and frontWall >= 20:
        ai.thrust(1)
    elif trackWall < 20:
        ai.thrust(1)
    #Turn rules


#  if leftWall < rightWall:
#    ai.turnRight(1)
#  else:
#    ai.turnLeft(1)
#------------------------
    degList = []
    deg = 0
    for i in range(9):
        degree = heading + deg
        degList.append(ai.wallFeeler(500, degree))
        deg = deg + 45

    highestDist = 0
    print(degList)
    for element in degList:
        if element >= highestDist:
            highestDist = element
            print("highestDist")
            print(highestDist)
            print("index of highestdist")
            print(degList.index(highestDist))

    ai.turn(heading + ((degList.index(highestDist)) * 45))
    print("the way to turn")
    print(heading + ((degList.index(highestDist)) * 45))
    #-------------------------------

    #Just keep shooting
    ai.fireShot()
Example #7
0
    def AI_loop(self):

        # Release keys
        ai.thrust(0)

        # Controller logic
        if ai.selfSpeed() < self.speedLimit:
            ai.thrust(1)

        # Track updated information
        self.frameCount += 1
Example #8
0
    def AI_loop(self):

        # 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()
        message = ai.scanMsg(0)
        x = ai.selfX()
        y = ai.selfY()

        if "***" in message:
            coordMessage = message.split("***")[1]
            coordinatesString = coordMessage.strip().split(" [")[0]
            coordinates = eval(coordinatesString)

            closestEnemyX = coordinates[0]
            closestEnemyY = coordinates[1]
            toTurn = self.angleToPoint(x, y, closestEnemyX, closestEnemyY,
                                       heading)
            distance = self.distance(x, closestEnemyX, y, closestEnemyY)

            #-------------------- Move to target point --------------------#
            if toTurn > 0 and toTurn < 20 and distance > 300:
                ai.thrust(1)
                ai.turnLeft(0)
                ai.turnRight(0)
            elif toTurn >= 20:
                ai.turnRight(1)
            elif toTurn <= 0:
                ai.turnLeft(1)

        if self.counter % 300 == 0:
            self.foundPrey((900, 400))

        self.counter = self.counter + 1
Example #9
0
def getSendDataV1():
    #make all the feelers/get current sichuation data
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackWall = ai.wallFeeler(500, tracking)
    trackL3 = ai.wallFeeler(500, tracking + 3)
    trackL10 = ai.wallFeeler(500, tracking + 10)
    trackR3 = ai.wallFeeler(500, tracking - 3)
    trackR10 = ai.wallFeeler(500, tracking - 10)
    frontWall = ai.wallFeeler(500, heading)
    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    leftWall = ai.wallFeeler(500, heading + 90)
    rightWall = ai.wallFeeler(500, heading - 90)
    backWall = ai.wallFeeler(500, heading - 180)
    backL = ai.wallFeeler(500, heading - 185)
    backR = ai.wallFeeler(500, heading - 175)
    speed = ai.selfSpeed()

    #get position to enemy
    enemyX = ai.screenEnemyX(0)
    enemyY = ai.screenEnemyY(0)

    selfX = ai.selfX()
    selfY = ai.selfY()
    enemyDegrees = (math.degrees(math.atan2(enemyY - selfY, enemyX - selfX)) +
                    360) % 360
    enemySpeed = ai.enemySpeed(0)
    enemyMoveDirection = ai.enemyTrackingDeg(0)

    #get shots at us
    data = [heading / 360, tracking / 360]
    for i in [
            trackWall, trackL3, trackL10, trackR3, trackR10, frontWall, frontL,
            frontR, leftWall, rightWall, backWall, backL, backR
    ]:
        if i == -1:
            data.append(1)
        else:
            data.append(i / 500)
    for j in [speed, enemyDegrees / 360, enemySpeed, enemyMoveDirection / 360]:
        if not math.isnan(j):
            data.append(j)
        else:
            data.append(1)

    return data
Example #10
0
def tick():
    #
    # The API won't print out exceptions, so we have to catch and print them ourselves.
    #
    try:

        #
        # Declare global variables so we have access to them in the function
        #
        global tickCount
        global mode

        #
        # Reset the state machine if we die.
        #
        if not ai.selfAlive():
            tickCount = 0
            mode = "ready"
            return

        tickCount += 1

        #
        # Read some "sensors" into local variables, to avoid excessive calls to the API
        # and improve readability.
        #

        selfX = ai.selfX()
        selfY = ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()

        selfHeading = ai.selfHeadingRad() 
        # 0-2pi, 0 in x direction, positive toward y

        # Add more sensors readings here

        print ("tick count:", tickCount, "mode", mode)


        if mode == "ready":
            pass


    except:
        print(traceback.print_exc())
def getSendData():
    #Metadata
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackHeadRelative = (tracking - heading) / 360
    speed = ai.selfSpeed() / 10
    #Wall Feelers
    trackWall = ai.wallFeeler(500, tracking)
    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    left = ai.wallFeeler(500, heading + 90)
    right = ai.wallFeeler(500, heading - 90)
    backL = ai.wallFeeler(500, heading - 200)
    backR = ai.wallFeeler(500, heading - 160)

    data = [heading / 360, tracking / 360, trackHeadRelative, speed]
    for i in [trackWall, frontL, frontR, left, right, backL, backR]:
        if i == -1:
            data.append(0)
        else:
            data.append(1 - i / 500)
    return data
Example #12
0
def tick():

    try:

        global tickCount
        global mode

        if not ai.selfAlive():
            tickCount = 0
            mode = "ready"
            return

        tickCount += 1

        selfX = ai.selfX()
        selfY = ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()
        tracking = ai.selfTrackingRad()
        selfHeading = ai.selfHeadingRad()
        message = ai.scanTalkMsg(0)
        mass = ai.selfMass()
        friction = ai.getOption("friction")
        thrustPower = ai.getPower()

        def scalar_product(lis, n):
            return [x * n for x in lis]

        def vector_sum(list1, list2):
            return [sum(x) for x in zip(list1, list2)]

        def time_of_impact(px, py, vx, vy, s):
            a = s * s - (vx * vx + vy * vy)
            b = px * vx + py * vy
            c = px * px + py * py

            d = b * b + a * c

            t = 0  # Time
            if d >= 0:
                t = (b + math.sqrt(d)) / a
                if (t < 0):
                    t = 0
            return t

        def stopping_distance(mass, friction, thrustPower, selfSpeed):
            fForce = friction * mass
            tForce = thrustPower
            accTot = ((fForce / mass) + (tForce / (mass + 5)))
            return ((selfSpeed * selfSpeed) / (2 * accTot))

        stopping_distance = stopping_distance(mass, friction, thrustPower,
                                              selfSpeed)

        print("tick count:", tickCount, "mode", mode)

        if mode == "ready":
            print(friction, mass, selfSpeed, thrustPower)
            print(selfX, selfY)
            if "move-to" in message:
                splitmessage = message.split()
                action = splitmessage[0]

                if "move-to-stop" in action:
                    mode = "move-to-stop"
                if "move-to-pass" in action:
                    mode = "move-to-pass"

        if mode == "move-to-pass":
            splitmessage = message.split()
            coordX = float(splitmessage[1])
            coordY = float(splitmessage[2])
            print(coordX, coordY)
            distance = math.sqrt(
                abs(coordX - selfX)**2 + abs(coordY - selfY)**2)
            time = time_of_impact((coordX - selfX), (coordY - selfY), 0, 0, 10)
            targetDirection = (math.atan2(coordY - selfY, coordX - selfX))
            print(targetDirection)
            if tracking == targetDirection:
                ai.thrust()
            else:
                ai.turnToRad(targetDirection)
                ai.thrust()
                if distance < 10:
                    mode == "klar"

        if mode == "move-to-stop":
            splitmessage = message.split()
            coordX = int(splitmessage[1])
            coordY = int(splitmessage[2])
            print(coordX, coordY)
            distance = math.sqrt(
                abs(coordX - selfX)**2 + abs(coordY - selfY)**2)
            time = time_of_impact((coordX - selfX), (coordY - selfY), 0, 0,
                                  selfSpeed + 0.000001)
            target_position = vector_sum(
                (coordX - selfX, coordY - selfY),
                scalar_product((0 - selfVelX, 0 - selfVelY), time))
            targetDirection = (math.atan2(target_position[1],
                                          target_position[0]))
            print(target_position)
            print(targetDirection)
            if tickCount % 2 == 0:
                if abs(tracking - targetDirection) > 0.01:
                    ai.turnToRad(targetDirection)
            print("vinkel", (tracking - targetDirection), "tid", time)
            #if abs(targetDirection-tracking) > 0.03:
            #    ai.thrust()
            #ai.thrust()
            #    if tickCount % 2 == 0:
            #if selfSpeed < 30:
            ai.thrust()
            #if targetDirection-tracking < -0.1:
            #    ai.turnRad(-(tracking-targetDirection))
            #    ai.thrust()
            #if targetDirection-tracking < 0.1:
            #    ai.turnRad(-(tracking-targetDirection))
            #    ai.thrust()
            #if not tracking == targetDirection:
            #    ai.turnToRad(targetDirection)
            #    ai.thrust()
            #    if distance < 10:
            #        mode == "klar"
            #    print("V", selfSpeed, "tP", thrustPower, "fr", friction, "M", mass)
            print(stopping_distance, distance)
            if stopping_distance > distance:
                mode = "brake"

        if mode == "brake":
            ai.turnToRad(tracking + math.pi)
            ai.thrust()
            print(selfX, selfY)
            splitmessage = message.split()
            coordX = int(splitmessage[1])
            coordY = int(splitmessage[2])
            distance = math.sqrt(
                abs(coordX - selfX)**2 + abs(coordY - selfY)**2)
            print(distance)
            if selfSpeed < 2:
                mode = "xD"

        if mode == "xD":
            print(selfX, selfY)
            splitmessage = message.split()
            coordX = int(splitmessage[1])
            coordY = int(splitmessage[2])
            distance = math.sqrt(
                abs(coordX - selfX)**2 + abs(coordY - selfY)**2)
            print(distance)

    except:
        print(traceback.print_exc())
Example #13
0
        def dummyLoop():
            global maxSpeed, shotAngle, wallClose, dead, previousScore
            global turnedLeft, turnedRight, thrusted, shot

            #Release keys
            DataMinerBD.tthrustDummy(0)
            DataMinerBD.tturnLeftDummy(0)
            DataMinerBD.tturnRightDummy(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.tturnRightDummy(
                            1)  #If the target is to our right- turn right

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

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

                    else:
                        DataMinerBD.tturnLeftDummy(
                            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.tturnLeftDummy(1)

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

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

                else:  #Back Wall is closest- turn so that we are facing directly away from it
                    if backLeftWall < backRightWall:
                        DataMinerBD.tturnRightDummy(
                            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.tturnLeftDummy(1)

            #Rules for thrusting

            if speed < maxSpeed and frontWall > 100:  #If we are moving slowly and we won't ram into anything, accelerate
                DataMinerBD.tthrustDummy(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.tthrustDummy(1)
            elif backWall < 20:  #If there is a wall very close behind us, get away from it
                DataMinerBD.tthrustDummy(1)

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

            previousScore = ai.selfScore()
Example #14
0
def AI_loop():
  #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)
  left45Wall = ai.wallFeeler(500,heading+45)
  right45Wall = ai.wallFeeler(500,heading-45)
  left90Wall = ai.wallFeeler(500,heading+90)
  right90Wall = ai.wallFeeler(500,heading-90)
  left135Wall = ai.wallFeeler(500,heading+135)
  right135Wall = ai.wallFeeler(500,heading-135)
  backWall = ai.wallFeeler(500,heading-180) 
  trackWall = ai.wallFeeler(500,tracking)
  
  result_list = []
  risk_list = []
  for i in range(8):
    Degree = tracking+(45*i)
    Speed = ai.selfSpeed()
    Distance = ai.wallFeeler(10000,tracking+(45*i))
    result = Closing_Rate(Degree, tracking, Speed, Distance)
    result_list.append(result)
  	
    ### Fuzzy membership ###
    closing_rate, distance = Closing_Rate(Degree, tracking, Speed, Distance)
    low, medium, fast = Fuzzy_Speed(closing_rate)
    close, far = Fuzzy_Distance(distance)
    risk = Fuzzy_Risk(low, medium, fast, close, far)
    risk_list.append(risk)
  
  ## Get the direction in deg that is most risky for the robot ##
  max_risk = max(risk_list)
  track_risk = (tracking + (risk_list.index(max_risk)*45) % 360)
  min_risk = min(risk_list)
  

  #######   Shooting Ennemies  ########
  
  ##Find the closest ennemy##
  ClosestID = ai.closestShipId()
  #print(ClosestID)
  ##Get the closest ennemy direction and speed##
  ClosestSpeed = ai.enemySpeedId(ClosestID)
  ClosestDir = ai.enemyTrackingDegId(ClosestID)
  ## Get the lockheadingdeg ##
  enemy = ai.lockClose()
  #print(enemy)
  head = ai.lockHeadingDeg()
  #print(head)
  enemyDist = ai.selfLockDist()
  #print(enemyDist, ClosestSpeed, ClosestDir, head)
  int1, int2, int3, int4, int5 = Data(enemyDist, ClosestSpeed, ClosestDir, head, heading, tracking)
  output = Out(int1, int2, int3, int4, int5)
  #print(output)
  
  if(output > 0.5):
  	addDeg = output * 20
  else: 
  	addDeg = (output -0.5) * 20 * -1
  
  ## Get the angles on both side between tracking and heading ##
  dist = (heading - track_risk) % 360
  dist2 = (360 - dist) % 360
  
  ## Production system rules based off fuzzy output ##
  if(dist <= 130 and dist >= 0 and ai.selfSpeed() > 0 and max_risk >= 75):
    ai.turnLeft(1)
    #print("turning left")
  elif(dist2 <= 130 and dist2 >= 0 and ai.selfSpeed() > 0 and max_risk >= 75):
    ai.turnRight(1)
    #print("turning right")
  elif(ai.selfSpeed() <= 10):
    ai.thrust(1)
    #print("thrust")
  elif(trackWall <= 150):
    ai.thrust(1)
    #print("thrust")
  elif(enemyDist <= 400 and heading > (head) and enemyDist != 0):
    ai.turnRight(1)
    ai.fireShot()
  elif(enemyDist <= 400 and heading < (head) and enemyDist != 0):
    ai.turnLeft(1)
    ai.fireShot()
  elif(enemyDist > 400 and heading > (head + addDeg) and enemyDist != 0):
    ai.turnRight(1)
    ai.fireShot()
  elif(enemyDist > 400 and heading < (head + addDeg) and enemyDist != 0):
    ai.turnLeft(1)
    ai.fireShot()
  else:
    #print("chilling")
    ai.thrust(0)
    ai.fireShot()
Example #15
0
def AI_loop():

    chrom = [
        0, 0, 0, 1, 0, 1, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1,
        1, 0, 1, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 1,
        1, 1, 0, 0, 1, 1, 1, 0, 1, 0, 0, 1, 0, 1, 1, 0
    ]
    when_to_thrust_speed = convert(chrom[0:4])
    front_wall_distance_thrust = convert(chrom[4:8]) * 4
    back_wall_distance_thrust = convert(chrom[8:12]) * 2
    track_wall_distance_thrust = convert(chrom[12:16]) * 4
    left_wall_angle = convert(chrom[16:20]) * 3
    right_wall_angle = convert(chrom[20:24]) * 3
    back_wall_angle = convert(chrom[24:28]) * 10
    left_90_wall_angle = convert(chrom[28:32]) * 6
    right_90_wall_angle = convert(chrom[32:36]) * 6
    left_back_wall_angle = convert(chrom[36:40]) * 9
    right_back_wall_angle = convert(chrom[44:48]) * 9
    fuzzy_rate = convert(chrom[48:52])
    fuzzy_rate_1 = convert(chrom[52:56])
    angle_diff_shoot = convert(chrom[56:60])
    shot_alert_distance = convert(chrom[60:64]) * 6

    rate = fuzzy_rate
    rate1 = fuzzy_rate_1

    #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 + left_wall_angle)
    rightWall = ai.wallFeeler(500, heading - right_wall_angle)

    left90Wall = ai.wallFeeler(500, heading + left_90_wall_angle)
    right90Wall = ai.wallFeeler(500, heading - right_90_wall_angle)

    leftbackWall = ai.wallFeeler(500, heading + left_back_wall_angle)
    rightbackWall = ai.wallFeeler(500, heading - right_back_wall_angle)

    trackWall = ai.wallFeeler(500, tracking)
    backWall = ai.wallFeeler(500, heading - back_wall_angle)

    #Shooting rule - checks whether theres an enemy to aim at using aimdir,
    #and then if we're pointing at them within 10 degrees
    #check whether theres a wall between us and the enemy; if there is not then we shoot
    if ai.aimdir(0) >= 0 and -angle_diff_shoot <= ai.angleDiff(
            heading, ai.aimdir(0)) <= angle_diff_shoot and ai.screenEnemyX(
                0) >= 0 and ai.screenEnemyY(0) >= 0 and ai.wallBetween(
                    ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                    ai.screenEnemyY(0)) == -1:
        ai.fireShot()

    #Turn rules
    #standard check for enemy proximity and wall between us,
    #and if we're not aiming at them the angle is corrected
    if ai.aimdir(0) >= 0 and ai.angleDiff(
            heading, ai.aimdir(0)) > 0 and ai.wallBetween(
                ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                ai.screenEnemyY(0)) == -1:
        ai.turnLeft(1)
        print("aim turn left")
    elif ai.aimdir(0) >= 0 and ai.angleDiff(
            heading, ai.aimdir(0)) < 0 and ai.wallBetween(
                ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                ai.screenEnemyY(0)) == -1:
        ai.turnRight(1)
        print("aim turn right")

    #misc turn rules with fuzzy logic
    elif left90Wall < right90Wall and minmax(10, (rate * ai.selfSpeed()), 100):
        ai.turnRight(1)
        print("left90wall")
    elif right90Wall < left90Wall and minmax(10, (rate * ai.selfSpeed()), 100):
        ai.turnLeft(1)
        print("right90wall")
    elif leftbackWall < minmax(5, (rate1 * ai.selfSpeed()), 50):
        ai.turnRight(1)
        print("leftbackwall")
    elif rightbackWall < minmax(5, (rate1 * ai.selfSpeed()), 50):
        ai.turnLeft(1)
        print("rightbackwall")

    #default/base case turn rules
    elif leftWall < rightWall:
        ai.turnRight(1)
    else:
        ai.turnLeft(1)

#Thrust rules
#rule for speeding up when no wall in front of us
    if ai.selfSpeed(
    ) <= when_to_thrust_speed and frontWall >= front_wall_distance_thrust:
        ai.thrust(1)
        print("thrust 1")

    #dynamic thrust away from walls
    elif trackWall < track_wall_distance_thrust:
        ai.thrust(1)
        print("thrust 2")

    #thrust away from back wall
    elif backWall < back_wall_distance_thrust:
        ai.thrust(1)
        print("thrust 3")


#this block handles dodging enemy bullets

    elif ai.shotAlert(0) >= 0 and ai.shotAlert(
            0) <= shot_alert_distance and ai.shotVelDir(
                0) != -1 and ai.angleDiff(heading, ai.shotVelDir(0)) > 0:
        print("shotveldir turn left")
        ai.turnLeft(1)
        ai.thrust(1)

    elif ai.shotAlert(0) >= 0 and ai.shotAlert(
            0) <= shot_alert_distance and ai.shotVelDir(
                0) != -1 and ai.angleDiff(heading, ai.shotVelDir(0)) < 0:
        print("shotveldir turn right")
        ai.turnRight(1)
        ai.thrust(1)
def AI_loop():
    global frames, frameHistory, generation, current_chrom, population, scores, current_score
    print("frame", frames)

    #rules

    chrom = population[current_chrom][0]
    when_to_thrust_speed = convert(chrom[0:4])
    front_wall_distance_thrust = convert(chrom[4:8]) * 4
    back_wall_distance_thrust = convert(chrom[8:12]) * 2
    track_wall_distance_thrust = convert(chrom[12:16]) * 4
    left_wall_angle = convert(chrom[16:20]) * 3
    right_wall_angle = convert(chrom[20:24]) * 3
    back_wall_angle = convert(chrom[24:28]) * 10
    left_90_wall_angle = convert(chrom[28:32]) * 6
    right_90_wall_angle = convert(chrom[32:36]) * 6
    left_back_wall_angle = convert(chrom[36:40]) * 9
    right_back_wall_angle = convert(chrom[44:48]) * 9
    fuzzy_rate = convert(chrom[48:52])
    fuzzy_rate_1 = convert(chrom[52:56])
    angle_diff_shoot = convert(chrom[56:60])
    shot_alert_distance = convert(chrom[60:64]) * 6

    rate = fuzzy_rate
    rate1 = fuzzy_rate_1

    #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 + left_wall_angle)
    rightWall = ai.wallFeeler(500, heading - right_wall_angle)

    left90Wall = ai.wallFeeler(500, heading + left_90_wall_angle)
    right90Wall = ai.wallFeeler(500, heading - right_90_wall_angle)

    leftbackWall = ai.wallFeeler(500, heading + left_back_wall_angle)
    rightbackWall = ai.wallFeeler(500, heading - right_back_wall_angle)

    trackWall = ai.wallFeeler(500, tracking)
    backWall = ai.wallFeeler(500, heading - back_wall_angle)

    #Shooting rules
    if ai.aimdir(0) >= 0 and -angle_diff_shoot <= ai.angleDiff(
            heading, ai.aimdir(0)) <= angle_diff_shoot and ai.screenEnemyX(
                0) >= 0 and ai.screenEnemyY(0) >= 0 and ai.wallBetween(
                    ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                    ai.screenEnemyY(0)) == -1:
        ai.fireShot()

    #Turn rules
    if ai.aimdir(0) >= 0 and ai.angleDiff(
            heading, ai.aimdir(0)) > 0 and ai.wallBetween(
                ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                ai.screenEnemyY(0)) == -1:
        ai.turnLeft(1)
        #print("aim turn left")
    elif ai.aimdir(0) >= 0 and ai.angleDiff(
            heading, ai.aimdir(0)) < 0 and ai.wallBetween(
                ai.selfX(), ai.selfY(), ai.screenEnemyX(0),
                ai.screenEnemyY(0)) == -1:
        ai.turnRight(1)
        #print("aim turn right")
    elif left90Wall < right90Wall and minmax(10, (rate * ai.selfSpeed()), 100):
        ai.turnRight(1)
        #print("left90wall")
    elif right90Wall < left90Wall and minmax(10, (rate * ai.selfSpeed()), 100):
        ai.turnLeft(1)
        #print("right90wall")
    elif leftbackWall < minmax(5, (rate1 * ai.selfSpeed()), 50):
        ai.turnRight(1)
        #print("leftbackwall")
    elif rightbackWall < minmax(5, (rate1 * ai.selfSpeed()), 50):
        ai.turnLeft(1)
        #print("rightbackwall")
    #base case turn rules
    elif leftWall < rightWall:
        ai.turnRight(1)
    else:
        ai.turnLeft(1)

    #Thrust rules
    if ai.selfSpeed(
    ) <= when_to_thrust_speed and frontWall >= front_wall_distance_thrust:
        ai.thrust(1)
        #print("thrust 1")

    #dynamic thrust away from walls
    elif trackWall < track_wall_distance_thrust:
        ai.thrust(1)
        #print("thrust 2")

    #thrust away from back wall
    elif backWall < back_wall_distance_thrust:
        ai.thrust(1)
        #print("thrust 3")

    #Shot avoidance
    elif ai.shotAlert(0) >= 0 and ai.shotAlert(
            0) <= shot_alert_distance and ai.shotVelDir(
                0) != -1 and ai.angleDiff(heading, ai.shotVelDir(0)) > 0:
        #print("shotveldir turn left")
        ai.turnLeft(1)
        ai.thrust(1)

    elif ai.shotAlert(0) >= 0 and ai.shotAlert(
            0) <= shot_alert_distance and ai.shotVelDir(
                0) != -1 and ai.angleDiff(heading, ai.shotVelDir(0)) < 0:
        #print("shotveldir turn right")
        ai.turnRight(1)
        ai.thrust(1)

    #tracks frames alive
    if ai.selfAlive() == 1:
        frames += 1

    elif ai.selfAlive() == 0 and frames == 0:
        pass

    else:
        #adds every fitness to a list to avoid the issue of xpilot score never resetting
        scores.append(ai.selfScore())
        #base case
        if len(scores) < 2:
            current_score = scores[-1]
        else:
            current_score = scores[-1] - scores[-2]
        if current_score <= 0:
            current_score = 2

        population[current_chrom][1] = (frames**2) * current_score

        print("fitness: ", population[current_chrom][1])

        current_chrom += 1
        print("current_chrom is: ", current_chrom)

        if current_chrom >= len(population):
            current_chrom = 0
            print("current_chrom is: ", current_chrom)

            generation += 1

            fitness_scores = fitness(population)

            #writes highest fitness agent to file
            if generation % 5 == 0:
                print("first write")

                current_fitness = max(fitness_scores)
                best_individual_index = fitness_scores.index(current_fitness)
                best_individual = population[best_individual_index][0]

                newfile = open("GA_output.txt", "a+")
                newfile.write("Generation: ")
                newfile.write("\n")
                newfile.write(str(generation))
                newfile.write("\n")
                newfile.write("Best individual: ")
                newfile.write("\n")
                newfile.write(str(best_individual))
                newfile.write("\n")
                newfile.write("Best fitness: ")
                newfile.write("\n")
                newfile.write(str(current_fitness))
                newfile.write("\n")
                newfile.close()

            chrom_pair = top_individuals(population, fitness_scores)
            new_pop = []
            new_pop += crossover(chrom_pair)

            while (len(new_pop) < population_size):
                new_pop += crossover(chrom_pair)

            population = []
            population = new_pop

            #writes population to file
            if generation % 10 == 0:
                print("second write")

                popfile = open("GA_pop.txt", "a+")
                popfile.write("Generation: ")
                popfile.write("\n")
                popfile.write(str(generation))
                popfile.write("\n")

                for i in population:
                    popfile.write(str(i))
                    popfile.write("\n")
                    popfile.write("\n")

                popfile.close()

        frames = 0
Example #17
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
Example #18
0
def AI_loop():
    #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)
    left45Wall = ai.wallFeeler(500, heading + 45)
    right45Wall = ai.wallFeeler(500, heading - 45)
    left90Wall = ai.wallFeeler(500, heading + 90)
    right90Wall = ai.wallFeeler(500, heading - 90)
    left135Wall = ai.wallFeeler(500, heading + 135)
    right135Wall = ai.wallFeeler(500, heading - 135)
    backWall = ai.wallFeeler(500, heading - 180)
    trackWall = ai.wallFeeler(500, tracking)

    #######   Shooting Ennemies  ########
    ##Find the closest ennemy##
    ClosestID = ai.closestShipId()
    #print(ClosestID)
    ##Get the closest ennemy direction and speed##
    ClosestSpeed = ai.enemySpeedId(ClosestID)
    #print(ClosestSpeed)
    ClosestDir = ai.enemyTrackingDegId(ClosestID)
    #print(ClosestDir)
    ## Get the lockheadingdeg ##
    enemy = ai.lockNext()
    print(enemy)
    head = ai.lockHeadingDeg()
    print(head)
    enemyDist = ai.selfLockDist()
    print(enemyDist)

    ### Turning Rules ###
    if frontWall <= 200 and (left45Wall < right45Wall):
        print("turning right")
        ai.turnRight(1)
    elif frontWall <= 200 and (left45Wall > right45Wall):
        ai.turnLeft(1)
    elif left90Wall <= 200:
        print("turning right")
        ai.turnRight(1)
    elif right90Wall <= 200:
        print("turning left")
        ai.turnLeft(1)
    ### Thrust commands ####
    elif ai.selfSpeed() <= 10 and (frontWall >= 200) and (
            left45Wall >= 200) and (right45Wall >= 200) and (
                right90Wall >= 200) and (left90Wall >= 200) and (
                    left135Wall >= 50) and (right135Wall >= 50) and (backWall
                                                                     >= 50):
        print("go forward")
        ai.thrust(1)
    elif trackWall < 75 and ai.selfSpeed() >= 10:
        ai.thrust(1)
    elif trackWall < 50 and ai.selfSpeed() <= 10:
        ai.thrust(1)
    elif backWall <= 75:
        ai.thrust(1)
    elif left135Wall <= 75:
        ai.thrust(1)
    elif right135Wall <= 75:
        ai.thrust(1)
    ##### Shooting Ennemy Commands #####
    elif enemyDist <= 500 and heading > (head):
        ai.turnRight(1)
        ai.fireShot()
    elif enemyDist <= 500 and heading < (head):
        ai.turnLeft(1)
        ai.fireShot()
    else:
        print("chilling")
        ai.thrust(0)
Example #19
0
def tick():
    #NO EXCEPTION HANDLING
    try:
        #GLOBAL VARIABLES
        global tickCount
        global mode
        global item
        global itemId
        global lastItemCount
        global latestTask
        global mapWidth
        global mapHeight
        global maplist
        global finalPath
        global pathThread # Does not need to be global at the moment
        global searchForPath, searchQueue
        global selfVelX, selfVelY
        global selfSpeed
        global selfTracking
        global finalPosition

        #RESET IF DEAD
        if not ai.selfAlive():
            tickCount = 0

            #Create a clear function
            targetPos = []
            finalPath = []

            mode = "idle"
            return

        tickCount += 1

        #SENSORS READINGS
        selfX = ai.selfX()
        selfY = (mapHeight * ai.blockSize()) - ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()
        selfTracking = ai.selfTrackingRad()
        selfHeading = ai.selfHeadingRad()
        mass = ai.selfMass()
        friction = ai.getOption("friction")
        thrustPower = ai.getPower()

        mapWidth = ai.getOption("mapwidth")
        mapHeight = ai.getOption("mapheight")

        print ("tick count:", tickCount, "mode", mode)

        #IN THIS MODE WE ARE WAITING FOR THE PLAYER TO GIVE THE BOT INSTRUCTIONS
        if mode == "idle":
            mode, value = getMessage()

            if mode == "move":
                finalPosition = value
            elif mode == "collect":
                item = value
        #IN THIS MODE WE ARE CALUCLATING PATH USING ASTAR
        elif mode == "move":
            #GET PATH
            searchForPath = True
            searchQueue.put(searchForPath)
            try:
                finalPath = pathQueue.get(timeout=1)
            except queue.Empty:
                pass
                
            #if not finalPath:
                #print("CALCULATING PATH")
                #finalPath = getPath(pixelsToBlockSize(mapWidth, mapHeight), tuple(finalPosition), mapWidth, mapHeight)
            # else:
            #SEARCH
            print("final path", finalPath)
            
            if finalPath:
                print("I HAVE A FINAL PATH!")
                print("FINAL PATH: ", finalPath)
                searchForPath = False # We have now found a path
                searchQueue.put(searchForPath)

                print("Final Path:", finalPath)
                print("Player Pos:","(",selfY // ai.blockSize(), selfX // ai.blockSize(),")")
                targetPosition = finalPath[0]

                if finalPath[0][1] == selfX // ai.blockSize() and finalPath[0][0] == selfY // ai.blockSize():
                    if len(finalPath) > 1:
                        finalPath = finalPath[1:]
                    else:
                        print("REACHED TARGETPOS")
                        sendMessage("teacherbot")
                        finalPosition = []
                        finalPath = []
                        mode = "idle"
                    

            #MOVES
            if finalPath and finalPosition:
                print("I HAVE A FINAL POSITION!")
                stoppingDist = stopping_distance(mass, friction, thrustPower, selfSpeed)
                moveToPos(selfX, selfY, [targetPosition[1]*ai.blockSize(), targetPosition[0]*ai.blockSize()], stoppingDist)
            else:
                print("NO FINAL POSITION")

        #TODO: Search and destroy
        elif mode == "destroy":
            pass
        #TODO: Astar safe path
        elif mode == "refuel":
            fuelIndex = random.randint(0, ai.fuelstationCount())
            refueling = False

            #GET FEULSTATION X AND Y POS
            finalxPosition = ai.fuelstationBlockX(fuelIndex)
            finalyPosition = mapHeight - ai.fuelstationBlockY(fuelIndex)

            finalxAndyPosition = [finalyPosition - 1, finalxPosition]

            targetPos = finalxAndyPosition

            mode = "move"
            #TODO: USE WITH ASTAR

            if refueling:
                '''Amount of fuel in station'''
                if ai.fuelstationFuel(fuelIndex) > 0:
                    '''Keep calling to refuel'''
                    ai.refuel()
                else:
                    mode = "idle"

            '''Number of fueltanks on server'''
            #ai.tankCountServer()
            '''Number of fuelstations on server'''
            #ai.fuelstationCount()
        #IN THIS MODE WE ARE COLLECTING ITEMS
        elif mode == "collect":
            if ai.itemCountScreen() > 0:
                itemOnScreen = False
                for i in range(ai.itemCountScreen()):
                    if ai.itemType(i) == item:
                        itemId = i
                        itemOnScreen = True
                        break

                if not itemOnScreen:
                    print("No item of type " + str(item) + " on screen")
                    mode = "idle"

                itemX = ai.itemX(itemId)
                itemY = ai.itemY(itemId)
                itemVelX = ai.itemVelX(itemId)
                itemVelY = ai.itemVelY(itemId)

                deltaPosX = itemX - selfX
                deltaPosY = itemY - ai.selfY()

                deltaVelX = itemVelX - selfVelX
                deltaVelY = itemVelY - selfVelY

                time = time_of_impact(deltaPosX, deltaPosY, itemVelX, itemVelY, 10)
                targetPosition = vector_sum((deltaPosX, deltaPosY), scalar_product((deltaVelX, deltaVelY), time))

                ai.turnToRad(math.atan2(targetPosition[1], targetPosition[0]))

                if selfSpeed < 10:
                    thrust(10)
                else:
                    brake(2)

    except:
        print(traceback.print_exc())
Example #20
0
def AI_loop():
    #Release keys
    ai.thrust(0)
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.setTurnSpeed(45)

    turn, thrust = 0.5, 0
    maxSpeed = 3
    shotAngle = 9
    wallClose = 12

    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, 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)

    crashWall = min(
        trackWall, trackLWall, trackRWall
    )  #The wall we are likely to crash into if we continue on our current course

    #Rules for turning
    if wallNum == 1 or wallNum == 5 or wallNum == 6:  #Front Wall is Closest (Turn Away From It)
        ai.turnLeft(1)
        turn = 0
    elif wallNum == 2:  # Left Wall is Closest (Turn Away From It)
        ai.turnRight(1)
        turn = 1
    elif wallNum == 3:  #Right Wall is Closest (Turn Away From It)
        ai.turnLeft(1)
        turn = 0
    else:  #Back Wall is closest- turn so that we are facing directly away from it
        if backLeftWall < backRightWall:
            ai.turnRight(
                1)  #We need to turn right to face more directly away from it
            turn = 1
        if backLeftWall > backRightWall:  # We need to turn left to face more directly away from it
            ai.turnLeft(1)
            turn = 0

    #Rules for thrusting
    if speed < maxSpeed and frontWall > 100:  #If we are moving slowly and we won't ram into anything, accelerate
        ai.thrust(1)
        thrust = 1
    elif trackWall < 250 and (
            ai.angleDiff(heading, tracking) > 120
    ):  #If we are getting close to a wall, and we can thrust away from it, do so
        ai.thrust(1)
        thrust = 1
    elif backWall < 20:  #If there is a wall very close behind us, get away from it
        ai.thrust(1)
        thrust = 1
Example #21
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()
Example #22
0
  heading = int(ai.selfHeadingDeg())
  tracking = int(ai.selfTrackingDeg())
  frontWall = ai.wallFeeler(500,heading)
  left45Wall = ai.wallFeeler(500,heading+45)
  right45Wall = ai.wallFeeler(500,heading-45)
  left90Wall = ai.wallFeeler(500,heading+90)
  right90Wall = ai.wallFeeler(500,heading-90)
  left135Wall = ai.wallFeeler(500,heading+135)
  right135Wall = ai.wallFeeler(500,heading-135)
  backWall = ai.wallFeeler(500,heading-180) 
  trackWall = ai.wallFeeler(500,tracking)
  
You can run a server with the following command:
  
  #Thrust rules
  if ai.selfSpeed() <= 5 and (frontWall >= 200) and (left45Wall >= 200) and (right45Wall >= 200) and (right90Wall >= 200) and (left90Wall >= 200) and (left135Wall >= 50) and (right135Wall >= 50) and (backWall >= 50):
    ai.thrust(1)
  elif trackWall < 100:
    ai.thrust(1)
  elif frontWall <= 300 and (left45Wall < right45Wall): 
    ai.turnRight(1)
  elif left90Wall <= 200:
    ai.turnRight(1) 
  elif frontWall <= 300 and (left45Wall > right45Wall):
    ai.turnLeft(1)
  elif right90Wall <= 200:
    ai.turnLeft(1)
  elif backWall <= 30 or left135Wall <= 30 or right135Wall <= 30:
    ai.thrust(1)
  else:
    ai.thrust(0)
Example #23
0
def AI_loop():
    turn, thrust = .5, 0
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.thrust(0)
    ai.setTurnSpeed(64)

    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())

    trackWall = ai.wallFeeler(500, tracking)

    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    leftF = ai.wallFeeler(500, heading + 70)
    leftB = ai.wallFeeler(500, heading + 110)
    rightF = ai.wallFeeler(500, heading - 70)
    rightB = ai.wallFeeler(500, heading - 110)
    backL = ai.wallFeeler(500, heading - 190)
    backR = ai.wallFeeler(500, heading - 170)

    speed = ai.selfSpeed()

    def findClosestArea(x):
        return {
            frontL: 1,
            leftF: 2,
            leftB: 3,
            backL: 4,
            backR: 5,
            rightF: 6,
            rightB: 7,
            frontR: 8
        }[x]

    closestVal = min(frontL, leftF, leftB, backL, backR, rightF, rightB,
                     frontR)
    #Find the closest Wall to our ship
    closestWall = findClosestArea(closestVal)

    #Rules for turning
    #if we are heading for a wall, turn away from it
    if trackWall < 100:
        #round(abs(ai.angleDiff(heading, tracking))/3)
        ai.setTurnSpeed(15 + round(abs(ai.angleDiff(heading, tracking)) / 4))
        if ai.angleDiff(heading, tracking) > 0:
            ai.turnRight(1)
            turn = .9
        else:
            ai.turnLeft(1)
            turn = .1
#otherwise turn away from the closest wall
    elif closestWall == 1:
        ai.setTurnSpeed(64)
        ai.turnRight(1)
        turn = 1
    elif closestWall == 2:
        ai.setTurnSpeed(46)
        ai.turnRight(1)
        turn = .9
    elif closestWall == 3:
        ai.setTurnSpeed(28)
        ai.turnRight(1)
        turn = .8
    elif closestWall == 4:
        ai.setTurnSpeed(10)
        ai.turnRight(1)
        turn = .6
    elif closestWall == 5:
        ai.setTurnSpeed(10)
        ai.turnLeft(1)
        turn = .4
    elif closestWall == 6:
        ai.setTurnSpeed(28)
        ai.turnLeft(1)
        turn = .2
    elif closestWall == 7:
        ai.setTurnSpeed(26)
        ai.turnLeft(1)
        turn = .1
    elif closestWall == 8:
        ai.setTurnSpeed(64)
        ai.turnLeft(1)
        turn = 0

#if we are going too fast and are not in danger turn around
#    if speed > 2.5 and closestVal > 100:
#        ai.setTurnSpeed(64)
#        if ai.angleDiff(heading, tracking) > 0:
#            ai.turnRight(1)
#            turn = 1
#            #print("R",random())
#        else:
#            ai.turnLeft(1)
#            turn = 0
#print("L",random())

#Rules for thrusting
#if we are going slow and there isn't a wall in front of us
    if min(frontL, frontR) > 100 and speed < 2.5:
        ai.thrust(1)
        thrust = 1
#if we are going too fast and are facing away from the direction we are heading
    elif abs(ai.angleDiff(heading, tracking)) > 135 and speed > 2.5:
        ai.thrust(1)
        thrust = 1

#if we are heading toward a wall and we are not facing it
    elif trackWall < 150 and (abs(ai.angleDiff(heading, tracking)) > 120):
        ai.thrust(1)
        thrust = 1
#If there is a wall very close behind us, get away from it
    elif backL < 25 or backR < 25:
        ai.thrust(1)
        thrust = 1

    doBackPropigation = False
    if ai.selfAlive() and doBackPropigation:
        #adjust the the learning NN
        infile = open("Sem2W_1.txt", "r")
        weight = eval(infile.read())
        infile.close()

        sendData = getSendData(turn, thrust)
        weight = adjustNN(sendData, 12, 5, 2, weight)

        outfile = open("Sem2W_1.txt", "w")
        outfile.write(str(weight))
        outfile.close()
Example #24
0
def AI_loop():
    turn, thrust = .5, 0
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.thrust(0)
    ai.setTurnSpeed(64)

    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    trackWall = ai.wallFeeler(500, tracking)
    trackL3 = ai.wallFeeler(500, tracking + 3)
    trackL10 = ai.wallFeeler(500, tracking + 10)
    trackR3 = ai.wallFeeler(500, tracking - 3)
    trackR10 = ai.wallFeeler(500, tracking - 10)

    frontWall = ai.wallFeeler(500, heading)
    frontL = ai.wallFeeler(500, heading + 15)
    frontR = ai.wallFeeler(500, heading - 15)
    leftWall = ai.wallFeeler(500, heading + 90)
    leftF = ai.wallFeeler(500, heading + 65)
    leftB = ai.wallFeeler(500, heading + 115)
    rightWall = ai.wallFeeler(500, heading - 90)
    rightF = ai.wallFeeler(500, heading - 65)
    rightB = ai.wallFeeler(500, heading - 115)
    backWall = ai.wallFeeler(500, heading - 180)
    backL = ai.wallFeeler(500, heading - 195)
    backR = ai.wallFeeler(500, heading - 165)
    trackHeadRelative = (tracking - heading)
    speed = ai.selfSpeed()

    def findClosestArea(x):
        return {
            frontWall: 1,
            frontL: 2,
            leftF: 3,
            leftWall: 4,
            leftB: 5,
            backL: 6,
            backWall: 7,
            backR: 8,
            rightB: 9,
            rightWall: 10,
            rightF: 11,
            frontR: 12
        }[x]

    closestVal = min(frontWall, frontL, leftF, leftWall, leftB, backL,
                     backWall, backR, rightB, rightWall, rightF, frontR)
    #Find the closest Wall to our ship
    closestWall = findClosestArea(closestVal)
    #The wall we are likely to crash into if we continue on our current course
    crashWall = min(trackWall, trackL3, trackL10, trackR3, trackR10)

    #Rules for turning
    if closestWall == 1:
        ai.setTurnSpeed(64)
        ai.turnLeft(1)
        turn = 0
    elif closestWall == 2:
        ai.setTurnSpeed(64)
        ai.turnRight(1)
        turn = 1
    elif closestWall == 3:
        ai.setTurnSpeed(52)
        ai.turnRight(1)
        turn = .9
    elif closestWall == 4:
        ai.setTurnSpeed(40)
        ai.turnRight(1)
        turn = .8
    elif closestWall == 5:
        ai.setTurnSpeed(28)
        ai.turnRight(1)
        turn = .7
    elif closestWall == 6:
        ai.setTurnSpeed(16)
        ai.turnRight(1)
        turn = .6
    elif closestWall == 7:
        pass
    elif closestWall == 8:
        ai.setTurnSpeed(16)
        ai.turnLeft(1)
        turn = .4
    elif closestWall == 9:
        ai.setTurnSpeed(28)
        ai.turnLeft(1)
        turn = .3
    elif closestWall == 10:
        ai.setTurnSpeed(40)
        ai.turnLeft(1)
        turn = .2
    elif closestWall == 11:
        ai.setTurnSpeed(52)
        ai.turnLeft(1)
        turn = .1
    elif closestWall == 12:
        ai.setTurnSpeed(64)
        ai.turnLeft(1)
        turn = 0

#Rules for thrusting
#if we are going slow and there isn't a wall in front of us
    if min(frontWall, frontL, frontR) > 100 and speed < 4:
        ai.thrust(1)
        thrust = 1
#if we are heading toward a wall and we are not facing it
    elif crashWall < 150 and (ai.angleDiff(heading, tracking) > 90):
        ai.thrust(1)
        thrust = 1
#If there is a wall very close behind us, get away from it
    elif backWall < 20 or backL < 20 or backR < 20:
        ai.thrust(1)
        thrust = 1

    doBackPropigation = False
    if ai.selfAlive() and doBackPropigation:
        #adjust the the learning NN
        infile = open("Sem2W_2.txt", "r")
        weight = eval(infile.read())
        infile.close()

        sendData = getSendData(turn, thrust)
        weight = adjustNN(sendData, 17, 7, 2, weight)

        outfile = open("Sem2W_2.txt", "w")
        outfile.write(str(weight))
        outfile.close()
Example #25
0
def AI_loop():
  global count_frame, loop, boolean, score, population_size, chromosome_size, population, mutation_prob, crossover_prob, fitness_list, generation, generation_size, first_time, done_learning
  #Release keys
  ai.thrust(0)
  ai.turnLeft(0)
  ai.turnRight(0)

  ## Get A Chromosome in the Population -- Eventually Will go through each individual in the population ##
  current_chromosome = population[loop]
  
  ## Transform Each Gene insisde A Single Selected Chromosome. 0s & 1s Are Turned Into Intergers For Fuzzy Sets to understand ## 
  ## Each Value obtained is used to calculate the risk of each 45 degree around the agent ##
  ## Each value has its own "jump" variable which refers to the distance from each possible points/values ##
  ## The start and end represents the possible start point and end point for each variable and they depend on
  ## what the variiable is. It is to ensure a viable fuzzy set and fuzzy functions that these restrictions are applied. ##
  frontAlert = current_chromosome[0:5]
  frontAlertValue = transform(frontAlert, 25)
  
  backAlert = current_chromosome[5:9]
  backAlertValue = transform(backAlert, 25)
  
  speedAlert = current_chromosome[9:13]                 #4 bits
  speedAlertValue = transform(speedAlert, 1)            #1 jumps per value
  
  EnemyAlert = current_chromosome[13:18]                #5 bits
  EnemyAlertValue = transform(EnemyAlert, 50)           #50 jumps per value
  
  TrackSlowAlert = current_chromosome[18:22]            #4 bits
  TrackSlowAlertValue = transform(TrackSlowAlert, 25)   #25 jumps per value
  
  TrackFastAlert = current_chromosome[22:26]            #4 bits 
  TrackFastAlertValue = transform(TrackFastAlert, 25)   #25 jumps per value
  
  BulletAlert = current_chromosome[26:32]               #4 bits 
  BulletAlertValue = transform(BulletAlert, 15)         #15 jumps per value


  ## Get values of variables for Wall Feelers, Head & Tracking ##
  heading = int(ai.selfHeadingDeg())
  tracking = int(ai.selfTrackingDeg())
  frontWall = ai.wallFeeler(500,heading)
  left45Wall = ai.wallFeeler(500,heading+45)
  right45Wall = ai.wallFeeler(500,heading-45)
  left90Wall = ai.wallFeeler(500,heading+90)
  right90Wall = ai.wallFeeler(500,heading-90)
  left135Wall = ai.wallFeeler(500,heading+135)
  right135Wall = ai.wallFeeler(500,heading-135)
  backWall = ai.wallFeeler(500,heading-180) 
  trackWall = ai.wallFeeler(500,tracking)
  
  ####### Getters Variable Regarding Important Information About Enemies ########
  ##Find the closest ennemy##
  enemy = ai.lockClose()
  ## Get the lockheadingdeg of enemy ##
  head = ai.lockHeadingDeg()
  ## Get the dstance from enemy ##
  enemyDist = ai.selfLockDist()

  ## If the Enemy is Dead ##
  if(ai.selfAlive() == 0 and boolean == False): 

    ## Calculate Fitness Current Population ##
    score_previous = score
    score_current = ai.selfScore()
    fitness_value = fitness(population, count_frame, score_previous, score_current)
    fitness_list.append(fitness_value)

    ## If it went through the whole population and ready to move to next generation ##
    if((loop+1) == population_size):
      ## Output the fitness of population to allow user to see if learning is happening ##
      print("Generation:", generation)
      print("Agent Fitness:")
      print(fitness_list)
      print("Average Fitness:", statistics.mean(fitness_list))
      print("Best Fitness:", max(fitness_list))
      
      ## Finding the optimal chromosome to output it in data file ##
      string_maxChromosome = ""
      for chrom_max in range(chromosome_size):
         string_maxChromosome = string_maxChromosome + str(population[fitness_list.index(max(fitness_list))][chrom_max])

      ## Formatting entire population in a big string to register it in excel file##
      string_population = ""
      for pop in range(population_size):
        for pop_chrom in range(chromosome_size):
          string_population = string_population + str(population[pop][pop_chrom])
        if(pop != (population_size-1)):
          string_population = string_population + ","

      ## Formatting entire population's fitness in a big string to register it in excel file##
      string_fitness = ""
      for fit in range(len(fitness_list)):
        string_fitness = string_fitness + str(fitness_list[fit])
        if(fit != (len(fitness_list)-1)):
          string_fitness = string_fitness + ","


      ## Output Data into Excel File ##
      titles = ["Generation", "Average Fitness", "Best Fitness","Population Size", "Chromosome Size", "Crossover Probability", "Mutation Probability", "Best Chromosome", "Entire Population Chromosome", "Entire Population Fitness"]
      data = [generation, statistics.mean(fitness_list), max(fitness_list), population_size, chromosome_size, crossover_prob, mutation_prob, string_maxChromosome, string_population, string_fitness]
      first_time = Save_Data("Tiger_Training_Data.xls", 0, titles, data, first_time)

      ## Select Next Generation -- Apply Crossover & Mutation ##
      new_population = select(population, fitness_list)
      new_population = crossover(new_population, chromosome_size, population_size, crossover_prob)
      new_population = mutate(new_population, chromosome_size, mutation_prob)
      population = new_population
      
      loop = 0
      count_frame = 0
      generation += 1
      fitness_list.clear()
  
      ### DONE -- QUIT ###
      if (generation == generation_size):
        quitAI()
 
    ## Move to the next individual in population ## 
    else:   
      loop += 1 
      count_frame = 0
    boolean = True


  else:

    ## The agent is Alive ##
    if(ai.selfAlive() == 1):
      
      ### Turning Rules ###
      if frontWall <= frontAlertValue and (left45Wall < right45Wall) and ai.selfSpeed() > speedAlertValue: 
        ai.turnRight(1)
      elif frontWall <= frontAlertValue and (left45Wall > right45Wall) and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
      elif left90Wall <= frontAlertValue and ai.selfSpeed() > speedAlertValue:
        ai.turnRight(1) 
      elif right90Wall <= frontAlertValue and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
      ### Thrust commands ####
      elif ai.selfSpeed() <= speedAlertValue and (frontWall >= frontAlertValue) and (left45Wall >= frontAlertValue) and (right45Wall >= frontAlertValue) and (right90Wall >= frontAlertValue) and (left90Wall >= frontAlertValue) and (left135Wall >= backAlertValue) and (right135Wall >= backAlertValue) and (backWall >= backAlertValue):
        ai.thrust(1)
      elif trackWall <= TrackFastAlertValue and ai.selfSpeed() >= speedAlertValue:
        ai.thrust(1)
      elif trackWall <= TrackSlowAlertValue and ai.selfSpeed() <= speedAlertValue:
        ai.thrust(1)
      elif backWall <= TrackFastAlertValue and ai.selfSpeed() >= speedAlertValue:
        ai.thrust(1)
      elif backWall <= TrackSlowAlertValue and ai.selfSpeed() <= speedAlertValue:
        ai.thrust(1)  
      elif left135Wall <= TrackFastAlertValue and ai.selfSpeed() >= speedAlertValue:
        ai.thrust(1)
      elif left135Wall <= TrackSlowAlertValue and ai.selfSpeed() <= speedAlertValue:
        ai.thrust(1)
      elif right135Wall <= TrackFastAlertValue and ai.selfSpeed() >= speedAlertValue:
        ai.thrust(1)
      elif right135Wall <= TrackSlowAlertValue and ai.selfSpeed() <= speedAlertValue:
        ai.thrust(1)
      ##### Bullet Avoidance Commands #####
      elif ai.shotAlert(0) >= 0 and ai.shotAlert(0) <= BulletAlertValue:
        if ai.angleDiff(heading, ai.shotVelDir(0)) > 0 and ai.selfSpeed() <= speedAlertValue:
          ai.turnLeft(1)
          ai.thrust(1)
        elif ai.angleDiff(heading, ai.shotVelDir(0)) < 0 and ai.selfSpeed() <= speedAlertValue: 
          ai.turnRight(1)
          ai.thrust(1)
        elif ai.angleDiff(heading, ai.shotVelDir(0)) > 0 and ai.selfSpeed() > speedAlertValue:
          ai.turnLeft(1)
        else:
          ai.turnRight(1)
      ##### Shooting Ennemy Commands #####
      elif enemyDist <= EnemyAlertValue and heading > (head) and ai.selfSpeed() > speedAlertValue:
        ai.turnRight(1)
        ai.fireShot()
      elif enemyDist <= EnemyAlertValue and heading < (head) and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
        ai.fireShot()
      elif ai.selfSpeed() < speedAlertValue:
        ai.thrust(1)
      else:
        ai.thrust(0)

      count_frame += 3
      boolean = False
Example #26
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
Example #27
0
def AI_loop():

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

    ## Get values of variables for Wall Feelers, Head & Tracking ##
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    frontWall = ai.wallFeeler(500, heading)
    left45Wall = ai.wallFeeler(500, heading + 45)
    right45Wall = ai.wallFeeler(500, heading - 45)
    left90Wall = ai.wallFeeler(500, heading + 90)
    right90Wall = ai.wallFeeler(500, heading - 90)
    left135Wall = ai.wallFeeler(500, heading + 135)
    right135Wall = ai.wallFeeler(500, heading - 135)
    backWall = ai.wallFeeler(500, heading - 180)
    trackWall = ai.wallFeeler(500, tracking)

    ####### Getters Variable Regarding Important Information About Enemies ########
    ##Find the closest ennemy##
    enemy = ai.lockClose()
    ## Get the lockheadingdeg of enemy ##
    head = ai.lockHeadingDeg()
    ## Get the dstance from enemy ##
    enemyDist = ai.selfLockDist()

    ##### Production System Rules ######
    ### Turning Rules ###
    if frontWall <= frontAlertValue and (
            left45Wall < right45Wall) and ai.selfSpeed() > speedAlertValue:
        ai.turnRight(1)
    elif frontWall <= frontAlertValue and (
            left45Wall > right45Wall) and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
    elif left90Wall <= frontAlertValue and ai.selfSpeed() > speedAlertValue:
        ai.turnRight(1)
    elif right90Wall <= frontAlertValue and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
    ### Thrust commands ####
    elif ai.selfSpeed() <= speedAlertValue and (
            frontWall >=
            frontAlertValue) and (left45Wall >= frontAlertValue) and (
                right45Wall >=
                frontAlertValue) and (right90Wall >= frontAlertValue) and (
                    left90Wall >=
                    frontAlertValue) and (left135Wall >= backAlertValue) and (
                        right135Wall >= backAlertValue) and (backWall >=
                                                             backAlertValue):
        ai.thrust(1)
    elif trackWall <= TrackFastAlertValue and ai.selfSpeed(
    ) >= speedAlertValue:
        ai.thrust(1)
    elif trackWall <= TrackSlowAlertValue and ai.selfSpeed(
    ) <= speedAlertValue:
        ai.thrust(1)
    elif backWall <= TrackFastAlertValue and ai.selfSpeed() >= speedAlertValue:
        ai.thrust(1)
    elif backWall <= TrackSlowAlertValue and ai.selfSpeed() <= speedAlertValue:
        ai.thrust(1)
    elif left135Wall <= TrackFastAlertValue and ai.selfSpeed(
    ) >= speedAlertValue:
        ai.thrust(1)
    elif left135Wall <= TrackSlowAlertValue and ai.selfSpeed(
    ) <= speedAlertValue:
        ai.thrust(1)
    elif right135Wall <= TrackFastAlertValue and ai.selfSpeed(
    ) >= speedAlertValue:
        ai.thrust(1)
    elif right135Wall <= TrackSlowAlertValue and ai.selfSpeed(
    ) <= speedAlertValue:
        ai.thrust(1)
    ##### Bullet Avoidance Commands #####
    elif ai.shotAlert(0) >= 0 and ai.shotAlert(0) <= BulletAlertValue:
        if ai.angleDiff(
                heading,
                ai.shotVelDir(0)) > 0 and ai.selfSpeed() <= speedAlertValue:
            ai.turnLeft(1)
            ai.thrust(1)
        elif ai.angleDiff(
                heading,
                ai.shotVelDir(0)) < 0 and ai.selfSpeed() <= speedAlertValue:
            ai.turnRight(1)
            ai.thrust(1)
        elif ai.angleDiff(
                heading,
                ai.shotVelDir(0)) > 0 and ai.selfSpeed() > speedAlertValue:
            ai.turnLeft(1)
        else:
            ai.turnRight(1)
    ##### Shooting Ennemy Commands #####
    elif enemyDist <= EnemyAlertValue and heading > (
            head) and ai.selfSpeed() > speedAlertValue:
        ai.turnRight(1)
        ai.fireShot()
    elif enemyDist <= EnemyAlertValue and heading < (
            head) and ai.selfSpeed() > speedAlertValue:
        ai.turnLeft(1)
        ai.fireShot()
    elif ai.selfSpeed() < speedAlertValue:
        ai.thrust(1)
    else:
        ai.thrust(0)
Example #28
0
def tick():
    #
    # The API won't print out exceptions, so we have to catch and print them ourselves.
    #
    try:

        #
        # Declare global variables so we have access to them in the function
        #
        global tickCount
        global mode

        #
        # Reset the state machine if we die.
        #
        if not ai.selfAlive():
            tickCount = 0
            mode = "ready"
            return

        tickCount += 1

        #
        # Read some "sensors" into local variables, to avoid excessive calls to the API
        # and improve readability.
        #

        selfX = ai.selfX()
        selfY = ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()
        shotSpeed = ai.getOption("shotSpeed")

        selfHeading = ai.selfHeadingRad()
        # 0-2pi, 0 in x direction, positive toward y

        # Add more sensors readings here

        print ("tick count:", tickCount, "mode", mode)

        def scalar_product(lis, n):
            return [x * n for x in lis]

        def vector_sum(list1, list2):
            return [sum(x) for x in zip(list1, list2)]

        # [a, b, c] [d, e, f]
        # [a,d] [b, e] [c, f]

        def time_of_impact(px, py, vx, vy, s):
            a = s * s - (vx * vx + vy * vy)
            b = px * vx + py * vy
            c = px * px + py * py

            d = b*b + a*c

            t = 0 # Time
            if d >= 0:
                t = (b + math.sqrt(d)) / a
                if (t < 0):
                    t = 0
            return t


        closest_asteroid_id = 0

        if mode == "ready":
            #print("self vel Y: ", selfVelY)
            if ai.selfSpeed() > 7: # We're going too fast!!!
                mode = "brake"

            # Find closest asteroid
            if tickCount % 1 == 0:
                for i in range(ai.asteroidCountScreen()):
                    #if not 130 <= ai.radarType(i) <= 133: # We're only looking for asteroids.
                    #    continue
                    radar_dist = ai.asteroidDist(i)
                    if radar_dist < ai.asteroidDist(closest_asteroid_id):
                        closest_asteroid_id = i

                if ai.asteroidCountScreen() > 0:
                    mode = "aim"

        if mode == "aim":
            asteroidX = ai.asteroidX(closest_asteroid_id)
            asteroidY = ai.asteroidY(closest_asteroid_id)
            asteroidVelX = ai.asteroidVelX(closest_asteroid_id)
            asteroidVelY = ai.asteroidVelY(closest_asteroid_id)

            if asteroidX - selfX > ai.mapWidthPixels()/1.2:
                print("Target is to the right. Seen to the left")
                dx = ai.mapWidthPixels() - asteroidX
                asteroidX = -dx
                #targetPosition[0] -= ai.mapWidthPixels()
            if selfX - asteroidX > ai.mapWidthPixels()/1.2:
                print("Target is to the left. Seen to the right")
                dx = asteroidX
                asteroidX = ai.mapWidthPixels() + dx

                #targetPosition[0] += ai.mapWidthPixels()

            if asteroidY - selfY > ai.mapHeightPixels()/1.2:
                print("Target is above. Seen below")
                dx = ai.mapHeightPixels() - asteroidY
                asteroidY = -dx
                #targetPosition[1] -= ai.mapHeightPixels()
            if selfY - asteroidY > ai.mapHeightPixels()/1.2:
                print("Target is below. Seen above.")
                dx = asteroidY
                asteroidY = ai.mapHeightPixels() + dy
                #targetPosition[1] += ai.mapHeightPixels()

            time = time_of_impact(asteroidX - selfX, asteroidY - selfY,
                                    asteroidVelX, asteroidVelY, shotSpeed)

            targetPosition = vector_sum((asteroidX - selfX, asteroidY - selfY),
                                scalar_product((asteroidVelX, asteroidVelY), time*1.1))

            print("Map size x: ", ai.mapWidthPixels())

            targetAngle = math.atan2(targetPosition[1], targetPosition[0])
            ai.turnToRad(targetAngle)
            if abs(selfHeading - targetAngle) % 2*math.pi < 0.8:
                print("Firing at", targetPosition[0], ",", targetPosition[1])
                ai.fireShot()
            mode = "ready"

        if mode == "brake":
            velocityVector = (selfVelX, selfVelY)
            targetAngle = math.pi + (math.atan2(velocityVector[1], velocityVector[0])) # Negative velocity vector
            ai.turnToRad(targetAngle)
            ai.thrust()
            selfVel = velocityVector[0] * velocityVector[0] + velocityVector[1] * velocityVector[1]
            if selfVel < 3: # The bot has come to a stop.
                mode = "ready"

    except:
        print(traceback.print_exc())
Example #29
0
def tick():
    #
    # The API won't print out exceptions, so we have to catch and print them ourselves.
    #
    try:

        #
        # Declare global variables so we have access to them in the function
        #
        global tickCount
        global mode
        global targetId
        global lis

        #
        # Reset the state machine if we die.
        #
        if not ai.selfAlive():
            tickCount = 0
            mode = "ready"
            return

        tickCount += 1

        #
        # Read some "sensors" into local variables, to avoid excessive calls to the API
        # and improve readability.
        #

        selfX = ai.selfX()
        selfY = ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()

        selfHeading = ai.selfHeadingRad()
        selfTracking = ai.selfTrackingRad()
        # 0-2pi, 0 in x direction, positive toward y

        # Add more sensors readings here

        print("tick count:", tickCount, "mode", mode)

        if mode == "ready":
            for i in range(4):
                if ai.targetAlive(i):
                    targetId = i
                    break
            xDiff = ai.targetX(targetId) - ai.selfX()
            yDiff = ai.targetY(targetId) - ai.selfY()
            targetDirection = math.atan2(yDiff, xDiff)
            ai.turnToRad(targetDirection)
            ai.setPower(20)
            if selfSpeed < 20:
                ai.thrust()

            if xDiff < 400 and yDiff < 400:
                mode = "brake"

            if abs(selfHeading - selfTracking) > 0.1 and selfSpeed > 20:
                mode = "stab"

        elif mode == "stab":
            if selfSpeed < 2:
                mode = "ready"
            else:
                ai.setPower(50)
                ai.turnToRad(math.pi + ai.selfTrackingRad())
                ai.thrust()
        elif mode == "brake":
            if selfSpeed < 2:
                mode = "aim"
            else:
                ai.setPower(50)
                ai.turnToRad(math.pi + ai.selfTrackingRad())
                ai.thrust()
        elif mode == "aim":
            xDiff = ai.targetX(targetId) - ai.selfX()
            yDiff = ai.targetY(targetId) - ai.selfY()
            targetDirection = math.atan2(yDiff, xDiff)
            ai.turnToRad(targetDirection)
            angleDiff = abs(targetDirection - selfHeading)
            if angleDiff < 0.25 or angleDiff > 2 * math.pi - 0.25:
                mode = "shoot"
        elif mode == "shoot":
            ai.fireShot()
            xDiff = ai.targetX(targetId) - ai.selfX()
            yDiff = ai.targetY(targetId) - ai.selfY()
            targetDirection = math.atan2(yDiff, xDiff)
            ai.turnToRad(targetDirection)
            if not ai.targetAlive(targetId):
                mode = "ready"

    except:
        print(traceback.print_exc())
Example #30
0
def tick():
    #NO EXCEPTION HANDLING
    try:
        #
        #GLOBAL VARIABLES
        #

        #XPILOT-SPEC
        global tickCount
        global mode
        global selfVelX, selfVelY
        global selfX, selfY
        global selfSpeed
        global selfTracking

        #ITEMS
        global item
        global itemId
        global lastItemCount

        #COMMUNICATION
        global latestTask

        #A*
        global mapWidth
        global mapHeight
        global maplist
        global finalPath
        global finalPosition

        #REFUELING
        global fuelIndex
        global stationId

        #MULTITHREADING
        global maplistQueue
        global searchForPath
        global searchQueue
        global pathQueue

        #RESET IF DEAD
        if not ai.selfAlive():
            tickCount = 0

            #CLEAR A*
            finalPosition = []
            finalPath = []

            mode = "idle"
            return

        tickCount += 1

        #
        #SENSORS READINGS
        #

        #XPILOT-SPEC
        selfX = ai.selfX()
        selfY = (mapHeight * ai.blockSize()) - ai.selfY()
        selfVelX = ai.selfVelX()
        selfVelY = ai.selfVelY()
        selfSpeed = ai.selfSpeed()
        selfTracking = ai.selfTrackingRad()
        selfHeading = ai.selfHeadingRad()

        #DOES NOT EXIST FIRST TICKS
        if tickCount > 6:
            mass = ai.selfMass()

        thrustPower = ai.getPower()
        friction = ai.getOption("friction")
        mapWidth = ai.getOption("mapwidth")
        mapHeight = ai.getOption("mapheight")

        print ("tick count:", tickCount, "mode", mode)

        #IN THIS MODE WE ARE WAITING FOR THE PLAYER TO GIVE THE BOT INSTRUCTIONS
        if mode == "idle":
            mode, value, latestTask = getMessage()

            if mode == "move":
                finalPosition = value
            elif mode == "collect":
                item = value
            elif mode == "refuel":
                fuelIndex = value

        #IN THIS MODE WE ARE CALUCLATING PATH USING ASTAR
        elif mode == "move":

            #MULTITHREADING
            searchForPath = True
            searchQueue.put(searchForPath)
            try:
                finalPath = pathQueue.get(timeout=1)
                maplist = maplistQueue.get(timeout=1)
            except queue.Empty:
                pass

            #SEARCH-PATH-PART
            if not finalPath:
                print("CALCULATING PATH")
                maplist, finalPath = getPath(pixelsToBlockSize(mapWidth, mapHeight), tuple(finalPosition), mapWidth, mapHeight)
                print("CALCULATED MAPLIST LENGTH:", len(maplist))
                print("CALCULATED FINAL PATH:", len(finalPath))
            else:
                if maplist:
                    printMap(finalPath, True)

                #MULTITHREADING
                searchForPath = False
                searchQueue.put(searchForPath)

                print("Final Path:", finalPath)
                print("Player Pos:","(",selfY // ai.blockSize(), selfX // ai.blockSize(),")")
                targetPosition = finalPath[0]

                if finalPath[0][1] == selfX // ai.blockSize() and finalPath[0][0] == selfY // ai.blockSize():
                    if len(finalPath) > 1:
                        finalPath = finalPath[1:]
                    else:
                        print("REACHED TARGETPOS")
                        sendMessage("teacherbot")

                        finalX = finalPosition[1]
                        finalY = finalPosition[0]
                        finalPosition = []
                        finalPath = []

                        print(latestTask)
                        if "refuel" in latestTask:
                            mode = "refueling"
                        elif latestTask == "use-item mine":
                            mode = useMine(finalX, finalY)
                        elif latestTask == "use-item missile":
                            mode = useMissile(finalX, finalY)
                        elif latestTask == "use-item laser":
                            mode = useLaser(finalX, finalY)
                        else:
                            mode = "idle"

            #MOVE-PART
            if finalPosition:
                stoppingDist = stopping_distance(mass, friction, thrustPower, selfSpeed)
                moveToPos(selfX, selfY, [targetPosition[1]*ai.blockSize(), targetPosition[0]*ai.blockSize()], stoppingDist)

        #IF OTHER PLAYER IS SHOOTING TOWARDS YOU FLEE
        elif mode == "flee":
            if ai.selfItem(18):
                usePhasing(0, 0)
            elif ai.selfItem(17):
                useHyperJump(0, 0)
            elif ai.selfItem(10):
                useEcm(0,0)
            elif ai.selfItem(15):
                useEmergencyShield(0, 0)
            else:
                ai.shield()

        #IN THIS MODE WE ARE REFUELING
        elif mode == "refuel":

            mode, finalPath, finalPosition = moveToFuelStation()
        elif mode == "refueling":
            '''Amount of fuel in station'''
            if ai.fuelstationFuel(fuelIndex) > 0:
                '''Keep calling to refuel'''
                ai.refuel()
            else:
                mode = "idle"

        #IN THIS MODE WE ARE COLLECTING ITEMS
        elif mode == "collect":
            if ai.itemCountScreen() > 0:
                itemOnScreen = False
                for i in range(ai.itemCountScreen()):
                    if ai.itemType(i) == item:
                        itemId = i
                        itemOnScreen = True
                        break

                if not itemOnScreen:
                    print("No item of type " + str(item) + " on screen")
                    mode = "idle"

                collectAim(itemId)

                if selfSpeed < 10:
                    thrust(10)
                else:
                    brake(2)

    except:
        print(traceback.print_exc())
def AI_loop():
    turn, thrust = .5, 0
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.thrust(0)
    ai.setTurnSpeed(64)

    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())

    trackWall = ai.wallFeeler(500, tracking)

    frontL = ai.wallFeeler(500, heading + 10)
    frontR = ai.wallFeeler(500, heading - 10)
    leftF = ai.wallFeeler(500, heading + 70)
    leftB = ai.wallFeeler(500, heading + 110)
    rightF = ai.wallFeeler(500, heading - 70)
    rightB = ai.wallFeeler(500, heading - 110)
    backL = ai.wallFeeler(500, heading - 200)
    backR = ai.wallFeeler(500, heading - 160)

    trackHeadRelative = (tracking - heading)
    speed = ai.selfSpeed()

    def findClosestArea(x):
        return {
            frontL: 1,
            leftF: 2,
            leftB: 3,
            backL: 4,
            backR: 5,
            rightF: 6,
            rightB: 7,
            frontR: 8
        }[x]

    closestVal = min(frontL, leftF, leftB, backL, backR, rightF, rightB,
                     frontR)
    #Find the closest Wall to our ship
    closestWall = findClosestArea(closestVal)

    #Rules for turning

    if closestWall == 1:
        ai.setTurnSpeed(64)
        ai.turnRight(1)
        turn = 1
    elif closestWall == 2:
        ai.setTurnSpeed(46)
        ai.turnRight(1)
        turn = .9
    elif closestWall == 3:
        ai.setTurnSpeed(28)
        ai.turnRight(1)
        turn = .8
    elif closestWall == 4:
        ai.setTurnSpeed(10)
        ai.turnRight(1)
        turn = .6
    elif closestWall == 5:
        ai.setTurnSpeed(10)
        ai.turnLeft(1)
        turn = .4
    elif closestWall == 6:
        ai.setTurnSpeed(28)
        ai.turnLeft(1)
        turn = .2
    elif closestWall == 7:
        ai.setTurnSpeed(26)
        ai.turnLeft(1)
        turn = .1
    elif closestWall == 8:
        ai.setTurnSpeed(64)
        ai.turnLeft(1)
        turn = 0

#Rules for thrusting
#if we are going slow and there isn't a wall in front of us
    if min(frontL, frontR) > 100 and speed < 3:
        ai.thrust(1)
        thrust = 1
#if we are heading toward a wall and we are not facing it
    elif trackWall < 150 and (ai.angleDiff(heading, tracking) > 90):
        ai.thrust(1)
        thrust = 1
#If there is a wall very close behind us, get away from it
    elif backL < 20 or backR < 20:
        ai.thrust(1)
        thrust = 1

    doBackPropigation = True
    if ai.selfAlive() and doBackPropigation:
        #adjust the the learning NN
        infile = open("Sem2W_1.txt", "r")
        weight = eval(infile.read())
        infile.close()

        sendData = getSendData(turn, thrust)
        weight = adjustNN(sendData, 12, 5, 2, weight)

        outfile = open("Sem2W_1.txt", "w")
        outfile.write(str(weight))
        outfile.close()