コード例 #1
0
ファイル: message.py プロジェクト: mvppjr/predator-prey
    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
コード例 #2
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)
コード例 #3
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
コード例 #4
0
ファイル: integration.py プロジェクト: mvppjr/predator-prey
    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
コード例 #5
0
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
コード例 #6
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()
        x = ai.selfX()
        y = ai.selfY()
        coordinate = self.grid[self.counter][1]
        targetX = coordinate[0]
        targetY = coordinate[1]
        toTurn = self.angleToPoint(x, y, targetX, targetY, heading)
        distance = self.distance(x, targetX, y, targetY)

        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 abs(turning) <= 165:
                ai.turnRight(1)
            elif negateAngle >= 10:
                ai.turnLeft(1)

        else:

            #-------------------- Print statements --------------------#
            # print("(x, y): (",x,",",y,")")
            print("destination: ", self.grid[self.counter % self.gridLength])
            # print("distance: ", distance)
            # print("closestEnemyX: ", targetX)
            # print("closestEnemyY: ", targetY)
            # print("screen enemy? ", ai.screenEnemyXId(ai.closestShipId()))
            # print("toTurn: ", toTurn)
            print("speed: ", speed)
            print("")

            #-------------------- Move to target point --------------------#
            if abs(toTurn) < 10 and distance > 100:
                print("Lock!")
                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 distance < 200:
                self.markSpotChecked(coordinate)
                self.checkSearchComplete()

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

            #---------------- Turn rules ----------------#

            # 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
コード例 #7
0
def AI_loop():
    """ The main loop for this agent!
        Greenock is a rule-based expert system.
    """

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

    # Heuristics
    sideFeelerOffset = 15  # Offsets from heading for wall feelers (degrees)
    nearLimit = 20 * ai.selfSpeed(
    )  # Threshold for close objects (xp distance units)
    shotDanger = 80  # Threshold for close bullets (xp distance units)

    # Reset everything else
    ai.setTurnSpeedDeg(20)  # Artificial handicap!

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

    frontLeftWall = ai.wallFeeler(500, heading + sideFeelerOffset)
    frontRightWall = ai.wallFeeler(500, heading - sideFeelerOffset)

    rshipnum = ai.closestShipId()

    # Combat decisions
    if (ai.shotAlert(0) > -1) and (ai.shotAlert(0) < shotDanger):
        ai.turnToDeg(angleDiff(heading, ai.angleAdd(ai.shot_idir(0), 90)))
        ai.thrust(1)
    elif (ai.closestShipId() > -1):
        ai.turnToDeg(angleDiff(heading, ai.aimdir(ai.closestShipId())))
        ai.fireShot()
    elif (rshipnum > -1):
        ai.turnToDeg(angleDiff(heading, ai.aimdir(ai.closestShipId)))
        if (ai.selfSpeed() < 10):
            ai.thrust(1)
        else:
            ai.fireShot()

    # Navigation decisions
    if ((frontRightWall == frontLeftWall) and (frontRightWall < nearLimit)
            and (ai.selfSpeed() > 1)):
        ai.turnToDeg(angleDiff(heading, ai.angleAdd(180,
                                                    ai.selfTrackingDeg())))
        ai.thrust(1)
    elif ((frontRightWall < frontLeftWall) and (frontRightWall < nearLimit)
          and (ai.selfSpeed() > 1)):
        ai.turnToDeg(
            angleDiff(heading,
                      ai.angleAdd(180, ai.angleAdd(-15,
                                                   ai.selfTrackingDeg()))))
        ai.thrust(1)
    elif ((frontRightWall > frontLeftWall) and (frontRightWall < nearLimit)
          and (ai.selfSpeed() > 1)):
        ai.turnToDeg(
            angleDiff(heading,
                      ai.angleAdd(180, ai.angleAdd(15, ai.selfTrackingDeg()))))
        ai.thrust(1)
