def get_right(self): return [ Auxiliars.angle_to_vector(self.physics.get_angle() + math.pi / 2.0)[0], Auxiliars.angle_to_vector(self.physics.get_angle() + math.pi / 2.0)[1] ]
def __init__(self, pars, player_pos, wih=None, who=None): self.pars = pars v = random.uniform(0, pars['v_max']) # velocity [0, v_max] # orientation [0, 360] self.pars["ang"] = random.uniform(0, 360) front = Auxiliars.angle_to_vector(self.pars["ang"]) self.pars["vel"] = [v * front[0], v * front[1]] # self.pars["pos"] = [uniform(0, pars['WIDTH']), uniform(0, pars['HEIGHT'])] Ship.__init__(self, self.pars, True, self.pars["acc"], self.pars["ang_acc"], self.pars["fr"]) self.delay = 0 # self.dv = pars["acc_max"] self.d_player = 0 # distance to player self.angle_front = 0 self.angle_right = 0 self.facing(player_pos) # orientation to player Ship.set_score(self, pars["score"]) # fitness (score) self.wih = wih self.who = who af = lambda x: np.tanh(x) # activation function h1 = af( np.matmul( self.wih, np.mat(np.array([1.0, self.angle_front, self.d_player])).transpose())) # hidden layer out = af( np.matmul( self.who, np.mat(np.append(np.mat(np.ones(np.size(h1, 1))), h1, axis=0)))) # output layer
def facing(self, enemy, other): front = enemy.front right = enemy.right vec = [(other.pos[0] - enemy.pos[0])/Auxiliars.dist(enemy.pos, other.pos), (other.pos[1] - enemy.pos[1])/Auxiliars.dist(enemy.pos, other.pos)] enemy.angle_front, enemy.angle_right = (math.acos(front[0]*vec[0] + front[1]*vec[1])*180.0/math.pi, math.acos(right[0]*vec[0] + right[1]*vec[1])*180.0/math.pi) if enemy.angle_front <= enemy.values["ang_rang"]: return True
def enemy_ai(self, player): enemy_copy = self.enemy_group.copy() for enemy in enemy_copy: if self.facing(enemy, player) and Auxiliars.dist(enemy.pos, player.pos) > enemy.values["min_dist"]: enemy.thrust(True) print("thrust") elif self.facing(enemy, player) and Auxiliars.dist(enemy.pos, player.pos) < enemy.values["min_dist"]: enemy.thrust() enemy.shoot() print("not thrust") if self.facing(enemy, player): #and np.random.random_sample()<math.exp(-(enemy.values["V"])/enemy.values["T"]): enemy.key(0.0, True) elif not self.facing(enemy, player) and 0.0 <= enemy.angle_right < 90.0: enemy.key(enemy.values["ang_acc"]) elif not self.facing(enemy, player) and 90.0 <= enemy.angle_right <= 180.0: enemy.key(-enemy.values["ang_acc"]) elif self.facing(enemy, player) and Auxiliars.dist(enemy.pos, player.pos) <= enemy.values["min_dist"]: enemy.shoot() print("Shoot") self.enemy_group = enemy_copy.copy()
def rock_spawner(self): x=0 for s in self.rock_group: x+=1 rock_pos=[random.randrange(0, self.globals_dict["WIDTH"]-44),random.randrange(0, self.globals_dict["HEIGHT"]-44)] if self.globals_dict["score"]>0 and self.globals_dict["score"]%5==0: self.explosion_group=set() self.globals_dict["sc_dif"]+=.2 rock_vel=[random.randrange(-1,3) * random.random() * self.globals_dict["sc_dif"], random.randrange(-1,3) * random.random() * self.globals_dict["sc_dif"]] if self.globals_dict["started"] and x<12 and Auxiliars.dist(rock_pos, self.pars["my_ship"].get_pos())> (self.pars["ship_info"].get_radius() + self.pars["asteroid_info"].get_radius())*1.2: a_rock = Sprite(rock_pos ,rock_vel, random.random(), 0.10471976, self.pars["asteroid_image"], \ self.pars["asteroid_info"], self.globals_dict["WIDTH"], self.globals_dict["HEIGHT"]) self.rock_group.add(a_rock)
def facing(self, other_pos): front = Ship.get_front(self) right = Ship.get_right(self) self.d_player = Auxiliars.dist(Ship.get_pos(self), other_pos) vec = [(other_pos[0] - Ship.get_pos(self)[0]) / self.d_player, (other_pos[1] - Ship.get_pos(self)[1]) / self.d_player] phi = math.atan2(vec[1], vec[0]) # self.angle_front, self.angle_right = (math.acos(front[0]*vec[0] + front[1]*vec[1])*180.0/math.pi, math.acos(right[0]*vec[0] + right[1]*vec[1])*180.0/math.pi) front = Ship.get_front(self) self.angle_front = ( (phi - math.atan2(front[1], front[0])) * 180.0 / math.pi) / 360.0 self.d_player = self.d_player / 1000 if self.angle_front <= self.pars[ "ang_rang"] / 360.0 and self.angle_front >= -self.pars[ "ang_rang"] / 360.0: self.delay += 1 if self.delay >= 5: Ship.shoot(self) self.delay = 0
def evolve(self, organisms_old, gen): self.enemy_group = set() self.dead = set() elitism_num = int( np.floor(self.settings['elitism'] * self.settings['pop_size'])) new_orgs = self.settings['pop_size'] - elitism_num # --- GET STATS FROM CURRENT GENERATION ----------------+ stats = defaultdict(int) for org in organisms_old: if org.score > stats['BEST'] or stats['BEST'] == 0: stats['BEST'] = org.score if org.score < stats['WORST'] or stats['WORST'] == 0: stats['WORST'] = org.score stats['SUM'] += org.score stats['COUNT'] += 1 stats['AVG'] = stats['SUM'] / stats['COUNT'] # --- ELITISM (KEEP BEST PERFORMING ORGANISMS) ---------+ orgs_sorted = sorted(organisms_old, key=operator.attrgetter('score'), reverse=True) self.population = [] for i in range(0, elitism_num): aux_dict = {"wih": orgs_sorted[i].wih, "woh": orgs_sorted[i].who, "pos": [random.randrange(0, self.settings['WIDTH']), \ random.randrange(0, self.settings['HEIGHT'])]} self.population.append( Auxiliars.merge_two_dicts(orgs_sorted[i].pars, aux_dict)) # --- GENERATE NEW ORGANISMS ---------------------------+ for w in range(elitism_num - 1, self.settings["pop_size"]): aux_dict = dict() # SELECTION (TRUNCATION SELECTION) canidates = range(0, elitism_num) random_index = random.sample(canidates, 2) org_1 = orgs_sorted[random_index[0]] org_2 = orgs_sorted[random_index[1]] # CROSSOVER crossover_weight = random.random() aux_dict["wih"] = (crossover_weight * org_1.wih) + \ ((1 - crossover_weight) * org_2.wih) aux_dict["who"] = (crossover_weight * org_1.who) + \ ((1 - crossover_weight) * org_2.who) aux_dict["pos"] = [ random.randrange(0, self.settings['WIDTH']), random.randrange(0, self.settings['HEIGHT']) ] aux_dict["v_max"] = (crossover_weight * org_1.pars["v_max"]) + \ ((1 - crossover_weight) * org_2.pars["v_max"]) aux_dict["ang_rang"] = (crossover_weight * org_1.pars["ang_rang"]) + \ ((1 - crossover_weight) * org_2.pars["ang_rang"]) aux_dict["acc"] = (crossover_weight * org_1.get_acc()) + \ ((1 - crossover_weight) * org_2.get_acc()) aux_dict["ang_acc"] = (crossover_weight * org_1.get_ang_acc()) + \ ((1 - crossover_weight) * org_2.get_ang_acc()) aux_dict["vel"] = [0, 0] aux_dict["ang_vel"] = float(self.settings["ang_vel_median"] * np.random.randn(1) + self.settings["ang_vel_std_dev"]) aux_dict["ang"] = float(self.settings["ang_median"] * np.random.randn(1) + self.settings["ang_std_dev"]) aux_dict["WIDTH"] = self.settings["WIDTH"] aux_dict["HEIGHT"] = self.settings["HEIGHT"] aux_dict["score"] = 0 aux_dict["fr"] = self.settings["fr"] aux_dict["lives"] = self.settings["lives"] # MUTATION mutate = random.random() if mutate <= self.settings['mutate']: # PICK WHICH WEIGHT MATRIX TO MUTATE mat_pick = random.randint(0, 1) # MUTATE: WIH WEIGHTS if mat_pick == 0: index_row = random.randint(0, self.settings['hnodes'] - 1) aux_dict["wih"][index_row] = aux_dict["wih"][index_row] * \ random.uniform(0.9, 1.1) if aux_dict["wih"][index_row].any() > 1: aux_dict["wih"][index_row] = 1 if aux_dict["wih"][index_row].any() < - \ 1: aux_dict["wih"][index_row] = -1 # MUTATE: WHO WEIGHTS if mat_pick == 1: index_row = random.randint(0, self.settings['onodes'] - 1) index_col = random.randint(0, self.settings['hnodes'] - 1) aux_dict["who"][index_row][index_col] = aux_dict["who"][index_row][index_col] * \ random.uniform(0.9, 1.1) if aux_dict["who"][index_row][index_col] > 1: aux_dict["who"][index_row][index_col] = 1 if aux_dict["who"][index_row][index_col] < -1: aux_dict["who"][index_row][index_col] = -1 self.population.append(aux_dict)
def spawn_ships(self, player_pos): self.enemy_group = set([ EnemyShip(Auxiliars.merge_two_dicts(org, self.p), player_pos, org["wih"], org["who"]) for org in self.population ])
def get_front(self): return [ Auxiliars.angle_to_vector(self.physics.get_angle())[0], Auxiliars.angle_to_vector(self.physics.get_angle())[1] ]
def collide(self, other): if Auxiliars.dist(self.kinematic_dict["pos"], other.get_physics_component().get_pos()) <= self.radius + other.get_physics_component().get_radius(): return True else: return False
def get_right(self): return [Auxiliars.angle_to_vector(self.kinematic_dict["ang"]+math.pi/2.0)[0], Auxiliars.angle_to_vector(self.kinematic_dict["ang"]+math.pi/2.0)[1]]
def get_front(self): return [Auxiliars.angle_to_vector(self.kinematic_dict["ang"])[0], Auxiliars.angle_to_vector(self.kinematic_dict["ang"])[1]]
def collide(self, other_object): if Auxiliars.dist(other_object.get_pos(), self.get_pos() ) <= other_object.get_radius() + self.get_radius(): return True else: return False
def shoot(self): self.missile_group.add(Sprite([self.pos[0]+self.radius*Auxiliars.angle_to_vector(self.values["angle"])[0],\ self.pos[1]+self.radius*Auxiliars.angle_to_vector(self.values["angle"])[1]], \ [self.vel[0]+(Auxiliars.angle_to_vector(self.values["angle"])[0])*7 , self.vel[1]+(Auxiliars.angle_to_vector(self.values["angle"])[1])*7], \ 0, 0, self.pars["missile_image"], self.pars["missile_info"], self.WIDTH, self.HEIGHT, self.pars["missile_sound"]))
def get_right(self): return [Auxiliars.angle_to_vector(self.values["angle"]+math.pi/2.0)[0], Auxiliars.angle_to_vector(self.values["angle"]+math.pi/2.0)[1]]
def get_front(self): return [Auxiliars.angle_to_vector(self.values["angle"])[0], Auxiliars.angle_to_vector(self.values["angle"])[1]]