Beispiel #1
0
 def act(self):
     if ai.selfAlive():
         self.getInputs()
         #self.printInputs()
         steerOutput = self.steeringNet.activate(self.steerInputs)[0]
         thrustOutput = self.thrustingNet.activate(self.thrustInputs)[0]
         shootOutput = self.shootingNet.activate(self.shootInputs)[0]
         print([steerOutput,  thrustOutput,  shootOutput])
         if steerOutput > .5:
             ai.turnLeft(1)
             ai.turnRight(0)
         else:
             ai.turnRight(1)
             ai.turnLeft(0)
         if thrustOutput > .5:
             ai.thrust(1)
         else :
             ai.thrust(0)
         if shootOutput > .5:
             ai.fireShot()
         self.resetInputs()
     else:
         self.steeringNet.reset()
         self.thrustingNet.reset()
         self.shootingNet.reset()
Beispiel #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()
def AI_loop():
	#Release keys
    ai.thrust(0)
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.setTurnSpeed(45)

    sendData = getSendData()
    
    output = getOutput(sendData, 12, 5, 2, weight)
    
    turn, thrust = "N", "N"

    if output[0] >= .55:
        ai.turnRight(1)
        turn = "R"
    elif output[0] < .45:
        ai.turnLeft(1)
        turn = "L"
    ai.setTurnSpeed(abs(output[0]-.5)*100)

    if output[1] > random():
        ai.thrust(1)
        thrust = "Y"

    if ai.selfAlive():
        print (turn +"  "+ str(round(output[0],3)) +"  |  "+ thrust +"  "+ str(round(output[1],3)))
Beispiel #4
0
 def tturnLeft(self, num):
     if num == 1:
         self.turnedLeft = 1
         ai.turnLeft(1)
     else:
         ai.turnLeft(0)
         self.turnedLeft = 0
Beispiel #5
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()
Beispiel #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)
  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)
Beispiel #7
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
Beispiel #8
0
def AI_loop():

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

    #Set variables for Wall feelers, heading and tracking of the agent ##
    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)

    ## Create an array that represents the closing rate of each 45 degree of the full 360 degrees surrounding the agent ##
    result_list = []
    ## Array of the same size, but contains the risk of each direction ##
    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)

        ### Calculate the Fuzzy membership ###
        ### 1. Fuzzy Membership For Closing Rate (Speed + Tracking Involved) ###
        ### 2. Fuzzy Membership For Distance From Walls ###
        closing_rate, distance = Closing_Rate(Degree, tracking, Speed,
                                              Distance)
        low, medium, fast = Fuzzy_Speed(
            closing_rate, closingRate_SlowTopAlertValue,
            closingRate_SlowBottomAlertValue,
            closingRate_MediumBottomLeftAlertValue,
            closingRate_MediumTopLeftAlertValue,
            closingRate_MediumTopRightAlertValue,
            closingRate_MediumBottomRightAlertValue,
            closingRate_FastBottomAlertValue, closingRate_FastTopAlertValue)
        close, far = Fuzzy_Distance(distance, Distance_CloseTopAlertValue,
                                    Distance_CloseBottomAlertValue,
                                    Distance_FarBottomAlertValue,
                                    Distance_FarTopAlertValue)
        #print("close-far", close, far)
        risk = Fuzzy_Risk(low, medium, fast, close, far)
        risk_list.append(risk)

    ## Get the direction in deg that is most risky for the robot as well as the least risky direction ##
    max_risk = max(risk_list)
    track_risk = (tracking + (risk_list.index(max_risk) * 45) % 360)
    min_risk = min(
        risk_list
    )  ## Note: Biase Towards Left Side since min get the first min when risk might be equal ##

    ####### 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()

    ## Get the angles on both side between tracking and heading to decide which way to turn ##
    dist = (heading - track_risk) % 360
    dist2 = (360 - dist) % 360

    ###### Production System Rules ######
    ## Turning Rules ##
    if (dist <= 130 and dist >= 0 and ai.selfSpeed() > 0 and max_risk >= 75):
        ai.turnLeft(1)
    elif (dist2 <= 130 and dist2 >= 0 and ai.selfSpeed() > 0
          and max_risk >= 75):
        ai.turnRight(1)
    elif (trackWall <= 150):
        ai.thrust(1)
    ##### Bullet Avoidance Commands #####
    elif (ai.shotAlert(0) >= 0 and ai.shotAlert(0) <= 50):
        if (ai.shotVelDir(0) != -1
                and ai.angleDiff(heading, ai.shotVelDir(0)) > 0
                and ai.selfSpeed() <= 5):
            ai.turnLeft(1)
            ai.thrust(1)
        elif (ai.shotVelDir(0) != -1
              and ai.angleDiff(heading, ai.shotVelDir(0)) < 0
              and ai.selfSpeed() <= 5):
            ai.turnRight(1)
            ai.thrust(1)
        elif (ai.shotVelDir(0) != -1
              and ai.angleDiff(heading, ai.shotVelDir(0)) > 0
              and ai.selfSpeed() > 5):
            ai.turnLeft(1)
        else:
            ai.turnRight(1)
    ##### Shooting Ennemy Commands #####
    elif (enemyDist <= 3000 and heading > (head) and enemyDist != 0
          and ai.selfSpeed() > 2):
        ai.turnRight(1)
        ai.fireShot()
    elif (enemyDist <= 3000 and heading < (head) and enemyDist != 0
          and ai.selfSpeed() > 2):
        ai.turnLeft(1)
        ai.fireShot()
    ## Rules if nothing is happening ##
    elif (ai.selfSpeed() < 5):
        ai.thrust(1)
    else:
        ai.thrust(0)