コード例 #8
0
    def AI_loop(self):

        # print("AI_LOOP")

        if ai.selfAlive() == 0:
            print("selfAlive is 0")

            # if ai.selfAlive() == 0 and time2quit:
            outputFile = open("output.txt", "w")
            outputFile.write(str(self.counter))
            outputFile.close()
            # ai.quitAI()

        # print(countFrames)

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

        turnSpeedMin = 15
        turnSpeedMax = 64

        # Heuristics
        #frontFeelerOffset = 35
        ffo = self.frontFeelerOffset
        rfo = self.rearFeelerOffset
        perpFeelerOffset = 90
        #rearFeelerOffset = 135

        # speedLimit = 5
        lowSpeedLimit = 2
        targetingAccuracy = 4  # 1/2 tolerance in deg for aiming accuracy
        shotIsDangerous = 130

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

        # Wall feeling
        feelers = []

        frontWall = ai.wallFeeler(750, heading)
        leftWall = ai.wallFeeler(500, heading + perpFeelerOffset)
        rightWall = ai.wallFeeler(500, heading - perpFeelerOffset)
        trackWall = ai.wallFeeler(750, tracking)
        rearWall = ai.wallFeeler(250, heading - 180)
        backLeftWall = ai.wallFeeler(500, heading + round(rfo))
        backRightWall = ai.wallFeeler(500, heading - round(rfo))
        frontLeftWall = ai.wallFeeler(500, heading + round(ffo))
        frontRightWall = ai.wallFeeler(500, heading - round(ffo))

        feelers.append(frontWall)
        feelers.append(leftWall)
        feelers.append(rightWall)
        feelers.append(trackWall)
        feelers.append(rearWall)
        feelers.append(backLeftWall)
        feelers.append(backRightWall)
        feelers.append(frontLeftWall)
        feelers.append(frontRightWall)

        if min(feelers) < self.veryNearLimit:
            self.speedLimit = lowSpeedLimit

        # Movement controls

        # Compute angles to the nearest things
        m = self.angleToPointDeg((ai.selfX(), ai.selfY()),
                                 (ai.shotX(0), ai.shotY(0)))
        n = self.angleToPointDeg((ai.selfX(), ai.selfY()),
                                 (ai.shotX(0), ai.shotY(0)))

        # Sets turn speed and degree to the enemy
        if ai.screenEnemyX(0) >= 0:
            enemyDeg = self.angleToPointDeg(
                (ai.selfX(), ai.selfY()),
                (ai.screenEnemyX(0), ai.screenEnemyY(0)))
            ai.setTurnSpeed(
                self.rangeMap(abs(enemyDeg), 0, 180, turnSpeedMin,
                              turnSpeedMax))
        else:
            enemyDeg = self.angleToPointDeg(
                (ai.selfRadarX(), ai.selfRadarY()),
                (ai.closestRadarX(), ai.closestRadarY()))
            ai.setTurnSpeed(
                self.rangeMap(abs(enemyDeg), 0, 180, turnSpeedMin,
                              turnSpeedMax))

        # Turn towards unoccluded enemies while in open space
        if ai.aimdir(0) >= 0 and self.headingDiff(
                heading, ai.aimdir(0)) > 0 and not self.enemyBehindWall(0):
            ai.turnRight(1)
        elif ai.aimdir(0) >= 0 and self.headingDiff(
                heading, ai.aimdir(0)) < 0 and not self.enemyBehindWall(0):
            ai.turnLeft(1)
        # Turn away from nearby walls
        elif min(feelers) < ai.enemyDistance(
                0
        ) and trackWall < self.nearLimit and leftWall < rightWall:  #DONE
            ai.turnRight(1)
        elif min(feelers) < ai.enemyDistance(
                0
        ) and trackWall < self.nearLimit and rightWall < leftWall:  #DONE
            ai.turnLeft(1)
        elif min(feelers) < ai.enemyDistance(
                0
        ) and backLeftWall < self.nearLimit and rightWall > self.nearLimit:
            ai.turnRight(1)
        elif min(feelers) < ai.enemyDistance(
                0
        ) and backRightWall < self.nearLimit and leftWall > self.nearLimit:
            ai.turnLeft(1)
        elif min(feelers) < ai.enemyDistance(
                0) and frontRightWall < self.nearLimit:
            ai.turnLeft(1)
        elif min(feelers) < ai.enemyDistance(
                0) and frontLeftWall < self.nearLimit:
            ai.turnRight(1)
        # TODO: NEED RULES FOR WHEN ENEMY IS OCCLUDED
        elif self.enemyBehindWall and enemyDeg < 0:
            ai.turnRight(1)
        elif self.enemyBehindWall and enemyDeg >= 0:
            ai.turnLeft(1)
        # Turn away from shots
        elif m > 0:
            ai.turnRight(1)
        elif m < 0:
            ai.turnLeft(1)

        # THRUST (includes fuzzy controller)

        # Power levels
        power1 = 55
        power2 = 45
        power3 = 55
        power4 = 36
        power5 = 36
        power6 = 28
        power7 = 24
        power8 = 30

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

        # Aggregation

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

        consequents = [
            power1, power2, power3, power4, power5, power6, power7, power8
        ]
        memberships = [p1, p2, p3, p4, p5, p6, p7, p8]

        # Defuzzification
        ai.setPower(self.crispify(memberships, consequents))

        # Further thrusting rules
        if ai.shotAlert(0) < 130 and ai.shotAlert(0) != -1 and ai.wallBetween(
                ai.selfX(), ai.selfY(), ai.shotX(0), ai.shotY(0)) == -1:
            ai.thrust(1)
        elif ai.selfSpeed() <= self.speedLimit:
            ai.thrust(1)
        elif trackWall < self.nearLimit and self.angleDiff(heading,
                                                           tracking) > 75:
            ai.thrust(1)
        elif rearWall < self.nearLimit and self.angleDiff(heading,
                                                          tracking) > 90:
            ai.thrust(1)

        # FIRE

        # Restrict firing to reasonably accurate attempts
        if self.headingDiff(heading, ai.aimdir(
                0)) < targetingAccuracy and not self.enemyBehindWall(0):
            ai.fireShot()

        self.counter += 1
