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 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()
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()
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
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 tick(): # # The API won't print out exceptions, so we have to catch and print them ourselves. # try: # # Declare global variables so we're allowed to use them in the function # global tickCount global mode global targetId # # Reset the state machine if we die. # if not ai.selfAlive(): tickCount = 0 mode = "aim" return tickCount += 1 # # Read some "sensors" into local variables to avoid excessive calls to the API # and improve readability. # selfX = ai.selfX() selfY = ai.selfY() selfHeading = ai.selfHeadingRad() # 0-2pi, 0 in x direction, positive toward y targetCount = ai.targetCountServer() targetCountAlive = 0 for i in range(targetCount): if ai.targetAlive(i): targetCountAlive += 1 # Use print statements for debugging, either here or further down in the code. # Useful functions: round(), math.degrees(), math.radians(), etc. # os.system('clear') clears the terminal screen, which can be useful. print("tick count:", tickCount, "mode:", mode, "heading:", round(math.degrees(selfHeading)), "targets alive:", targetCountAlive) if mode == "wait": if targetCountAlive > 0: mode = "aim" elif mode == "aim": if targetCountAlive == 0: mode = "wait" return # Loop through the indexes of targets and find one that is alive, # save that index in targetId. # useful variables: targetCount, targetId # useful functions: ai.targetAlive for i in range(targetCount): if ai.targetAlive(i): targetId = i # Calculate what direction the target is in, save in # the variable targetDirection # useful variables: selfX, selfY # useful functions: math.atan2, ai.targetX, ai.targetY xDiff = ai.targetX(targetId) - ai.selfX() yDiff = ai.targetY(targetId) - ai.selfY() targetDirection = math.atan2(yDiff, xDiff) # Turn to the direction of the target # useful variables: targetDirection # useful functions: ai.turnRad, ai.turnToRa # If the ship keeps oscillating between a few angles # it may be due to latency. Only turning every second # or third tick is a simple solution (use tickCount and %) # Check if you are aiming in the direction of the target, # if so, change mode to shoot. # Note that, due to how the game handles angles, the difference # cannot be 0 for many angles. # useful variables: selfHeading, targetDirection, mode # There is a function defined below called angleDiff that # is very useful as well. if angleDiff(selfHeading, targetDirection) < 0.1 and ai.targetAlive(targetId): mode = "shoot" else: if tickCount % 3 == 0: ai.turnToRad(targetDirection) elif mode == "shoot": # Shoot the target # useful functions: ai.fireShot # if the target is destroyed, change state to aim # useful variables: targetId, mode # useful functions: ai.targetAlive ai.fireShot() if not ai.targetAlive(targetId): mode = "aim" except: # # If tick crashes, print debugging information # print(traceback.print_exc())
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)
def open_fire(self): """ Fires the selected target """ angle = angle_to(self.target) ai.turnToDeg(int(angle)) ai.fireShot()
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
def AI_loop(self): # print("AI_LOOP") if ai.selfAlive() == 0: outputFile = open("fitness.txt", "a") # outputFile.write(str((self.totalDists/self.counter))+"\t") outputFile.write(str(int((self.fitness**1.2))) + "\t") [ print(str("%.5f" % g) + "\t", end="", file=outputFile) for g in self.chromosome ] print("\n", end="", file=outputFile) outputFile.close() # Release keys ai.thrust(0) ai.turnLeft(0) ai.turnRight(0) ai.setTurnSpeed(55) # Heuristics frontFeelerOffset = 45 perpFeelerOffset = 90 rearFeelerOffset = 135 # turnSpeedMin = 15 # learn range: 4 - 24 turnSpeedMax = 55 speedLimit = 5 # learn range: 2-6 lowSpeedLimit = 2 targetingAccuracy = 4 # 1/2 tolerance in deg for aiming accuracy shotIsDangerous = 130 # Acquire information heading = int(ai.selfHeadingDeg()) tracking = int(ai.selfTrackingDeg()) ###=== ENEMY FEELERS ===### # gets angle to enemy enemyDeg = self.angleToPointDeg( (ai.selfX(), ai.selfY()), (ai.screenEnemyX(0), ai.screenEnemyY(0))) enemyWallDistances = [] # maxAngleOffset = 90 # learn range: 30 - 120 # resolution = 5 # learn range: 2 - 10 distAngleTuples = [] # creates tuples of degrees and wallFeelers for m in (0, self.maxAngleOffset, self.resolution): distAngleTuples.append( (enemyDeg - m, ai.wallFeeler(500, int(enemyDeg - m)))) distAngleTuples.append( (enemyDeg + m, ai.wallFeeler(500, int(enemyDeg + m)))) # gets furthest feeler maxFeelerAngle = max(distAngleTuples, key=self.returnSecond) angleToOpenSpace = self.headingDiff(ai.selfHeadingDeg(), maxFeelerAngle[0]) ###=== WALL FEELERS ===### frontWall = ai.wallFeeler( self.genericFeelerDist, heading) # wall feeler for wall directly ahead leftFrontWall = ai.wallFeeler( self.genericFeelerDist, heading + frontFeelerOffset) # wall feeler for wall 45 degrees to the left rightFrontWall = ai.wallFeeler( self.genericFeelerDist, heading - frontFeelerOffset) # wall feeler for wall 45 degrees to the right leftWall = ai.wallFeeler( self.genericFeelerDist, heading + perpFeelerOffset) # wall feeler for wall 90 degrees to the left rightWall = ai.wallFeeler( self.genericFeelerDist, heading - perpFeelerOffset) # wall feeler for wall 90 degrees to the right backWall = ai.wallFeeler(self.genericFeelerDist, heading - 180) # wall feeler for wall straight back leftBackWall = ai.wallFeeler( self.genericFeelerDist, heading + rearFeelerOffset) # wall feeler for wall 135 degrees to the left rightBackWall = ai.wallFeeler( self.genericFeelerDist, heading - rearFeelerOffset) # wall feeler for wall 135 degrees to the right trackWall = ai.wallFeeler( self.genericFeelerDist, tracking) # wall in front of where ship is moving # Keep track of all the feeler distances feelers = [ frontWall, leftFrontWall, rightFrontWall, leftWall, rightWall, backWall, leftBackWall, rightBackWall, trackWall ] # Aim assist leftDir = (heading + 90) % 360 # angle 90 degrees to the left of current heading rightDir = (heading - 90 ) % 360 # angle 90 degrees to the right of current heading aimer = ai.aimdir( 0 ) # direction that the ship needs to turn to in order to face the enemy in degrees shot = ai.shotAlert( 0 ) # returns a danger rating of a shot, the smaller the number the more likely the shot is to hit the ship enemyX = ai.screenEnemyX(0) # returns the closest enemy's x-coord enemyY = ai.screenEnemyY(0) # returns the closest enemy's y-coord selfX = ai.selfX() # returns the ship's x-coord selfY = ai.selfY() # returns the ship's x-coord # Fuzzy variable declaration trackRisk = riskEval(trackWall, ai.selfSpeed()) #risk of running into trackWall frontRisk = riskEval(frontWall, ai.selfSpeed()) #risk of running into frontWall leftRisk = riskEval(leftWall, ai.selfSpeed()) #risk of running into leftWall rightRisk = riskEval(rightWall, ai.selfSpeed()) #risk of running into rightWall LFRisk = riskEval(leftFrontWall, ai.selfSpeed()) #risk of running into leftFrontWall RFRisk = riskEval(rightFrontWall, ai.selfSpeed()) #risk of running into rightFrontWall LBRisk = riskEval(leftBackWall, ai.selfSpeed()) #risk of running into leftBackWall RBRisk = riskEval(rightBackWall, ai.selfSpeed()) #risk of running into rightBackWall backRisk = riskEval(backWall, ai.selfSpeed()) #risk of running into backWall # Compress some wall feelers sTrack = self.squisher(trackWall) sLeft = self.squisher(leftFrontWall) sRight = self.squisher(rightFrontWall) sLeftStraight = self.squisher(leftWall) sRightStraight = self.squisher(rightWall) # output from neural network that tells how much to turn and which direction turn = self.trainedNeuralNetwork(sTrack, sLeft, sRight, sLeftStraight, sRightStraight) ###=== THRUST POWER ADJUSTMENT ===# # Power levels mfS = self.mfSpeed(ai.selfSpeed()) mfD = self.mfDanger(ai.shotAlert(0)) # if S is high and D is moderate or high: p1 = max(mfS[2], min(mfD[1], mfD[2])) # if S is moderate and D is moderate: p2 = max(mfS[1], mfD[1]) # if S is low and D is high: p3 = max(mfS[0], mfD[2]) # if S is moderate and D is moderate: p4 = max(mfS[1], mfD[1]) # if S is low and D is moderate: p5 = max(mfS[0], mfD[1]) # if S is high and D is low: p6 = max(mfS[2], mfD[0]) # if S is moderate and D is low: p7 = max(mfS[1], mfD[0]) # if S is low and D is low: p8 = max(mfS[0], mfD[0]) consequents = [55, 45, 55, 36, 36, 28, 24, 30] memberships = [p1, p2, p3, p4, p5, p6, p7, p8] ai.setPower(self.crispify(memberships, consequents)) if ai.enemyDistance(0) > self.lastDist and ai.enemyDistance( 0) < self.enemyClose: ai.thrust(1) elif ai.selfSpeed( ) <= 3 and frontWall >= 200: # if speed is slow and front wall is far away, thrust ai.thrust(1) elif trackWall < 60 and frontWall >= 200: # if the track wall is close, thrust ai.thrust(1) elif backWall < 20: # if the back wall is close, thrust ai.thrust(1) ###=== TURNING RULES ===### # Escape shots if shot > 0 and shot < 70: # if a shot is closeby, turn and thrust to avoid if self.angleDif(rightDir, ai.shotX(0)) < self.angleDif( leftDir, ai.shotX(0) ) or self.angleDif(rightDir, ai.shotY(0)) < self.angleDif( leftDir, ai.shotY(0) ): # if shot is coming from the right, turn away and thrust # print("Turning: avoiding shot")#debug ai.turnLeft(1) ai.thrust(1) elif self.angleDif(leftDir, ai.shotX(0)) < self.angleDif( rightDir, ai.shotX(0) ) or self.angleDif(leftDir, ai.shotY(0)) < self.angleDif( rightDir, ai.shotY(0) ): # if shot is coming from the left, turn away and shoot ------> change this shot is just a number # print("Turning: avoiding shot")#debug ai.turnRight(1) ai.thrust(1) # Turn towards unoccluded enemy elif aimer >= 0 and self.angleDif(rightDir, aimer) < self.angleDif( leftDir, aimer) and not self.enemyBehindWall( 0): # if an enemy to the right, turn and shoot it if ai.screenEnemyX(0) >= 0: enemyDeg = self.angleToPointDeg( (ai.selfX(), ai.selfY()), (ai.screenEnemyX(0), ai.screenEnemyY(0))) ai.setTurnSpeed( self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin, turnSpeedMax)) else: enemyDeg = self.angleToPointDeg( (ai.selfRadarX(), ai.selfRadarY()), (ai.closestRadarX(), ai.closestRadarY())) ai.setTurnSpeed( self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin, turnSpeedMax)) # print("Turning: aiming right")#debug ai.turnRight(1) elif aimer >= 0 and self.angleDif(leftDir, aimer) < self.angleDif( rightDir, aimer) and not self.enemyBehindWall( 0): # if an enemy to the left, turn and shoot it if ai.screenEnemyX(0) >= 0: enemyDeg = self.angleToPointDeg( (ai.selfX(), ai.selfY()), (ai.screenEnemyX(0), ai.screenEnemyY(0))) ai.setTurnSpeed( self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin, turnSpeedMax)) else: enemyDeg = self.angleToPointDeg( (ai.selfRadarX(), ai.selfRadarY()), (ai.closestRadarX(), ai.closestRadarY())) ai.setTurnSpeed( self.rangeMap(abs(enemyDeg), 0, 180, self.turnSpeedMin, turnSpeedMax)) # print("Turning: aiming left")#debug ai.turnLeft(1) #fuzzy avoid walls ahead elif leftRisk > rightRisk and trackRisk > 0.5: # and min(feelers) < self.nearLimit: #if the left wall and track walls are close, turn right #if enemyX >=0 and enemyY >= 0 and ai.wallBetween(selfX, selfY, enemyX, enemyY) == -1: ai.turnRight(1) # print("Turning: fuzzy right")#debug elif rightRisk > leftRisk and trackRisk > 0.5: # and min(feelers) < self.nearLimit: #if the right wall and track walls are close, turn left # if enemyX >=0 and enemyY >= 0 and ai.wallBetween(selfX, selfY, enemyX, enemyY) == -1: ai.turnLeft(1) # print("Turning: fuzzy left")#debug # Turn to open space nearest the angle to the enemy elif self.enemyBehindWall(0) and min(feelers) > self.nearLimit: if angleToOpenSpace < 0: # print("Turning: open space left")#debug ai.turnLeft(1) elif angleToOpenSpace > 0: # print("Turning: open space right")#debug ai.turnRight(1) # if neural net value is not between 0.48 and 0.52 then we have to turn right or left elif not (turn >= 0.43 and turn <= 0.57): if turn < 0.43: # turn right if value is below 0.43 # print("Turning: neural net right")#debug ai.turnRight(1) elif turn > 0.57: # turn left if value is below 0.57 # print("Turning: neural net left")#debug ai.turnLeft(1) ###=== FIRING RULES ===### # Restrict firing to reasonably accurate attempts: # accurate range, enemy not behind wall and enemy close enough if self.headingDiff( heading, ai.aimdir(0)) < targetingAccuracy and not self.enemyBehindWall( 0) and ai.enemyDistance(0) < self.enemyFireDist: ai.fireShot() # print("Shot Fired")#debug # print("Firing Dist: ", self.enemyFireDist)#debug self.counter += 1 ###=== How did we die? and other Fitness Calculations ===### # Fitness function information self.totalDists += ai.enemyDistance(0) if ai.enemyDistance(0) > 0: self.currentDist = ai.enemyDistance(0) if self.currentDist < self.lastDist: self.fitness += 1 self.lastDist = self.currentDist self.fitness += 1 alive = ai.selfAlive() message = ai.scanGameMsg(1) # print(message)#debug if alive == 0: self.framesDead += 1 # print(self.framesDead, message)#debug if self.framesDead == 2: # print("dead now")#debug # Ran into wall if message.find("Beal-Morneault") != -1 and message.find( "wall") != -1: print("End of match: wall collision.") #debug self.fitness -= self.wallPenalty # Crashed into player elif message.find("crashed.") != -1: print("End of match: player collision.") #debug self.fitness -= self.crashPenalty # Killed by bullet elif message.find("Beal-Morneault was") != -1: print("End of match: killed by opponent.") #debug self.fitness -= self.killedPenalty # Killed the opponent elif message.find("by a shot from Beal-Morneault") != -1: print("End of match: killed the opponent!") #debug self.fitness += self.killerBonus else: print("End of match: enemy died.") self.fitness += (ai.selfScore() - ai.enemyScoreId(0) ) * self.scoreDiffBonusFactor ai.quitAI() else: self.framesDead = 0
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 tshoot(self): ai.fireShot() self.shot = 1
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)
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()
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)
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
def AI_loop(): #Release keys ai.thrust(0) ai.turnLeft(0) ai.turnRight(0) ai.setTurnSpeed(45) #version 1 #weight = [[2.550266104824679, 2.3362165093652325, 1.5807639825885653, -1.4221271253105021, -2.9016633051153033, 0.19417452140965624, -0.7858351527734876, 1.7007054652187374, -1.2878795871096003, -0.4424965595968601, -0.2098355723057839, -0.44589477290286, -1.28594990724884, -1.3690169977065576, 0.3544860383973552, 6.217219847875376, 0.860574363988091, 2.2201551532796278, -0.8753105245960284, -3.996221026155867], [1.2129751833981501, -0.39489947867021, -0.6103434139585784, -1.2708044350734833, -1.5573093901624917, -1.557604341746312, -1.2827496511035177, -0.9246564003301376, -0.23107040698453024, -1.5425394097477745, -1.4771599558270174, 0.2944529525896604, -1.1435880833167114, -0.3759001845094683, 1.0831029491193562, 10.872354760265011, 1.144123313013959, 1.7595540288210627, 0.8635020714036377, -4.297485822683961], [1.8188948190777128, 0.09439031462959233, -0.847775917083252, -1.405107602608586, -1.7690221739488392, -1.1109052455684598, -2.6450672036914233, 0.030731427696499176, -0.2946854249221828, -1.8479267010834763, -0.805455012410909, -0.813140294052604, -0.9596518171731309, -0.3457898885997498, 2.475092958793735, 10.083435742082035, -0.06084554193326555, 1.0806629332945072, 0.7473583842777305, -3.877247786710661], [2.0672870520768396, 0.38281701914368993, -0.005236452915172924, -1.4956012417457192, -1.7508071552812512, -0.9005733793451363, -2.878211127434142, -1.2220639837673026, -0.9185476375005881, -1.7826861963483098, -0.7583425587659988, -1.487790400385734, 0.11808779723484325, 0.8151115320326576, 0.6097271910362039, 9.614591007776966, 0.11348211650835437, 0.2470605588666191, 0.7756360382263713, -3.4363467385706947], [3.6038858021282376, -1.0370819889884997, 0.4708304068702163, -0.3642924379955362, -1.453687395646565, 1.4063080999900834, -1.10856503569124, 2.3526480602154547, -1.5610983424792233, 2.3853558076892702, 19.94833443689028, -12.69539073265824, -0.9902791927606951, 8.295676706656682, -4.298734455635756, -0.0025716052512615587, -6.409022843502277, 0.09111256867920055, -4.030440120195723, 3.492809018575802], [1.3591504199962974, 1.9072598188796497, -0.1572708702380515, 0.09492823659144821, -3.7351986863846083, 0.40505220240012596, -1.9549392152162859, -2.586314308488624, -3.7018425831031645, -5.482428253068671, 4.428582910286293, -1.5213795728349209, 0.5400002739420181, 2.9059037796579896, 2.6277680497655895, -1.8640865126897534, -0.6224859804858036, -1.396411973686435, -0.5078939832140874, 2.051658396295223], [1.175158276089206, -1.2148455782187595, -1.454188463616707, -1.09740835241673, -2.1594485844130222, -1.7972789486557026, -0.9155374250603407, -0.29820044138586366, -0.7785155444830156, -2.025138745902771, -1.6802716254717354, -0.30410102005599904, -1.223426421447483, -0.11751846910051522, 0.31681541237784006, 10.27378681270671, -0.7094343875663274, -0.2424664935484773, -0.2939004614060303, -4.296350317611783], [0.36863234324926053, -0.9610417384319038, -1.5221426669771745, -1.6699391522556555, -2.4150675341320302, -0.9701348498928188, 0.3301128338672623, -1.1899875029101021, -1.551467039269157, -0.7310205075943033, -2.240783107949794, 1.1458475330082836, -1.5219788681646966, -0.896726155668825, -0.33143554301190264, 9.628148038991878, 1.8942397548285632, 2.023202119366169, 0.546810331024528, -5.447158503850532], [-2.5325002348433836, 2.930321785073164, -0.3709087227063106, -1.596465592260178, -3.2029991773002093, -2.265914884490358, 0.0980004999320249, -0.65965866562701, -2.704314672375589], [3.8122215871064373, -4.104335315746765, -2.4263184454881643, -2.9871305358007847, -1.924528198404445, -1.712928503475962, -3.534593371802936, -3.415888364195872, -10.874219685646768], [-0.3944278078731921, -0.04084176486614567, 0.2714551892673181, 0.7993076771484554, 0.7365400310117656, -0.7809436451077841, -0.9083619709096666, -0.058239190231471775, 3.1465762688553176]] #version 2.0 #weight = [[1.0348539030121238, 0.2138499159570746, 0.479883480446254, -0.815396855708741, 0.49133825699664746, -0.0016578918355715545, -0.34770516312181937, -0.6097858551178503, -0.4918317248574016, 0.11707224567853086, 0.7297002395624936, -0.8597712863767865, -0.16881378431217509, 2.2362662180903667, -4.543038144901142, -16.686427437927875, 13.864966206625198, -0.23218667876918228, 0.8742424369741824, -2.271505837531476, 1.7486613252486425, -3.6031912349032216], [1.3853183689023212, 1.0304105460921373, -0.35087146909354233, 0.2274803616136946, -0.48862423480728573, -0.28648692421364597, 1.0841392532520482, 0.09412595558859133, 0.04866731125206707, 1.6389417563949324, 1.569604147737689, 1.6674544809606042, -12.058686048723487, 1.6368666415264628, 1.396237317222872, 1.2659222326172297, 3.1379063984127007, 0.7199586864633407, -1.9911656575885084, 2.9843283564742276, 2.6409315634963537, -2.0522490561304605], [0.4853983621760604, 1.2278363034213262, -0.534538281011901, 1.4921029488413888, -0.5682938512874909, 0.136034639999008, -0.4823176751789039, 0.7299930410894804, -0.3380570275737542, 1.3378814857822758, 1.2744108061572372, 1.325840335845375, -3.5612921690285995, 3.0321845576145816, 0.38139827152793515, 0.5064679570604714, 3.7091834398982626, 1.6379493417868636, 0.009587243300177439, 1.081135119209285, 2.5046956599199497, 0.13829859663336705], [0.513584374521616, 0.1396027345647868, 0.22003104586082617, -1.020520258285862, 0.4525530610072905, -0.863674094851868, -0.1456566996482743, 0.047996417778646244, 0.8347183398777567, 0.2826901799136233, 0.25344471815587716, 2.4968765095441396, -10.767402471368994, 3.8646627117880543, 2.3902808619796256, 3.3890357704770366, 2.7852380631143063, 2.225603236672958, -0.504426424340796, 2.29799007530236, 3.698254347831815, -1.753619719499527], [1.7334142614615886, 0.3508351395425429, -1.3235043172085337, -4.712617614027661, 1.1137039036149858, 0.8939884576104425, 1.4487232713125826, 0.6755150172128699, 0.318891192947518, 0.2805540371856373, 2.9414146196728352, -0.14367593664104633, -2.9917413394008117, 1.8153446120603003, 4.6017363644759754, 2.457776782413075, 5.5378846257137235, 0.7949800980703232, 0.2702571471773026, 1.100592199222341, 1.7157229479854335, -3.3274868243083957], [0.5231825029989361, 0.6019825286766198, -1.5992975503634501, -3.9344512049190894, 1.6336177072216003, 1.0628326454663803, 0.5918183390244784, 1.217921833774511, 0.4680719963330766, 0.9297477538302225, 0.8635738588292406, 1.6123162284279307, -4.76548028065167, 2.7691114482670924, 3.7902925560585246, 2.2893541227789482, 4.854469198939795, 1.5709878981378373, 0.37408474552320636, 0.6419956750602649, 2.9549686547606604, -2.660182601822638], [-0.550163275118097, 0.37800898901961993, -0.04232253225402527, 2.093644426941638, 1.045179858641923, 0.17005426100535168, 0.8465114783670081, 1.4954083025618152, 0.3547558848475753, 0.34645209087435797, 2.2504511328564063, 1.3135532902149227, -3.0308408568456784, 5.43208120520448, -4.637196129987869, -3.161519314264366, -4.277206554828303, -1.6912563245385916, 0.3395595728232166, -2.333523479350886, -0.9987914267823002, 0.1610415218209105], [0.46948929915550935, 0.12889104192032508, 0.3401893045804767, 4.2983485686243865, 0.3854536170989966, 0.5262024444908596, 0.2950204361704613, -0.11321412769052538, 0.7837012446764751, -1.2288323210441408, 0.48733523578267335, -0.4941691955389192, -7.3345652400167785, 1.9849081055744189, 3.122078959588068, 3.153727628013528, 3.099949834024941, 1.4301203728009702, -2.450297291533477, 0.4866949103297095, 1.3085441479240818, -2.1529498660578272], [-5.422148034686218, -2.8624753773956213, -1.4630602941910256, -6.4644825272727555, 1.6578707022365173, 0.5417475615846311, -3.776505543782651, -0.3272613058048199, -11.214986749661405], [-0.4436919292206762, -0.7284650510957685, -0.6342756229880361, 0.9166538346166686, 1.6302616941783443, -0.8118961608614238, -2.0714209395581937, -1.451433486092866, 1.9514970032640198], [2.0769540125793706, 0.23830906704269733, 0.7347161610910736, 0.5162733263135993, 1.3368292920252003, -1.3117432470255128, -1.3790837382523748, -1.3480998845289651, 4.698401132146571]] #version 2.1 #weight = [[2.6574536219859954, 1.4120937065147632, -0.9964549800883609, 0.9829450240801283, 0.2495879247807427, 1.1381847380133334, -0.05196357532829188, 0.2177067274916204, -0.18184327410783213, 1.5266603183390501, 1.1655327431726694, 1.4538826690762883, -0.20683390530966128, 6.210064369810357, -8.561138298832656, -15.141175220253892, 6.106295692739355, 0.6405611427897536, -0.619993022682205, 1.007397838658101, 1.8023875927980566, -8.56084958009673], [-0.24393761943006065, 1.4183607997158474, 0.09425096739424323, -0.2029915364248618, -0.7047604711501737, -0.0935972308466856, 0.8717326095896473, -0.10156289186319209, 2.3806674108927504, 0.8941263712307272, 2.19666699382538, 5.439990992459093, -7.887763096330764, 4.376131819990081, -7.277174385169979, -6.23193471018197, 6.183055457541491, -5.260002714722831, -2.3740028160395306, -1.0713124331187596, -9.519253163502997, -1.4012255957146156], [0.3092480039638263, -0.4648769995596973, 0.6619300014076455, -0.46738595522067783, 0.6463143239185843, -0.3356599551491758, -0.07742840335361757, -0.08670089870486762, -1.0148874579847347, 0.6282039895206416, 0.0917037047570109, -3.0884211717258094, -2.9171475628826005, -5.2581770493742, 3.453984870615717, -13.281480220687158, 21.374514932424127, -0.35919340067953615, -4.507048961766401, -0.43497321367666286, 3.981087014967673, 5.194889802241377], [-0.03121713746523143, 0.658170605383361, -0.2531309874005128, 0.956053578189376, 0.17821381135503844, 0.9266091750903891, -0.7953127031716622, 0.25553535888799306, 1.2314795539801198, 1.7852813842712634, -1.678532026084331, 4.148612498411745, 11.497105966655482, 6.8439102702199905, -8.815526428315916, -10.68902746912835, 1.6552990220080521, -3.7660569824116514, -1.250313377541347, -4.010914159908631, -5.8884341097372195, -4.454576745980269], [-0.4179297978084346, -0.20729405361397024, -0.1908786221315172, 0.10539854813859785, 0.07843607504676799, 0.6195143407049103, 0.7639470794024154, -0.22613246503323617, -0.808794223276627, -3.986427259494685, -0.6242168921052, -4.851136935980087, -4.529358594179961, 11.105038570667329, -2.200829446416287, -6.283638873080318, 4.994052607138207, -4.553987480597325, 1.4653663463512383, 0.2715398849863545, -3.1038381473752947, 1.5065869048018716], [1.2584072596819222, 1.1674410041604275, -0.5743325298341463, -0.3388908458287391, 0.5398287219373928, 0.6928231086714423, 1.243679682694803, -0.19568686996939313, 1.2423157756071983, 0.21848078121475661, 0.3589992525842555, 1.5523854122185874, 0.6397410441460646, 1.6716979844170503, 0.4828892285077613, 0.10691743774742216, 1.1716346322785212, -0.5813275893180825, 2.2140566424114656, -0.1231126520190957, 0.04770159507691009, -2.1594339641333775], [-2.5874889166458668, -2.582448894674087, -0.18642847250761904, -2.6422877632335373, -0.5036047565186409, -1.051574064560562, -1.0818989283059326, 0.6841682215326471, 0.41626282522368874, -3.79257878188681, -1.3240134851842005, -1.9420905097076873, 0.8243883262742999, -7.802686423554441, 1.6918832996529027, -10.483794529908046, 15.2976684119092, 2.5733337193769756, -0.9116818784135264, -1.5547819662126645, 4.142840206327382, -2.090695413014931], [1.0764323157454567, 0.6218709226146542, -0.20195119278881704, 0.30153072984647106, -1.0905820003929068, 0.16830734351948176, -0.16316793287642833, 0.26994730128651184, 0.11883269570067774, 1.5050655788131275, 2.12478298868216, 1.8724528735832382, -9.992959548883213, 2.884389965267914, 1.9823775978843652, 3.737063063844405, -1.0910694249788688, 5.930640876337126, 1.951307647889452, 3.9553613020571254, 8.690945764123681, -2.4232041534698454], [-4.384417022954113, -3.0918662562803068, -7.726594171948947, -5.12664908515938, -4.192451131446429, 4.84236399875358, -3.246501900071273, -9.801013755028295, -15.227079629670676], [-0.23857789590670314, 0.29482615509055193, -0.1455673203542247, 0.1643798905166609, -0.27755653011958453, 0.5809882975230658, -0.5215285482006043, -0.01819270339694459, 2.063484712690624], [3.546123040725555, -1.959504721014008, -0.7261195149861891, -0.4785114544074893, -0.09236303094081319, -4.805456318000878, -0.036423874389163, 5.012915787303742, 3.868962275727431]] #version 3.0 weight = [[ 8.191250040918927, 6.27173707204309, -1.5693807080107147, 4.119398296191028, 2.3616206301898766, -0.7323869349492124, 2.486553068844425, -0.45536371325253633, -0.3687745154687114, -3.1088839935075185, -0.05587784835405292, 0.6571302514686768, -10.028372472771732, 3.8448643065601353, -2.652534229783426, -10.449790496659174, 7.741139611111101, 2.7409749794682967, -4.6097948777426385, -4.981152265960378, 2.7143437597384596, -4.694090681712407 ], [ -0.030895862131684215, 0.26621276605346755, 0.9230897005332416, -0.4758685620625008, -0.06352234015475698, 1.2588453088499063, -0.09963864033723083, -0.31141873756715177, 0.28847293451434036, 0.34505152121295535, 5.098267069997973, 2.646644815424944, -17.74330713120718, 2.654454328811601, 4.510066807731305, 4.103473134287021, 0.8598216142868608, 4.612555330648679, 2.815330379442696, -0.15780885969600447, 2.9611464519494937, -6.0581704830364105 ], [ 1.033261017834031, 2.2596093023466954, 1.7268998648570575, 0.44864109370237526, 0.7591324601946607, 0.6906565437425874, 2.629984741521933, 0.6241958474716665, 3.536441324883574, 0.2541748455397638, 0.2525710200015311, 2.8359109175327113, 1.762090695407072, 12.187637551645857, -9.140646989185479, -2.9815431686503846, -9.988637349873864, 0.43215321503529064, 8.345343370250644, 1.1521308925663178, -1.1281648724312259, 3.3902990853125092 ], [ 1.0049794470830362, -0.7449654413114497, -0.63125755716366, 0.0053166699034151695, -0.24612628789711924, 1.1734683559949564, -1.6555593171950367, -2.565975090769444, 1.9867361332351496, -0.5605258501562052, -1.5110887916337794, 3.06200905597275, -6.008095473776355, -2.016663405897449, 3.4195954560140147, 14.825862028755896, -2.7462848013849137, -0.39254000972253356, 1.7428289687785519, 1.785685106672233, 1.2462915430440114, 2.6759769682936465 ], [ 4.148780486013721, -0.13730603124121193, -5.052884530378326, -0.500240504302838, 1.277475994884024, 1.4559480864495136, 3.330782067457632, -0.7560866225456043, -0.26928228655567515, 3.2848618360054758, 3.351850050825831, 3.664788598875761, -3.2217330598047984, 5.746652079858086, -0.9860525538859995, -2.765751901849228, 4.207195149042036, 2.3164523398315673, 7.536953358159171, 0.11666368068900933, -0.18132901896016088, -1.5741567977199717 ], [ -0.5723312773219504, -0.401957802429893, -0.6549603352077887, -1.398121941197631, -0.8276608370019821, -0.3179360870110543, 1.7412314562375526, 0.3385224570280019, -1.1765599948700323, 3.734490395002858, -0.5847551079895305, 0.21856472268345342, 10.774541980633623, 1.7884441905162747, -4.683250392879576, -17.650363684880357, 11.132094587129899, 8.66068475926927, -2.7489088786606097, -1.4381650446445755, 7.975437063770457, -2.640108642851023 ], [ 2.1110007372977804, 1.2360274639756719, -0.8108730809502931, -16.124950502124733, 2.662138312598027, 2.3773254324912774, -2.720298558971462, -4.265329074637865, -0.25144327837503094, -2.9949467815547925, -3.471570280761414, -1.8201345079830522, -2.015423312269534, -1.0759640449995418, 0.7604085531363927, -3.776217804542179, 8.099313371556228, -2.2675787692915517, 1.6998198862504297, -1.7929679067883642, -1.5210826217751623, -3.865894314359684 ], [ 0.6144904524816717, 0.04913418805237108, 0.08324523476559223, 0.7429416512021989, -0.8390331237708188, -0.47882353523776894, -0.6447033246188264, 1.6576222848674202, -0.2279029726443557, 1.1507295645486104, 1.5598656661442598, 0.8075073118691607, -3.18299901724587, 3.5192878463675963, -2.701226257527224, -21.178359693208034, 21.263948959033144, -10.07030573724461, -3.558973856323051, 0.23314267210038322, -6.662438907078873, -0.5888729690751188 ], [ -3.339014775385027, -7.827394292679561, -4.372840224160649, -3.7605771754135513, -0.6313399998378019, -2.6379943108276347, -2.454291908700733, -5.280895755111516, -19.354807527969758 ], [ -0.9759946383247877, 2.132316812411122, 2.8841719581167093, 5.5508168330525205, 2.627164707304193, 3.2589609535633066, 6.963017339633833, 2.2716945827489243, 16.154759519191924 ], [ 2.209533360006208, 0.8621106189833698, -0.8129862285765431, -1.2243852003111615, 1.531239159833933, 0.5501197292456045, -0.23588452031877324, -1.1549578752034027, 6.026822106599074 ]] #version 4.0 #weight = [[-3.2058672826538226, -4.31391408122669, -1.9142730193376933, -12.293777380421279, -2.387891297087439, 8.68679739367632, 1.0179091788563874, -1.1864651582010062, -5.568031035561596, 10.945033828831686, 7.834750114240515, 5.236440705736634, 20.255314949700157, -21.131631805193365, 1.1921446179087332, 2.018654043419168, -0.2924517823379373, 15.52712339353064, 0.4366372743461329, -0.8921765394311489, 10.405800179608214, -6.15314996443214], [-0.767454814697132, 0.3270540823716981, -0.8959997918702388, 31.985345421820234, 0.22583658469481768, -2.0904605899208324, 0.4273784018244229, 2.410751875131632, 0.024146724253123635, 5.774397922512571, 2.458713516031913, 1.762173402101207, 2.4863575229034893, 1.2173166557680144, 1.0852018143201185, -0.6947862502345211, -1.685440093621986, -0.5422644885853604, 0.371672490154568, -0.2525046130649465, -1.029469030781961, 9.593208633096934], [-17.154289700405826, 6.681215029944982, 24.231673612921732, 10.324563893797086, 4.136772272224117, -3.1130638723311854, 4.515112124645894, 0.9997905970901713, 5.504413268424209, 2.556598535155231, 0.9112635102744883, -4.962770675068674, -4.82389609822076, -0.06446445903848136, -2.4723316708037455, -0.5428165207942364, -7.315416348931536, 3.758828330059573, -2.8242187299905104, 1.734759841857676, 1.152129889773087, -16.76116456438828], [-0.06501157798767042, 1.4567442381814775, 0.9349636919861257, 0.19724327199064498, -0.420269773403132, -2.1926632389218015, 0.2821862127493296, 1.086614298228036, -1.3470084505075066, -2.5425432327309725, -4.921990833014046, -5.7874211435604055, 18.233500984503404, -5.258927298346166, -2.7632824301844674, -1.5865425620663383, -3.544791995252406, -4.670581973470177, -3.684265737192663, 3.0114885750233533, -0.9837815489549244, 5.246249412485307], [1.1910478253012255, -6.950521519652001, -6.368798586947499, -1.1159827626967929, 0.4696053239231746, -3.4963611951544813, 3.2069808840793717, -0.29163836630846424, -1.162953555504215, 4.18226971278469, 1.7555255094099949, -8.631403882178496, 23.101508541149407, -9.943888865373255, -2.398509463841365, -1.5222440287239083, -4.6397469121876105, -5.051940560197273, -6.99207199098171, 2.0055663192979694, -4.156765384104997, 6.503141180454374], [13.57280110649763, 6.019858632939986, -6.623141307302827, 10.424604902876256, 1.9953953875531552, -2.8741792504226993, 6.324323577178682, 0.3237797275733685, 5.015829713420473, -3.163853873021663, -8.003529070682655, -2.569082989340861, 6.120241052637211, 9.4680533376308, 1.4801486980559733, 6.186741469482223, -6.3901997771464325, -0.4758370721444493, 3.7677353063058834, 2.1151557605462927, 3.719474623674176, 10.557091243460672], [-0.2642642130222138, 0.26786550762849154, -0.9427811955331561, -0.2364293132308143, 1.3949475546439096, -2.6407826419238893, 0.6354977463456999, 2.464228996893628, -1.3032328924471543, 0.6310809412687352, 0.2150228942866794, 0.1666872069415135, -1.1688200772596649, 0.5587682415999177, -16.240262823009203, -15.309974334147668, -21.092956359650223, -0.03489069449202142, -0.27234786457753307, 1.2545484627048427, 1.6602215411736982, -51.350319274916906], [-0.4094335642145207, -2.7161788962936706, -1.7603001846797477, -0.5544816845501243, -4.510222713012636, 1.5605002257698304, -8.96746631978038, -5.3007555759058915, -7.110638740469486, -9.471747771777766, 0.37642701103211224, -1.6651592565994224, 6.784765962521808, -1.0277822113096637, 6.534140012818554, 10.858659224471731, -7.758962199813096, 5.3587546037248455, 2.4404851235620293, 3.481086036858572, 11.907556844606972, -13.401843449443835], [2.0659837913131405, -0.14329228112994682, 1.9457778772936758, 4.133378441565563, 1.7041876294084106, 2.108694875989604, 0.12983813277031878, 1.7958474394612036, 8.153932467113053], [0.11643592872953325, -10.22888784455891, -3.6413763265223356, -0.09614441107097611, -1.3936972167809407, -1.3870197146168897, -9.534945384944287, -3.1002738480008474, -20.820409089481043], [0.8559343326586317, 0.04234430072728213, 0.26482898747796946, -0.08527318527432841, 0.06940052650931862, 1.9641457658906996, 5.440040212500676, 0.3369850098494597, 11.497649165230445]] #version 4.1 (one with the nice graph) #weight = [[-0.6336871836186742, -1.167449399674333, 1.5956042715086312, -0.21746232381716357, 0.4924773974375489, -0.3462269717536519, -0.6311900392944271, -0.5929514960172317, 0.1371947405840749, -6.210216722545269, -1.4738866614997401, -12.57421503716155, 2.620980725291159, -3.2803130250947174, 12.622311830890181, 7.713670113608869, 3.6242916501175415, 25.432172442078194, -0.8405187249673789, 7.1432738014996895, 18.26022897549941, 1.4109974923185213], [-11.105837854649254, -7.820311990608547, 3.0012610167287503, -0.1910324647998192, 0.08325847247282948, -0.5819301617108271, 0.9398619514742088, 1.009051523873811, -2.118293092448913, 0.4103611075513795, 1.0402860509214722, -1.7412482148893549, 0.26012356816735377, -4.335269782619253, -1.0570531353492916, -2.4999030051600215, 0.28839923928022726, 6.2542962156128015, -14.086981076503191, 4.922554443274598, 1.849230774636396, 2.3978661981287255], [-0.02658216467208656, -0.4567525529173624, 0.4080479223932608, -0.053138768369102016, 0.5206715877850056, 0.6751450489041755, 0.20162547991524546, 0.6134489793283575, 0.2896435340542568, 0.676324397439964, -1.1180031670763215, 4.076953197913241, 0.5794145911087009, 1.1079670175785348, -3.593328019060576, 29.334753570608516, -30.037636840629485, 20.24140077237241, -5.45050248901165, 3.833685348051116, 10.895804118348266, -1.61670276989451], [0.28107153708717253, 0.2915099109358589, 0.2177970292812639, -0.005398472809729429, -0.25238686767377416, -0.08112274096303755, 0.04446637310540559, 0.2581330134935834, 0.3031677972637258, 0.39864193293585487, -0.24606861652934522, -0.48660633368651673, 0.03829779403858733, 0.05984275172813295, -0.9187526444101501, 0.31187578251812453, 1.5332557444242427, -1.4280798271393336, 61.56646657768384, -0.3211740028092684, -0.7282095085807708, -2.563425817508993], [-0.7979338089740086, -0.09878905184569382, -0.4428021364890991, 0.3618827471695385, -0.3196537619045103, 0.22314544704300662, -1.2017661140916953, 0.7151119298341873, -0.9606273221217585, -2.3130066083307703, -4.862764904189488, 0.40222490450774034, 15.446856161709984, -0.9063942695154484, -8.442314526427046, -5.43354311301973, 4.242406629554832, -13.307854854916519, 4.757242266522814, 0.8398823376019574, -7.6782500417795925, 5.5672100581979125], [-1.6847104170390788, -0.3011276468371078, 1.4071760320082194, 21.34984935715374, 0.4865347451530222, -0.8166575908953556, 3.128433131146564, -3.698665404711435, -2.854491469526845, -2.7887450944341405, 3.392862911423948, 2.328419632311121, 2.8963975025604887, -4.6377295674144605, -0.2517475529778077, 2.4381455436056205, -2.9673339472087874, -2.097916806984301, -8.840277055062272, 2.849011424376529, 1.9942837835492426, 0.25152431623620164], [-0.049781158431637905, -0.03879691465869378, 0.44175778950536654, -1.0700337751860096, -1.1828239616713498, -0.9372979625794005, 1.8482942438744485, -1.6927653423204483, 0.6789656207035225, 3.4643085005403043, -1.0906579434091543, -0.2775925482028496, -1.532811332009522, -27.141709870404135, 6.861054770754714, -0.15601697422228428, 7.373640042690445, 12.807079782807135, -8.908749285571979, 5.029818543985575, 7.746521014366709, -13.015279876125758], [-0.600288749647936, 0.7434759111804204, 0.7049245548247375, -0.3400560941655398, -0.1566484446686828, -1.1823337439859116, -1.7797066226420561, -3.0416357676882497, 0.0560575388155142, -3.359678491714238, 1.8742210929752985, -6.17810127516823, 0.8549184384759082, -5.662014907989769, 11.906105304897132, 19.839064275187916, -18.577530960582994, -13.318860580578937, -25.802025782533274, -3.1000014158527507, -6.6161228887695165, 4.872810633662916], [5.3168358410809535, 8.741715068424897, 8.196196480805414, 10.480088434094554, 13.111540315356688, 1.152146928212274, 7.5476137392724745, 4.326526156998077, 30.59781459287896], [1.3147812998647914, -0.6685892889388354, 0.4587298258365566, -0.17965210245606686, 0.11767335127743912, -17.926769568945723, -1.2324182658286038, 0.835335520014771, -15.120770311963799], [1.9748216111482906, -0.18028910512661622, 0.9572830923409497, 0.9866678898063377, -1.043145401079122, 1.0146393195271237, 1.8415713450067672, -10.848541553891737, 8.641922234711396]] #sendData = getSendDataV1() sendData = getSendData() output = getOutput(sendData, 21, 8, 3, weight) #print (output) if output[0] > .65: ai.turnRight(1) elif output[0] < .35: ai.turnLeft(1) if output[1] > .6: ai.thrust(1) if output[2] > .3: ai.fireShot()
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()
def shoot(): ai.fireShot()
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()
def open_fire(self): """ Fires the selected target """ angle = angle_to(self.target) ai.turnToDeg(int(angle)) ai.fireShot()
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()
def tick(): # # The API won't print out exceptions, so we have to catch and print them ourselves. # try: # # Declare global variables so we have access to them in the function # global tickCount global mode global targetId global lis # # Reset the state machine if we die. # if not ai.selfAlive(): tickCount = 0 mode = "ready" return tickCount += 1 # # Read some "sensors" into local variables, to avoid excessive calls to the API # and improve readability. # selfX = ai.selfX() selfY = ai.selfY() selfVelX = ai.selfVelX() selfVelY = ai.selfVelY() selfSpeed = ai.selfSpeed() selfHeading = ai.selfHeadingRad() selfTracking = ai.selfTrackingRad() # 0-2pi, 0 in x direction, positive toward y # Add more sensors readings here print("tick count:", tickCount, "mode", mode) if mode == "ready": for i in range(4): if ai.targetAlive(i): targetId = i break xDiff = ai.targetX(targetId) - ai.selfX() yDiff = ai.targetY(targetId) - ai.selfY() targetDirection = math.atan2(yDiff, xDiff) ai.turnToRad(targetDirection) ai.setPower(20) if selfSpeed < 20: ai.thrust() if xDiff < 400 and yDiff < 400: mode = "brake" if abs(selfHeading - selfTracking) > 0.1 and selfSpeed > 20: mode = "stab" elif mode == "stab": if selfSpeed < 2: mode = "ready" else: ai.setPower(50) ai.turnToRad(math.pi + ai.selfTrackingRad()) ai.thrust() elif mode == "brake": if selfSpeed < 2: mode = "aim" else: ai.setPower(50) ai.turnToRad(math.pi + ai.selfTrackingRad()) ai.thrust() elif mode == "aim": xDiff = ai.targetX(targetId) - ai.selfX() yDiff = ai.targetY(targetId) - ai.selfY() targetDirection = math.atan2(yDiff, xDiff) ai.turnToRad(targetDirection) angleDiff = abs(targetDirection - selfHeading) if angleDiff < 0.25 or angleDiff > 2 * math.pi - 0.25: mode = "shoot" elif mode == "shoot": ai.fireShot() xDiff = ai.targetX(targetId) - ai.selfX() yDiff = ai.targetY(targetId) - ai.selfY() targetDirection = math.atan2(yDiff, xDiff) ai.turnToRad(targetDirection) if not ai.targetAlive(targetId): mode = "ready" except: print(traceback.print_exc())
def tick(): # # The API won't print out exceptions, so we have to catch and print them ourselves. # try: # # Declare global variables so we have access to them in the function # global tickCount global mode # # Reset the state machine if we die. # if not ai.selfAlive(): tickCount = 0 mode = "ready" return tickCount += 1 # # Read some "sensors" into local variables, to avoid excessive calls to the API # and improve readability. # selfX = ai.selfX() selfY = ai.selfY() selfVelX = ai.selfVelX() selfVelY = ai.selfVelY() selfSpeed = ai.selfSpeed() shotSpeed = ai.getOption("shotSpeed") selfHeading = ai.selfHeadingRad() # 0-2pi, 0 in x direction, positive toward y # Add more sensors readings here print ("tick count:", tickCount, "mode", mode) def scalar_product(lis, n): return [x * n for x in lis] def vector_sum(list1, list2): return [sum(x) for x in zip(list1, list2)] # [a, b, c] [d, e, f] # [a,d] [b, e] [c, f] def time_of_impact(px, py, vx, vy, s): a = s * s - (vx * vx + vy * vy) b = px * vx + py * vy c = px * px + py * py d = b*b + a*c t = 0 # Time if d >= 0: t = (b + math.sqrt(d)) / a if (t < 0): t = 0 return t closest_asteroid_id = 0 if mode == "ready": #print("self vel Y: ", selfVelY) if ai.selfSpeed() > 7: # We're going too fast!!! mode = "brake" # Find closest asteroid if tickCount % 1 == 0: for i in range(ai.asteroidCountScreen()): #if not 130 <= ai.radarType(i) <= 133: # We're only looking for asteroids. # continue radar_dist = ai.asteroidDist(i) if radar_dist < ai.asteroidDist(closest_asteroid_id): closest_asteroid_id = i if ai.asteroidCountScreen() > 0: mode = "aim" if mode == "aim": asteroidX = ai.asteroidX(closest_asteroid_id) asteroidY = ai.asteroidY(closest_asteroid_id) asteroidVelX = ai.asteroidVelX(closest_asteroid_id) asteroidVelY = ai.asteroidVelY(closest_asteroid_id) if asteroidX - selfX > ai.mapWidthPixels()/1.2: print("Target is to the right. Seen to the left") dx = ai.mapWidthPixels() - asteroidX asteroidX = -dx #targetPosition[0] -= ai.mapWidthPixels() if selfX - asteroidX > ai.mapWidthPixels()/1.2: print("Target is to the left. Seen to the right") dx = asteroidX asteroidX = ai.mapWidthPixels() + dx #targetPosition[0] += ai.mapWidthPixels() if asteroidY - selfY > ai.mapHeightPixels()/1.2: print("Target is above. Seen below") dx = ai.mapHeightPixels() - asteroidY asteroidY = -dx #targetPosition[1] -= ai.mapHeightPixels() if selfY - asteroidY > ai.mapHeightPixels()/1.2: print("Target is below. Seen above.") dx = asteroidY asteroidY = ai.mapHeightPixels() + dy #targetPosition[1] += ai.mapHeightPixels() time = time_of_impact(asteroidX - selfX, asteroidY - selfY, asteroidVelX, asteroidVelY, shotSpeed) targetPosition = vector_sum((asteroidX - selfX, asteroidY - selfY), scalar_product((asteroidVelX, asteroidVelY), time*1.1)) print("Map size x: ", ai.mapWidthPixels()) targetAngle = math.atan2(targetPosition[1], targetPosition[0]) ai.turnToRad(targetAngle) if abs(selfHeading - targetAngle) % 2*math.pi < 0.8: print("Firing at", targetPosition[0], ",", targetPosition[1]) ai.fireShot() mode = "ready" if mode == "brake": velocityVector = (selfVelX, selfVelY) targetAngle = math.pi + (math.atan2(velocityVector[1], velocityVector[0])) # Negative velocity vector ai.turnToRad(targetAngle) ai.thrust() selfVel = velocityVector[0] * velocityVector[0] + velocityVector[1] * velocityVector[1] if selfVel < 3: # The bot has come to a stop. mode = "ready" except: print(traceback.print_exc())
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
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)
def AI_loop(): #Release keys ai.thrust(0) ai.turnLeft(0) ai.turnRight(0) ai.setTurnSpeed(45) turn, thrust, shoot = 0.5, 0, 0 maxSpeed = 3 shotAngle = 9 wallClose = 12 #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, 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) calcDir = 0 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 ai.turnRight(1) #Screw aiming and turn right and thrust ai.thrust(1) thrust = 1 #This is arguably a horrible strategy because our sideways profile is much larger, but it's required for the grade elif diff >= 0: if diff >= 180: ai.turnRight(1) #If the target is to our right- turn right turn = 1 else : ai.turnLeft(1) #If the target is to our left - turn left turn = 0 else : if diff > -180: ai.turnRight(1) #If the target is to our right - turn right turn = 1 else : ai.turnLeft(1) #If the target is to our left - turn left turn = 0 #Rules for avoiding death else : # 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) 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 if abs(calcDir - heading) < shotAngle : #If we are close to the current proper trajectory for a shot then fire ai.fireShot() shoot = 1 #adjust the the learning NN infile = open("myBotWeights.txt","r") weight = eval(infile.read()) infile.close() sendData = getSendData(turn, thrust, shoot) weight = adjustNN(sendData, 21, 8, 3, weight) outfile = open("myBotWeights.txt","w") outfile.write(str(weight)) outfile.close()