def __init__(self, nb=0, col=(0, 0, 0), pos=(0, 0), angle=0, res=20, sonars=None, encoders=None, servos=None, cameras=None, gyroscopes=None): self.nb = nb self.col = col self.pos = pos self.angle = angle self.mode = "Manual" self.modes = ["Manual", "Roam"] self.grid = Grid(300, res) self.servo_angles = [0, 0] self.sonars = sonars self.servos = servos self.cameras = cameras self.encoders = encoders self.gyroscopes = gyroscopes self.current_camera = 0 self.motors = Motors(nb) self.encoder_last = [encoder.read() for encoder in encoders] # For removing offset self.body = ((-6, -9), (6, -9), (6, 9), (-6, 9))
def __init__(self): # setting up the screen self.screen_size = screen_size self.screen = pygame.display.set_mode(self.screen_size) # fake screen is used for the game over screen self.fake_screen = None # clock and its defined frame rate self.clock = pygame.time.Clock() self.fps = 80 # Grid self.grid = Grid() # Pac-Man self.player = self.grid.get_player() # list of all enemies self.enemies = pygame.sprite.Group() self.grid.get_enemies(self.enemies, self.player) # list of food for our player self.foods = pygame.sprite.Group() self.grid.get_foods(self.foods) # list of all our sprites self.all_sprites = pygame.sprite.Group(self.foods, self.enemies, self.player) # if the game is running self.running = True # if the game has ended self.ended = False # used font self.font = font
def init(GENS, netlist_number): # prepare the data ends, starts, tpnum, net_number, SIZE, count_dict = get_data(netlist_number) # Random or Sorted # points_to_connect = sort_points_random(starts, ends) points_to_connect = sort_points3(starts, ends, count_dict) # create Instances generation = [Instance(Grid(SIZE, starts + ends)) for i in range(GENS)] # For every instance, connect the grid (deepcopy??) if new: for gen in generation: # A algorithm Wires, connected, not_connected = get_wires(gen.main, points_to_connect) # Link it to the instance gen.start((Wires, not_connected)) gen.main.value_grid = second_value(SIZE) else: # Loads wires from wire file data_path = "data\\pre_made_wires\\6" wire_names = os.listdir('data\\pre_made_wires\\6') # Add wire paths to the name, if wire name contains wire wire_paths = [data_path+"\\"+i for i in wire_names if 'wire' in i] for i, gen in enumerate(generation): # Load for every wire and reset the grid gen = load_gen(gen, name = wire_paths[i], excel_data = [((1, 3, 0), (9, 10, 0))]) gen.main.value_grid = second_value(SIZE) return generation, tpnum, SIZE, starts+ends
def plant_prop_sima(generation, options, SIZE, all_points, tpnum): ''' Plant prop like function with temprature ''' loops = int(options['swaploops']) swaps = int(options['swaps']) iterations = int(loops / 4) GENS = len(generation) delta_t = 0.01**(1 / (loops)) swap_list = [i + 1 * swaps for i in range(len(generation))] temp_list = [(i * (1 / len(generation))) + 0.1 for i in range(len(generation))] data = [] for iter in range(iterations): #50 # PRint loops loading(iter, loops) scrore_board = [i.score1() for i in generation] scrore_board.sort() scrore_board.reverse() for i, gen in enumerate(generation): SWAPS = swap_list[scrore_board.index(gen.score1())] TEMP = temp_list[scrore_board.index(gen.score1())] for i in range(loops): #100 gen.main, new_wires, new_not_con = swap_wires_prop( gen.gwires(), gen.gnotc(), gen.main, SWAPS, gen.t * TEMP) random.shuffle(new_wires) random.shuffle(new_not_con) gen.snotc(new_not_con) gen.swires(new_wires) gen.t = update_temperature(gen.t, delta_t) generation.sort(key=sortit) generation.reverse() shortest = generation[0].score1() data.append([ sum([w.length for w in generation[0].wires]), len(generation[0].wires) ]) short_list = [] for gen in generation: if gen.score1() == shortest: short_list.append(gen) short_list.sort(key=shortestit) X = short_list[0] generation = [Instance(Grid(SIZE, all_points)) for i in range(GENS)] for geni in generation: geni.snotc([i for i in X.not_connected]) new_wire = [] for i, w in enumerate(X.wires): new_wire.append(Wire(w.start, w.end, w.route)) geni.main.add_wire(new_wire[i]) geni.swires(new_wire) return X, data
class Buggy(object): def __init__(self, nb=0, col=(0, 0, 0), pos=(0, 0), angle=0, res=20, sonars=None, encoders=None, servos=None, cameras=None, gyroscopes=None): self.nb = nb self.col = col self.pos = pos self.angle = angle self.mode = "Manual" self.modes = ["Manual", "Roam"] self.grid = Grid(300, res) self.servo_angles = [0, 0] self.sonars = sonars self.servos = servos self.cameras = cameras self.encoders = encoders self.gyroscopes = gyroscopes self.current_camera = 0 self.motors = Motors(nb) self.encoder_last = [encoder.read() for encoder in encoders] # For removing offset self.body = ((-6, -9), (6, -9), (6, 9), (-6, 9)) def update(self, drive_cmd, servo_cmd): action = self._check_for_override( ) # Check sonar devices for override commands if action != "None": # If the override command is not "None" drive_cmd = action2drive( action) # Get the drive command, given the action to take self.motors.drive(drive_cmd) # Publish motor control (drive) disp = self._get_displacement() # Calculate total displacement x = disp * math.sin(-self.angle) # Calculate displacement in x y = disp * math.cos(-self.angle) # Calculate displacement in y self.pos = [self.pos[0] + x, self.pos[1] + y] # Calculate the position of the buggy self._update_sonars() # Update sonar devices self._update_servos(servo_cmd) # Update the servo angles self._update_gyroscopes() # Update gyroscope angles self.grid.update(self.sonars) # Update the grid def draw(self, display, pos, scale): outline = self._transform( pos, scale) # Transform body given buggy position and orientation pygame.draw.polygon(display, self.col, outline) # Draw buggy self._draw_sonar(display, pos, scale) # Draw each sonar device too def get_frame(self): if self.cameras: return self.cameras[self.current_camera].get_frame() else: return False def _check_for_override(self): for sonar in self.sonars: if sonar.action != "None": # If the device action is not "None" if sonar.data < sonar.min_dist and sonar.data != 0: # If the sonar data is lower than min_dist return sonar.action # Return the action to take return "None" def _update_gyroscopes(self): for gyroscope in self.gyroscopes: data = gyroscope.get_data() for ch in ['(', ' ', ')']: # Characters to remove from string if ch in data: data = data.replace(ch, '') # Remove character data = data.split(',') # Split data by , self.angle = -float( data[gyroscope. axis]) # Convert to float (- due to phone orientation) def _update_sonars(self): for sonar in self.sonars: sonar.update(self.pos, self.angle) # Update all sonar def _update_servos(self, servo_change): for i, angle in enumerate(servo_change): if angle == "reset": # If servo is required to reset servo_change[i] = -self.servo_angles[ i] # Change in sonar angle = - current angle self.servo_angles = map(operator.add, self.servo_angles, servo_change) for servo in self.servos: # For each servo if self.servo_angles[ servo. axis] > servo.max: # Restrict angles as per config file self.servo_angles[servo.axis] = servo.max elif self.servo_angles[servo.axis] < servo.min: self.servo_angles[servo.axis] = servo.min servo.move(self.servo_angles[servo.axis]) # Move the servo def _draw_sonar(self, display, pos, scale): for sonar in self.sonars: sonar.update(self.pos, self.angle) # Update sonar device sonar.draw(display, pos, self.angle, scale) # Draw sonar device def _transform(self, pos, scale): outline = [] # Initialise outline of buggy for point in self.body: # For every point in the outline if point[0]: # If point != 0 angle = math.atan(-float(point[1]) / float( point[0])) - self.angle # Calculate angle else: # Else avoid divide by zero angle = math.pi / 4 - self.angle # atan(x/0) = 90 if point[0] < 0: # If x coord of point is less than zero angle += math.pi # Flip by 180 degrees l = (point[0]**2 + point[1]**2)**0.5 # Hypotenuse of point x = round(-l * math.cos(angle), 0) * scale + pos[0] # Rotate and shift x y = round(-l * math.sin(angle), 0) * scale + pos[ 1] # -l because of pixel coordinate system outline.append([x, y]) # Append coord to outline return outline def _get_displacement(self): twisting = self.motors.left_dir != self.motors.right_dir # twisting = true if motor dirs are opposite encoder_data = [float(encoder.read()) for encoder in self.encoders] encoder_step = [ float(encoder.dist_per_tick) for encoder in self.encoders ] if twisting: self.encoder_last = encoder_data # Store last encoder value disp = 0 # displacement = 0 else: disp = np.array(encoder_data) - np.array( self.encoder_last) # Number of clicks since last checked disp *= np.array( encoder_step) # Multiply by distance travelled per click disp = np.mean(disp) # Take mean encoder value self.encoder_last = encoder_data # Difference between current and last value return disp
class Game: def __init__(self): # setting up the screen self.screen_size = screen_size self.screen = pygame.display.set_mode(self.screen_size) # fake screen is used for the game over screen self.fake_screen = None # clock and its defined frame rate self.clock = pygame.time.Clock() self.fps = 80 # Grid self.grid = Grid() # Pac-Man self.player = self.grid.get_player() # list of all enemies self.enemies = pygame.sprite.Group() self.grid.get_enemies(self.enemies, self.player) # list of food for our player self.foods = pygame.sprite.Group() self.grid.get_foods(self.foods) # list of all our sprites self.all_sprites = pygame.sprite.Group(self.foods, self.enemies, self.player) # if the game is running self.running = True # if the game has ended self.ended = False # used font self.font = font # function which will handle all of the events def event_handler(self): # allowing our user to exit for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() # movement controls if event.type == pygame.KEYDOWN: # says we want the Pac-Man to move right if event.key == pygame.K_RIGHT: self.player.stored_direction = "right" # says we want the Pac-Man to move left if event.key == pygame.K_LEFT: self.player.stored_direction = "left" # says we want the Pac-Man to move up if event.key == pygame.K_UP: self.player.stored_direction = "up" # says we want the Pac-Man to move down if event.key == pygame.K_DOWN: self.player.stored_direction = "down" # checking if the game has ended def check_for_end(self): # setting up the game over screen def game_over(): # while the games has ended while self.ended: # handling events self.event_handler() # freezing the screen self.fake_screen.blit(self.screen, self.screen_size) # putting the label on the screen self.fake_screen.blit(label, (self.screen_size[0] / 2 - label.get_width() / 2, self.screen_size[1] / 2 - label.get_height() / 2)) # updating the screen pygame.display.update() # checking if the game is lost for enemy in self.enemies: # checking if an enemy has collided with the player if pygame.sprite.collide_mask(enemy, self.player): self.ended = True self.running = False self.fake_screen = self.screen # the label used when you lose label = self.font.render("Oh no, You lost!", 0, colors["WHITE"]) game_over() # checking if the game is won if len(self.foods) == 0: self.ended = True self.running = False self.fake_screen = self.screen # the label used when you win label = self.font.render("Congrats, you won!", 1, colors["WHITE"]) game_over() # function drawing everything def draw_window(self): self.grid.draw_grid(self.screen) self.all_sprites.draw(self.screen) pygame.display.update() # function that is the actual game def run(self): # our game loop while self.running: # running the clock self.clock.tick(self.fps) # handling events self.event_handler() # updating sprites self.all_sprites.update() # updating the list of enemies for each enemy for enemy in self.enemies: enemy.enemies = self.enemies # checking if a food has been eaten for food in self.foods: food.get_eaten(self.player) # drawing everything self.draw_window() # checking for the end of the game self.check_for_end()