コード例 #9
0
    def AI_loop(self):
        # print("AI_LOOP")

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        # Power levels

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

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

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

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

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

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

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

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

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

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

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

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

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

        self.counter += 1

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

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

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

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

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

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

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

                self.fitness += (ai.selfScore() - ai.enemyScoreId(0)
                                 ) * self.scoreDiffBonusFactor
                ai.quitAI()
        else:
            self.framesDead = 0
コード例 #10
0
ファイル: sweep.py プロジェクト: mvppjr/predator-prey
    def AI_loop(self):

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

        #-------------------- 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()
        targetX = self.coordinateList[self.counter % self.coordListLength][0]
        targetY = self.coordinateList[self.counter % self.coordListLength][1]

        toTurn = self.angleToPoint(x, y, targetX, targetY, heading)
        distance = self.distance(x, targetX, y, targetY)

        #-------------------- Print statements --------------------#
        print("(x, y): (", x, ",", y, ")")
        print("destination: ",
              self.coordinateList[self.counter % self.coordListLength])
        print("distance: ", distance)
        # print("closestEnemyX: ", closestEnemyX)
        # print("closestEnemyY: ", closestEnemyY)
        # print("difference x: ", differenceX)
        # print("difference y: ", differenceY)
        # print("degrees: ", degrees)
        # print("screen enemy? ", ai.screenEnemyXId(ai.closestShipId()))
        print("toTurn: ", toTurn)
        print()

        #-------------------- Move to target point --------------------#
        # if toTurn > 0 and toTurn < 30 and distance > 300 and speed <= 15 and speed >= 4:
        if abs(toTurn) < 20 and distance > 200:
            print("Lock!")
            ai.turnLeft(0)
            ai.turnRight(0)
            if self.frames % 40 == 0:
                ai.thrust(1)
        elif toTurn >= 20:
            print("Turning right!")
            ai.turnLeft(1)
        elif toTurn <= -20:
            ai.turnRight(1)
            print("Turning left!")
        if distance < 200:
            # ai.thrust(0)
            self.counter = self.counter + 1

        # #-------------------- Thrust rules --------------------#
        # if speed <= 3 and frontWall >= 200:
        # 	print("Front wall far")
        # 	ai.thrust(1)
        # elif trackWall < 50:
        # 	print("Close to track wall")
        # 	ai.thrust(1)
        # elif backWall < 40:
        # 	print("Close to back wall")
        # 	ai.thrust(1)

        # #---------------- Turn rules ----------------#

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

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

        self.frames = self.frames + 1