def eval_genome(genomes, config): nets = [] snakes = [] ge = [] food = fd.Food() for genome_id, genome in genomes: genome.fitness = 0 net = neat.nn.FeedForwardNetwork.create(genome, config) nets.append(net) snakes.append(snk.Snake('NEAT')) ge.append(genome) pygame.init() fpsClock = pygame.time.Clock() for i in range(len(snakes)): while snakes[i].state == 'alive' and snakes[i].nb_moves < 200: ge[i].fitness = snakes[i].score relative_directions = const.RELATIVE_POSITIONS_DICTIONARY[str(snakes[i].direction)] #list relative to the current direction ['FORWARD', 'LEFT', 'RIGHT'] inputs = generate_inputs(snakes[i], food.position, relative_directions) output = nets[i].activate(inputs) # output in the form [FORWARD, LEFT, RIGHT] decision_index = output.index(max(output)) move = relative_directions[decision_index] graphics.initiateGraphics() snakes[i].move() food.isEaten(snakes[i], food) snakes[i].chooseDirection(move) graphics.updateGraphics(snakes[i], food, fpsClock, const.FPS)
def fitness(population_genome, population_size, current_generation): score_list = np.array([]) #fpsClock = pygame.time.Clock() fps = 6 snake = snake_object.Snake('genetic_alg.xml') foodie = food.Food() for i in range(population_size): snake.nb_moves = 0 while (snake.trials - 1) == i and snake.nb_moves < 20000: inputs = generate_inputs(snake, foodie.position) output = get_output(inputs, population_genome[i]) #graphics.initiateGraphics() snake.move() foodie.isEaten(snake, foodie) snake.chooseDirection(output) #graphics.updateGraphics(snake, foodie, fpsClock, fps) score_list = np.append(score_list, snake.score) return score_list
#sets up a pygame clock to limit the frame rate fpsClock = pygame.time.Clock() #(delay, intervals [ms]) pygame.key.set_repeat(1, 40) last_moves = [] #frame rate limit fps = const.FPS if __name__ == '__main__': #initiate the objects snake = snake.Snake('Naive1.2-g') food = food.Food() #The number of trials is taken as a command line argument max_trials = int(sys.argv[1]) #main loop while snake.trials <= max_trials: #loop through events for event in pygame.event.get(): #quits the program if the user quits if event.type == QUIT: datalogger.logAverageScore('Naive1.2-g') pygame.quit() sys.exit()