Beispiel #9
0
def AI_loop():
    global maxSpeed,  shotAngle,  wallClose,  dead,  previousScore
    global turnedLeft,  turnedRight,  thrusted,  shot
    
    
    #Release keys
    ai.thrust(0)
    ai.turnLeft(0)
    ai.turnRight(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:
                ai.turnRight(1)     #If the target is to our right- turn right
               
            else :                       
                ai.turnLeft(1)      #If the target is to our left - turn left
                
        else :
            if diff > -180:
                ai.turnRight(1)     #If the target is to our right - turn right
               
            else :
                ai.turnLeft(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)
            ai.turnLeft(1)
           
        elif wallNum == 2 :  # Left Wall is Closest (Turn Away From It)
            ai.turnRight(1)
            
        elif wallNum == 3 :   #Right Wall is Closest (Turn Away From It)
            ai.turnLeft(1)
           
        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
              
              
            if backLeftWall > backRightWall:        # We need to turn left to face more directly away from it
               ai.turnLeft(1)
              
       
       
    
    #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)
    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
        ai.thrust(1)
    elif backWall < 20: #If there is a wall very close behind us, get away from it
        ai.thrust(1)
    
    if abs(calcDir - heading) < shotAngle and calcDir != -1: #If we are close to the current proper trajectory for a shot then fire
        ai.fireShot()
   
    previousScore = ai.selfScore()
Beispiel #10
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
Beispiel #11
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
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()
Beispiel #13
0
def AI_loop():
    global lastTurn
    #Release keys
    ai.thrust(0)
    ai.turnLeft(0)
    ai.turnRight(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:
            ai.turnRight(1)
            ai.thrust(1)
        elif diff >= 0:
            if diff >= 180:
                a = 0
                ai.turnRight(1)  #If the target is to our right- turn right
            elif diff != 0:
                a = 0

                ai.turnLeft(1)  #If the target is to our left - turn left
        else:
            if diff > -180:
                a = 0
                ai.turnRight(1)  #If the target is to our right - turn right
            else:
                a = 0
                ai.turnLeft(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 == 1 or 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:
                ai.turnRight(
                    1)  #If the targetHEading is to our right- turn right

                print("right")
            elif diff != 0:
                ai.turnLeft(
                    1)  #If the targeHeadingt is to our left - turn left
                print("left")
        else:
            if diff > -180:
                print("right")
                ai.turnRight(
                    1)  #If the targetHeading is to our right - turn right
                #print("right")
            else:
                print("left")
                ai.turnLeft(
                    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
        ai.thrust(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
        ai.thrust(1)
    elif backWall < 30:  #If there is a wall very close behind us, get away from it
        ai.thrust(1)

    if abs(
            calcDir - heading
    ) < 15:  #If we are close to the current proper trajectory for a shot then fire
        ai.fireShot()
Beispiel #14
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()
Beispiel #15
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()
Beispiel #16
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)
Beispiel #17
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)
Beispiel #18
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
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
Beispiel #20
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
Beispiel #21
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():
    #Release keys
    ai.thrust(0)
    ai.turnLeft(0)
    ai.turnRight(0)
    ai.setTurnSpeed(45)

    #noshoot simple2 v1 - possibly broken
    #weight = [[0.7493857316521443, 0.13368056995306654, -0.47767010506248414, 0.36303490376111747, 0.3699402939846066, -0.24513421555956436, 0.6049213422682447, -1.002771350490762, 0.04035249957935825, -0.28434589370049973, 0.06045481719428707, -0.7059773487995405], [0.4597751718875, 0.48527265677711917, 1.1633270644302531, -0.2617787944640836, 0.43969814249154665, 0.39105202732983013, -0.4842763268769806, 0.0139642821717396, 0.6316767202549712, -0.7261062652316246, 0.21262210805420517, 0.5641099350636366], [-0.3874172140692371, 0.7651295146994167, 1.0395098788413182, 1.186226846675026, -0.025235379424306762, 0.2946735626872294, 0.8189904988668917, -0.3112836835374087, 0.4561011502092862, -1.117805735032487, -0.43961810490175446, -0.4119472393430895], [0.22275511634133816, -0.6648437205568158, -0.8414740640064268, 0.8056440111521608, 0.015267716015499746, 0.41334996924272127, 0.4081963555038903, -0.1419511839287509, 0.45361416054410414, -0.8794849582102071, -0.3468746833944422, 0.5401415708615188], [0.5074970117306209, 0.5819675141877677, 0.6517899284876814, 0.46691400605473293, 0.32604510520447944, 0.5968926122763236, 0.5310482664503053, -0.680392116654488, 0.8673231237747582, 0.33285892719317295, 0.8399077545012879, 0.6164215093257798], [-0.372562013299741, -0.19652620269354013, 0.1437357080878078, 0.4658598892474184, 0.2622911587442708, -0.0978653491300881], [-0.8758502232674676, -0.2171515591378693, -2.993752695121232, -0.35299785185297505, 0.23130479682141922, -0.3366867315248932]]
    #same
    #weight = [[-0.5615458044552419, 0.18357035281974562, 0.03349259503126993, 0.7384951638825633, -0.30798810007905386, 0.30573186272807085, 0.854959406907431, -0.7415861859492735, -0.7738387875893121, 0.02855354677310282, -0.851478966174285, -0.4098017778685181], [-0.207370684933253, -0.013364767376613134, -0.9163625758710611, 0.7147484720369136, 0.4332939609435104, 0.08179173241171495, -0.7872472562071717, -0.028481692524635203, 0.9018021433254303, 0.44174414866442663, -0.9254417448428363, -0.8782722048252558], [0.33830929947647237, 0.3662059060118147, 0.3811711776833437, 0.24042392561994674, 0.5277499126295441, -0.0004866655690337176, 0.25640579185352463, -0.7633986561071578, -0.612156341670209, 0.8230711072150679, 0.760953671186351, -0.2573796666700781], [-0.504034389497162, -0.5579761993837166, -0.5804468446739354, 0.20559197382639358, 0.2633102441141902, 0.6523171620389138, -0.024442707325193276, 0.20991650483980787, 0.8242995112997102, -0.310268650118638, 0.6134846337134139, -0.1333594123873779], [-0.1482061081648374, -0.8156028525698128, 0.5620698705963493, 0.3369535386843364, 0.4950101349517008, 0.632041030208815, 0.2282786987810209, 0.5886322102158713, 0.1479714498784525, -0.35843514023521145, 0.7822417167093876, -0.6863908492221918], [0.19475966937630487, 0.3329038845401951, -0.4194515125286082, -1.0059783572483236, 0.4401534681618835, -0.14131035905437314], [-0.1489506388852606, -0.7142411448348961, 0.19491176823686687, -0.7258125795197734, -0.5016315182547347, 1.187683861246764]]

    #noshoot simple2 v1
    #weight = [[4.023914862289385, -11.939688383204079, -15.825568188856662, -8.91142185823263, 2.641203914119205, -0.5129014819329881, 0.9220419943089314, 0.3895906088166904, -3.314207628630927, 1.467458787811278, 1.0256723985314264, 6.790853759075572], [0.46927642890835647, 0.4119664313516612, 1.0805195819839035, -22.587191583019706, -2.0569865767257087, 1.0122406403957074, 0.7655020473448081, 0.5363534804959299, -0.09153880599832058, 1.742638802899449, 0.604362216981221, -5.437549122082703], [-7.860553953097792, 8.381751807757572, 16.129268910929408, 0.8192147369369929, 12.621334155351937, 1.1871517887014937, 1.3270695309760896, 1.0735505581082165, -2.1305919492192547, 0.8033262515099523, 3.3317152348735313, -1.1046970930734303], [0.4398449547641411, 1.912802187200376, 1.5190820053279013, 0.05054235950852018, 20.89903152269866, -5.003395008994748, -2.6880139668653324, -7.882075146152547, 7.312459204984362, 0.7725581247271933, -3.2005214579831134, 8.556187322708842], [-1.293677418426306, 1.0762585514923537, 2.9472553959491394, -2.8811018920854745, 20.39410027291124, 3.5575387211971545, -4.928681592073799, 3.91012465174139, -0.6466184042394076, 8.419255646279453, -8.094268776239682, 19.5220882165644], [0.3806641134895386, -0.054247151061047154, 0.35553915476967757, -0.16909223457447353, 0.6749672736601655, -0.19785778477211138], [6.21846263437043, 13.27919055895352, 5.556186398879765, 1.9758063219353386, 3.685290720905768, 11.4029046390971]]
    #weight = [[0.5903138120766798, 0.3877986755669686, -0.9141386987535192, -0.1976691845132495, 0.20203743452617146, -3.8075577538969068, 13.355367631879064, -4.451492883287705, -4.077459994350015, -2.8670604965816433, -4.7237141988262215, 4.196577955775335], [0.05788957126040142, 0.7553202993193877, -0.41293776536874083, 0.9699420358471046, -0.39940905986885467, -0.7501531314002139, -3.649664715012045, -4.480417131687637, 12.40189634710716, -3.5479446525980323, -5.617634895580113, 4.614443478920718], [-0.44964748196431087, -0.21623652235598786, 0.5866855307562749, 2.6966017037464547, -0.2198767358187771, -15.121568447637916, 5.394174355851121, 3.3357101263144284, 5.142941080162113, 4.396587735322672, 6.27965132359125, -1.7132992179558508], [-0.8420976477874832, 3.6695944609982, 3.985187073998181, 11.839206173737303, -5.338358329529615, 12.584411691032383, -3.6258238911963225, -9.100219517619708, 0.09757837890948427, 0.26347032883307564, -2.317810633312963, 3.488522703736898], [0.7765991306851521, 0.28898396896441564, 0.7418514532805458, 7.79799228304993, -0.19002509820555794, -0.4950254716867189, 1.674108868938578, -2.550479398095525, -0.4777881148214889, -17.68616848936312, 17.798127474785755, 3.564677234214063], [-7.8104601458246075, -2.0636289766378315, -8.171829518484577, -0.3002860633762538, -0.8003364861508999, -8.88545431866241], [-9.931271155016605, -8.304191180682096, -4.721651527085654, -11.413401995134363, -6.807105641677094, -4.2517323859898255]]

    #take 3
    #weight = [[3.2209677211590364, 3.197844521358916, 1.0178700774531555, 2.6850832852265705, -0.1142410857208976, -7.424760693950065, 2.4741068398654735, -2.2455337118424423, 0.7975567187947812, -7.14879174218826, 1.1236926484785208, 1.0893799362829708], [0.8039483127966134, 2.0360025213584287, 0.01727196345640146, 13.743242184336747, -3.1131725731697797, 3.551772323183245, -1.912134715951023, 6.3466547648380365, 2.7583972445682843, -8.543348277242536, 1.0695972197298327, 1.0968548560479523], [-1.9711628616688408, -2.915258703528061, -0.6856763056229077, 5.775022292258987, -0.9242292134264676, -5.2290301586614545, 1.554497111395412, -8.663422012897401, 3.434867742464676, -1.4626063376098368, 3.1916811250980226, -3.1266957996982083], [-2.963581011499582, -1.8333571215071727, 0.19431283257511642, 12.685505979633772, 5.629563357825744, 2.269402859201827, -0.5394798674782302, 0.5415330617135145, -1.3492223641876873, -2.3782036784139104, -1.6868806998589756, -2.566848157895665], [-2.1971772106385568, -3.046613937692231, -1.91992660803775, 6.63802500331367, -13.090973918413972, 2.0019783380453955, 1.5786044885623458, -1.1226639661286304, -0.8816140948702889, -0.6041236731069092, 0.4128577493527515, -9.236718652388456], [-0.37898780078879885, 0.02278416261917311, -0.7370299412447531, 0.4580826382451188, 0.024909816638153417, -0.2986982689652905], [-6.204456817434451, -7.054321617074455, -3.8731103597961956, -7.0447149929917146, -6.223052160580929, -15.546591666508577]]
    #weight = [[1.1620356523045294, 1.2293119820243932, -1.0680281171990968, -5.292742962549776, 3.004567388617913, 0.1416865776270463, 3.291787739904783, 3.311779449153159, 0.14350525985680226, 1.864065320111765, 0.41531949262324336, -0.7533626568752921], [2.6058003821118527, 0.9844458916296726, -2.031523030007777, -3.4422006288675315, 4.5638626155289055, -2.7046080365173837, 1.5356155037759958, 2.143460607268979, 3.9199241782825687, 0.12721742246873802, -0.8673469875291382, -1.8507505784965346], [-0.6131784294183935, 0.4639547932071712, -0.2666315961058117, 7.5292821094228755, -1.087211170794136, -0.7293843967199962, 0.4755491742014118, 0.4206888297192853, -0.8152826105125003, 1.988359326013337, -5.637090150274117, 0.5993755933965147], [0.27691971567025647, 1.037850843325554, -0.8250576728298599, -2.000417570912899, -0.006391527390813737, 2.0837950209487466, -8.24238052083867, 2.073287983133908, 3.2529633929820907, 2.1453759622986524, 3.7417070714472893, -2.9435663281508724], [-0.5037569895779601, -0.09031006667126633, -0.5311072081881074, 0.9440264182616986, 0.783774066571815, 6.828375559954358, -2.841644500387658, 0.24901014690965492, -4.849174297326825, -1.5945524577293186, -4.823283932380879, 1.1962232130136108], [1.4042452333993327, -0.09263191061453735, 0.8155734671747938, 5.256825832477101, 3.7371321136701705, 6.574206973322576], [13.323880256265307, -2.429025764741311, -10.985707613602697, 5.331771733353978, -0.12615902379461702, 15.191420141027539]]

    #take 4
    #weight = [[0.1906964794417142, -1.3230251087714693, -1.8568527275491726, -10.570510924730712, 0.3754935945207968, -4.767279359714083, 0.11809759894653031, -6.033443845654109, -4.862563766686397, -1.5992520992754746, 7.726616433374799, -3.552685892017083], [0.3653010148791735, 1.6736547762277736, 0.4531478751025384, -16.54229219042565, -3.440356011229119, 1.0104044032989574, -1.5155008934004035, 0.10642496061430406, -0.31316504641192483, 3.6828030284027515, -0.7489883459127186, -1.5244542545724582], [3.764701498917189, 0.4439295275324288, -2.9864503359860985, -3.9316071635513206, 5.798674529890128, -5.74883908980071, 5.398546661400034, -2.51467872126794, 10.108154232633654, -2.18382803218839, 2.5521301844943816, 3.311614056240679], [3.540372052106104, 4.504838909273797, 0.9723232714577832, -8.437301256316747, 14.998025152577217, -0.31994218366769667, -2.907161494453055, 3.893824258473095, -0.7579119727276817, 5.473585535436292, -3.2397908440984766, 15.192742537984023], [-6.248680428157617, -6.451873887564568, 1.6916836827123973, -4.655942296742202, 16.84212812043791, 5.734711342713387, 0.2955864473988734, 1.791898461633518, -3.4668510416701595, -1.358433980522392, -1.1057313703313203, 0.6888252016526282], [-0.43458701659431115, -0.0012780178353029815, -0.3084730481531892, 0.45069433382083834, 0.11685910089310178, -0.38449878977835567], [3.853866205452628, 12.037185197898191, 1.8699413530857774, 5.001790072421261, 4.513316028443307, 9.851232302101327]]
    #weight = [[1.2911306905979911, -0.24861004977707912, -0.3569265073483646, 6.428936726785303, -1.3066626434454807, 0.25686627368220305, 0.9109367109212936, 0.16801829318526124, -0.20947845384297986, 1.2064241958740287, 0.036856251428802896, -3.359023278463905], [0.8036278040339718, 0.08012145204557049, 0.6845458738830329, 5.665809973883479, -0.9210048722891027, 1.3932208121673026, 1.046083232807299, 0.7941648248360582, 0.9365855847155237, 1.459603497851585, -0.5332056328831426, -2.534773939928277], [0.13301078275476066, 0.3429847838792201, -1.0338159784473917, 4.850766016537791, 0.7802072613774678, 1.2836937010475253, -0.8584360890917163, 1.7672832265369043, 0.10738236989054603, 3.4517636983002387, 0.22658851691351473, -1.0683529525811006], [1.6450210175622832, -0.28557720210974497, -0.2443112896936013, 6.8747070212198045, -0.8271033896420884, 0.2800592224187591, 0.5652744631888489, 0.08792418368229415, 0.9155105124974535, 0.46138821886651926, -0.3837164120204661, -3.494842813175506], [-0.8165377903719206, 1.958062852731677, 2.000566970645578, 5.919031622286524, 0.5506236423988042, 0.5494849931384184, 1.7160531008225108, 0.5260681781001207, 2.06495028663279, -0.07306752095214097, -1.204154609328308, -4.01239045823013], [-0.6146224030404228, 0.3233086944120275, 5.3979041539672545, -4.401300546048576, -0.42678298976091805, 1.0758830778504247], [-5.977941738072086, 0.019369137899827416, -0.5522710341025945, -7.13480943116727, -4.873784872189164, -16.38430927507949]]

    #over break training
    weight = [[
        0.3662869049519842, -0.8570465997089849, -1.0415622777532179,
        0.4420706041485171, 0.009019607340448946, 10.71120549250932,
        -12.382299178044326, 10.244684059761504, -4.7714116184482425,
        10.703496354982395, -0.8400740885526794, 2.1209753284753745
    ],
              [
                  2.5366260663128686, 1.068830514524183, -2.0352964619508715,
                  -0.4999108962144593, 20.533875500405504, -1.301731900907607,
                  0.3103574877473953, -0.6500134665269202, 0.5084981306498488,
                  -0.8059254394827501, 1.31308616755389, 15.873718577684429
              ],
              [
                  0.08005904547677181, -0.007564753721625019,
                  -0.10037179685269433, -30.286524359136706,
                  1.0348747725041256, -0.9129196441653706, 0.3754957498625551,
                  -1.305163204786704, -0.30909410903499906, 1.3574890310465415,
                  -0.2886464224612783, -5.911566724871949
              ],
              [
                  4.655481170315177, -1.2991521769114085, -4.454652256174474,
                  4.274677448402512, 16.502421922725226, 12.710289689086315,
                  -9.738471684679293, 9.865851212762863, -8.873570414630043,
                  -0.1285739247431209, -14.804016099227272, 10.638993200840254
              ],
              [
                  -13.975667825847953, 13.618115550695093, 27.871087273931305,
                  1.7052627216183622, -16.717674225226972, 0.8131962686148689,
                  0.6430161349620291, -0.6832651795038519, 1.6123037795473343,
                  3.7701435389411695, -2.729257195826183, -2.0449519807080896
              ],
              [
                  0.6784559764050078, -0.30818410563793897,
                  -0.12048266318505906, 0.7386778766766025,
                  0.18813592750492103, 0.9656707078851317
              ],
              [
                  7.248480099597683, 9.862850677133501, 18.95475459828898,
                  1.981941403265762, 7.509742979506548, 19.364672423856124
              ]]

    sendData = getSendData()
    output = getOutput(sendData, 11, 5, 2, weight)

    turn, thrust = "N", "N"

    if output[0] >= .55:
        ai.turnRight(1)
        turn = "R"
    elif output[0] < .45:
        ai.turnLeft(1)
        turn = "L"
    ai.setTurnSpeed(abs(output[0] - .5) * 100)

    if output[1] > random():
        ai.thrust(1)
        thrust = "Y"

    if ai.selfAlive():
        print(turn + "  " + str(round(output[0], 3)) + "  |  " + thrust +
              "  " + str(round(output[1], 3)))
Beispiel #23
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()
Beispiel #24
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)
Beispiel #25
0
def AI_loop():
    ai.turnLeft(1)
Beispiel #26
0
def AI_loop():
    """ The main loop for this agent!
        Prod.py is a rule-based expert system.
    """

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

    # Heuristics
    sideFeelerOffset = 65  # Offsets from heading for wall feelers (degrees)
    perpFeelerOffset = 90  # (degrees)
    trackFeelerOffset = 45  # (degrees)

    nearLimit = 150  # Threshold for a relatively "close" object (xp distance units)
    nearLimitThreat = 300  # Threshold for a "very close" object (xp distance units)
    shotDanger = 130  # Threshold for relatively "close" bullets (xp distance units)

    speedLimit = 5  # (xp speed units)
    powerHigh = 45  # (xp thrust power units)
    powerLow = 20  # (xp thrust power units)
    targetingAccuracy = 5  # Tolerance from heading within which firing is OK (degrees)

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

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

    feelers = []
    heading = int(ai.selfHeadingDeg())
    tracking = int(ai.selfTrackingDeg())
    frontWall = ai.wallFeeler(500, heading)
    leftWall = ai.wallFeeler(500, heading + perpFeelerOffset)
    rightWall = ai.wallFeeler(500, heading - perpFeelerOffset)
    trackWall = ai.wallFeeler(500, tracking)
    rearWall = ai.wallFeeler(500, heading - 180)
    backLeftWall = ai.wallFeeler(500, heading + 135)
    backRightWall = ai.wallFeeler(500, heading - 135)
    frontLeftWall = ai.wallFeeler(500, heading + 45)
    frontRightWall = ai.wallFeeler(500, heading - 45)

    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)

    # Collect distances
    if ai.enemyDistanceId(ai.closestShipId()) > 0:
        closestPlayerDistance = ai.enemyDistanceId(ai.closestShipId())
    else:
        closestPlayerDistance = math.inf

    if ai.shotDist(0) > 0:
        closestBulletDistance = ai.shotDist(0)
    else:
        closestBulletDistance = math.inf

    dcw = min(feelers)
    distToNearestThreat = min(closestPlayerDistance, closestBulletDistance)

    # Assign priority to nearest threat
    if closestBulletDistance <= dcw and closestBulletDistance <= closestPlayerDistance:  # if closest threat is a bullet
        priority = 1
    elif dcw <= closestPlayerDistance and dcw <= closestBulletDistance:  # if closest threat is a wall
        priority = 2
    else:  # closest threat is a player
        priority = 3

    if distToNearestThreat < nearLimitThreat:
        ai.setPower(powerHigh)

    # If the closest threat is a bullet
    if priority == 1:
        m = angleToPointDeg((ai.selfX(), ai.selfY()),
                            (ai.shotX(0), ai.shotY(0)))
        if m >= 0:
            ai.turnRight(1)
        else:
            ai.turnLeft(1)

        if ai.shotAlert(0) < shotDanger:
            ai.thrust(1)

    # If the closest threat is a wall
    elif priority == 2:
        # Thrust
        if ai.selfSpeed() <= speedLimit:
            ai.thrust(1)
        elif trackWall < nearLimit and angleDiff(heading, tracking) > 90:
            ai.thrust(1)
        elif rearWall < nearLimit and angleDiff(heading, tracking) > 90:
            ai.thrust(1)

        # Turn
        if trackWall < nearLimit and leftWall < rightWall:
            ai.turnRight(1)
        elif trackWall < nearLimit and rightWall < leftWall:
            ai.turnLeft(1)
        elif backLeftWall < nearLimit and rightWall > 50:
            ai.turnRight(1)
        elif backRightWall < nearLimit and leftWall > 50:
            ai.turnLeft(1)
        elif frontRightWall < nearLimit:
            ai.turnLeft(1)
        elif frontLeftWall < nearLimit:
            ai.turnRight(1)

    # If the closest threat is a player
    elif priority == 3:
        m = angleToPointDeg((ai.selfX(), ai.selfY()),
                            (ai.shotX(0), ai.shotY(0)))
        if m <= 0:
            ai.turnRight(1)
        else:
            ai.turnLeft(1)

        if ai.selfHeadingDeg() <= (targetingAccuracy + angleToPointDeg(
            (ai.selfX(), ai.selfY()),
            (ai.screenEnemyX(0), ai.screenEnemyY(0)))) and ai.selfHeadingDeg(
            ) >= (targetingAccuracy - angleToPointDeg(
                (ai.selfX(), ai.selfY()),
                (ai.screenEnemyX(0), ai.screenEnemyY(0)))):
            ai.fireShot()
Beispiel #27
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
Beispiel #28
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. ##
    closingRate_SlowTopAlert = current_chromosome[0:4]
    closingRate_SlowTopAlertValue = transform_fuzzy(closingRate_SlowTopAlert,
                                                    1, 0, 16)
    closingRate_MediumTopLeftAlert = current_chromosome[4:8]
    closingRate_MediumTopLeftAlertValue = transform_fuzzy(
        closingRate_MediumTopLeftAlert, 1, (closingRate_SlowTopAlertValue + 1),
        (closingRate_SlowTopAlertValue + 1) + 16)
    closingRate_MediumTopRightAlert = current_chromosome[8:12]
    closingRate_MediumTopRightAlertValue = transform_fuzzy(
        closingRate_MediumTopRightAlert, 1,
        (closingRate_MediumTopLeftAlertValue + 1),
        (closingRate_MediumTopLeftAlertValue + 1) + 16)
    closingRate_FastTopAlert = current_chromosome[12:16]
    closingRate_FastTopAlertValue = transform_fuzzy(
        closingRate_FastTopAlert, 1,
        (closingRate_MediumTopRightAlertValue + 1),
        (closingRate_MediumTopRightAlertValue + 1) + 16)

    closingRate_SlowBottomAlert = current_chromosome[16:20]
    start = (closingRate_SlowTopAlertValue +
             (((closingRate_MediumTopLeftAlertValue -
                closingRate_SlowTopAlertValue) // 2) + 1))
    end = (start + (1 * (2**(len(closingRate_SlowBottomAlert)))))
    closingRate_SlowBottomAlertValue = transform_fuzzy(
        closingRate_SlowBottomAlert, 1, start, end)

    closingRate_MediumBottomLeftAlert = current_chromosome[20:24]
    end = (closingRate_MediumTopLeftAlertValue -
           (((closingRate_MediumTopLeftAlertValue -
              closingRate_SlowTopAlertValue) // 2) + 1))
    start = end - (1 * (2**(len(closingRate_MediumBottomLeftAlert))))
    if (end < 0):
        end = 0
    if (start < 0):
        start = 0
    jump = (end - start) // (2**(len(closingRate_MediumBottomLeftAlert)))
    closingRate_MediumBottomLeftAlertValue = transform_fuzzy(
        closingRate_MediumBottomLeftAlert, jump, start, end)

    closingRate_MediumBottomRightAlert = current_chromosome[24:28]
    start = (closingRate_MediumTopRightAlertValue +
             (((closingRate_FastTopAlertValue -
                closingRate_MediumTopRightAlertValue) // 2) + 1))
    end = start + (1 * (2**(len(closingRate_MediumBottomRightAlert))))
    closingRate_MediumBottomRightAlertValue = transform_fuzzy(
        closingRate_MediumBottomRightAlert, 1, start, end)

    closingRate_FastBottomAlert = current_chromosome[28:32]
    end = (closingRate_FastTopAlertValue -
           (((closingRate_FastTopAlertValue -
              closingRate_MediumTopRightAlertValue) // 2) + 1))
    start = end - (1 * (2**(len(closingRate_FastBottomAlert))))
    if (end < 0):
        end = 0
    if (start < 0):
        start = 0
    jump = (end - start) // (2**(len(closingRate_FastBottomAlert)))
    closingRate_FastBottomAlertValue = transform_fuzzy(
        closingRate_FastBottomAlert, jump, start, end)

    Distance_CloseTopAlert = current_chromosome[32:37]
    Distance_CloseTopAlertValue = transform_fuzzy(
        Distance_CloseTopAlert, 50, 0, (50 * (2**len(Distance_CloseTopAlert))))
    Distance_FarTopAlert = current_chromosome[37:42]
    Distance_FarTopAlertValue = transform_fuzzy(
        Distance_CloseTopAlert, 50, (Distance_CloseTopAlertValue + 50),
        (Distance_CloseTopAlertValue + 50) +
        (50 * (2**len(Distance_CloseTopAlert))))

    Distance_CloseBottomAlert = current_chromosome[42:47]
    start = (Distance_CloseTopAlertValue + ((
        (Distance_FarTopAlertValue - Distance_CloseTopAlertValue) // 2) + 1))
    end = Distance_FarTopAlertValue
    jump = (end - start) // (2**(len(Distance_CloseBottomAlert)))
    Distance_CloseBottomAlertValue = transform_fuzzy(Distance_CloseBottomAlert,
                                                     jump, start, end)

    Distance_FarBottomAlert = current_chromosome[47:52]
    end = (Distance_FarTopAlertValue - ((
        (Distance_FarTopAlertValue - Distance_CloseTopAlertValue) // 2) + 1))
    start = Distance_CloseTopAlertValue
    jump = (end - start) // (2**(len(Distance_FarBottomAlert)))
    Distance_FarBottomAlertValue = transform_fuzzy(Distance_FarBottomAlert,
                                                   jump, start, end)

    #Set variables for Wall feelers, heading and tracking of the agent ##
    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)

    ## Create an array that represents the closing rate of each 45 degree of the full 360 degrees surrounding the agent ##
    result_list = []
    ## Array of the same size, but contains the risk of each direction ##
    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)

        ### Calculate the Fuzzy membership ###
        ### 1. Fuzzy Membership For Closing Rate (Speed + Tracking Involved) ###
        ### 2. Fuzzy Membership For Distance From Walls ###
        closing_rate, distance = Closing_Rate(Degree, tracking, Speed,
                                              Distance)
        low, medium, fast = Fuzzy_Speed(
            closing_rate, closingRate_SlowTopAlertValue,
            closingRate_SlowBottomAlertValue,
            closingRate_MediumBottomLeftAlertValue,
            closingRate_MediumTopLeftAlertValue,
            closingRate_MediumTopRightAlertValue,
            closingRate_MediumBottomRightAlertValue,
            closingRate_FastBottomAlertValue, closingRate_FastTopAlertValue)
        close, far = Fuzzy_Distance(distance, Distance_CloseTopAlertValue,
                                    Distance_CloseBottomAlertValue,
                                    Distance_FarBottomAlertValue,
                                    Distance_FarTopAlertValue)
        #print("close-far", close, far)
        risk = Fuzzy_Risk(low, medium, fast, close, far)
        risk_list.append(risk)

    ## Get the direction in deg that is most risky for the robot as well as the least risky direction ##
    max_risk = max(risk_list)
    track_risk = (tracking + (risk_list.index(max_risk) * 45) % 360)
    min_risk = min(
        risk_list
    )  ## Note: Biase Towards Left Side since min get the first min when risk might be equal ##

    ####### 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 Individual ##
        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("Dumpster_Training_Data.xls", 0, titles,
                                   data, first_time)

            ## Select Population For 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):

            ## Get the angles on both side between tracking and heading to decide which way to turn ##
            dist = (heading - track_risk) % 360
            dist2 = (360 - dist) % 360

            ###### Production System Rules ######
            ## Turning Rules ##
            if (dist <= 130 and dist >= 0 and ai.selfSpeed() > 0
                    and max_risk >= 75):
                ai.turnLeft(1)
            elif (dist2 <= 130 and dist2 >= 0 and ai.selfSpeed() > 0
                  and max_risk >= 75):
                ai.turnRight(1)
            elif (ai.selfSpeed() <= 10):
                ai.thrust(1)
            elif (trackWall <= 150):
                ai.thrust(1)
            ##### Bullet Avoidance Commands #####
            elif (ai.shotAlert(0) >= 0 and ai.shotAlert(0) <= 50):
                if (ai.shotVelDir(0) != -1
                        and ai.angleDiff(heading, ai.shotVelDir(0)) > 0
                        and ai.selfSpeed() <= 5):
                    ai.turnLeft(1)
                    ai.thrust(1)
                elif (ai.shotVelDir(0) != -1
                      and ai.angleDiff(heading, ai.shotVelDir(0)) < 0
                      and ai.selfSpeed() <= 5):
                    ai.turnRight(1)
                    ai.thrust(1)
                elif (ai.shotVelDir(0) != -1
                      and ai.angleDiff(heading, ai.shotVelDir(0)) > 0
                      and ai.selfSpeed() > 5):
                    ai.turnLeft(1)
                else:
                    ai.turnRight(1)
            ##### Shooting Ennemy Commands #####
            elif (enemyDist <= 3000 and heading > (head) and enemyDist != 0
                  and ai.selfSpeed() > 5):
                ai.turnRight(1)
                ai.fireShot()
            elif (enemyDist <= 3000 and heading < (head) and enemyDist != 0
                  and ai.selfSpeed() > 5):
                ai.turnLeft(1)
                ai.fireShot()
            ## Rules if nothing is happening ##
            elif (ai.selfSpeed() < 5):
                ai.thrust(1)
            else:
                ai.thrust(0)

            count_frame += 3
            boolean = False
Beispiel #29
0
  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)
   
  #Just keep shooting
  ai.fireShot()

ai.start(AI_loop,["-name","Dubster","-join","localhost"])
    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