class Player(): def __init__(self, num, imr, amr, io, hidden_layers, activations): layers = [io[0]] + hidden_layers + [io[1]] self.brain = NeuralNetwork(layers, activations, 'SSE', imr=imr, amr=amr) self.num = num self.imr = imr self.amr = amr self.io = io self.hidden_layers = hidden_layers self.activations = activations self.fitness = 0 self.x = X self.y = Y self.r = R # the player plays the game and returns its score (frames survived) def calculate_fitness(self): fitness = game.play(self) self.fitness = fitness def mutate(self): self.brain.mutate() def crossover(self, other): brain = self.brain.crossover(other.brain) child = Player(self.num, self.imr, self.amr, self.io, self.hidden_layers, self.activations) child.brain = brain return child def move(self, dx, dy): #print(self.y) self.x += dx self.y += dy def clone(self): dolly = Player(self.num, self.imr, self.amr, self.io, self.hidden_layers, self.activations) dolly.brain = self.brain.clone() return dolly def decide(self, vision, n): x = np.array(vision) x[0:n] = x[0:n] / (game.WIDTH - self.x + self.r ) # bound the values [0,1] p = self.brain.forward_propogation(x)[0][-1] return p > THRESHOLD def intersects(self, other): # if the type is a rectangular barrier, check to see if any points on the barrier's perimeter is within the circle's radius if type(other) == game.Barrier: # check top and bottom for x in range(other.x, other.x + other.width): for y in [other.y, other.y + other.height]: if dist([x, y], [self.x, self.y]) < self.r: return True # check left and right for y in range(other.y, other.y + other.height): for x in [other.x, other.x + other.width]: if dist([x, y], [self.x, self.y]) < self.r: return True return False # less than method used for sorting players by fitness def __lt__(self, other): return self.fitness < other.fitness # equals method used for sorting players by fitness def __eq__(self, other): return self.fitness == other.fitness
def crossover(bird1, bird2): return BirdAgent(NeuralNetwork.crossover(bird1.brain, bird2.brain))