def __init__(self): self.screen = pygame.Surface((256, 256)) self.dialog = pygame.Surface((208, 38)) self.room_frame_0 = pygame.Surface((256, 256)) self.room_frame_1 = pygame.Surface((256, 256)) self.avatar_frame_0 = pygame.Surface((16, 16)) self.avatar_frame_1 = pygame.Surface((16, 16)) self.renderer = Renderer() self.avatar_x = 0 self.avatar_y = 0 self.avatar_room = None self.palette = None self.dialogue_lines = [] self.dialogue_char = 0 self.dialogue_style = { "shk": False, "wvy": False, "rbw": False, "clr": 0 } self.starting = False self.ending = False self.ended = True self.prev_frame = -1
def __init__(self, population_size, sim_population, sensor_radius=1, n_threads=1): """Initializes a simulation :population_size: The allowable population size per generation :sim_population: The allowable population size per grid simulation :n_threads: The number of threads to utilize """ # Type checking if type(n_threads) is not int: raise TypeError('Thread count must be a positive integer') elif n_threads < 1: raise ValueError('Thread count must be above 0') self.n_threads = n_threads self.sensor_radius = sensor_radius # Create genetic pool for simulation dims = (sensor_radius + 1, sensor_radius + 1) self.pool = NEAT_Pool(dims, 3) self.population = Population(population_size, sim_population, self.pool) self.renderer = Renderer()
def draw_avatars_timeline(dates): pygame.init() renderer = Renderer() width = max(len(date[1]) for date in dates) height = len(dates) gap = 0 page1 = pygame.Surface( (width * (8 * 2 + gap) + gap, height * (8 * 2 + gap) + gap)) page2 = pygame.Surface( (width * (8 * 2 + gap) + gap, height * (8 * 2 + gap) + gap)) values1 = [] values2 = [] maps = [] for y, row in enumerate(dates): for x, entry in enumerate(row[1]): i = y * width + x pos = (x * (8 * 2 + gap) + gap, y * (8 * 2 + gap) + gap) try: world = get_world(entry["boid"]) frame1, frame2 = get_avatar_frames(renderer, world) page1.blit(frame1, pos) page2.blit(frame2, pos) except Exception as e: print("Couldn't parse '%s' (%s)" % (entry["title"], entry["boid"])) pygame.image.save(page1, "timeline1.png") pygame.image.save(page2, "timeline2.png")
def __init__(self): # This will hold the actual units, # and will be used for logic. initial_grid = Grid(GRID_WIDTH, GRID_HEIGHT) self.__populate_grid__(initial_grid) # This will be the initial state. self.state = State(initial_grid, 0) # Keep track of how many turn self.renderer = Renderer()
def main(): print "Dwarf should not keep moving barrels around." game = Game((10, 6, 128)) renderer = Renderer(game) game.schedule(Dwarf((3, 3, 64))) for i in range(4): barrel = Item(Barrel, (8, i, 64), 1.0) barrel.contents.append(Item(Beverage, None, Barrel.capacity)) game.world.additem(barrel) game.world.addstockpile(Stockpile([(2, 5, 64)], [Beverage.stocktype])) game.world.addstockpile(Stockpile([(4, 5, 64)], [Beverage.stocktype])) while not game.done: game.step() renderer.step()
def all_single_energy_combos(): renderer = Renderer() renderer.start() renderer.wait_till_init() x_0 = renderer.get_param() for method_name, energy_name in product(Optimizer.method_dic, Optimizer.energy_dic): print method_name, energy_name renderer.set_param(x_0) optimizer = Optimizer(None) plotting.attach_plotter(optimizer, plotting.Plotter(*get_fname("..\\res"))) optimizer.set_target("C:\\Users\\cxz\\Pictures\\target.png") optimizer.set_method(method_name) optimizer.set_energy([energy_name], [1]) optimizer.run()
def __init__(self, min_cycle_time=10): self.min_cycle_time = min_cycle_time self._run = False self._last_update = 0 self._last_mouse_pos = None self._selecting = False self._select_start_pos = None self._selection_rect = None self._mouse_right_down = False pygame.init() screen_width, screen_height = screen_size = (1024, 768) self._screen = pygame.display.set_mode(screen_size, pygame.DOUBLEBUF) self._map = Map('default') self._camera = Camera(screen_size) self._renderer = Renderer(self._screen, self._camera) self._objects = ObjectManager(self._map.size) self._event_mgr = EventManager() self._event_mgr.subscribe(pygame.QUIT, self._handle_quit) self._event_mgr.subscribe(self._camera.move_event, self._camera_moved) self._input = InputManager(self._event_mgr) self._input.set_keybind(pygame.K_ESCAPE, self.stop) self._input.set_keybind(pygame.K_q, self.stop) self._input.set_hotarea((0, 0, screen_width, 2), self._camera.set_move, {'y': -1}) self._input.set_hotarea((0, screen_height - 2, screen_width, 2), self._camera.set_move, {'y': 1}) self._input.set_hotarea((0, 0, 2, screen_height - 2), self._camera.set_move, {'x': -1}) self._input.set_hotarea((screen_width - 2, 0, 2, screen_height), self._camera.set_move, {'x': 1}) self._input.set_hotarea((2, 2, screen_width - 4, screen_height - 4), self._camera.stop_moving) self._event_mgr.subscribe(self._input.mouse_drag_start, self._select_start) self._event_mgr.subscribe(self._input.mouse_drag_update, self._select_update) self._event_mgr.subscribe(self._input.mouse_drag_end, self._select_end) self._event_mgr.subscribe(self._input.lclick, self._leftclick) self._event_mgr.subscribe(self._input.rclick, self._rightclick) self._event_mgr.subscribe(self._input.rsclick, self._right_shiftclick)
def main(): print 'Dwarf should store barrel in stockpile, then drink from it.' game = Game((10,6,128)) renderer = Renderer(game) dwarf = Dwarf((3,3,64)) dwarf.hydration = 120 game.schedule(dwarf) barrel = Item(Barrel, (8,4,64), 1.0) barrel.contents.append(Item(Beverage, None, Barrel.capacity)) game.world.additem(barrel) game.world.addstockpile(Stockpile([(2,5,64)], [Beverage.stocktype])) while not game.done: pre = barrel.contents[0].materials[0].amount game.step() if barrel.contents[0].materials[0].amount != pre: print 'Dwarf drank' renderer.step()
def draw_average(index): pygame.init() renderer = Renderer() graphic = [pygame.Surface((16, 16)), pygame.Surface((16, 16))] sums = [[[0 for x in xrange(8)] for y in xrange(8)], [[0 for x in xrange(8)] for y in xrange(8)]] avgs = [[[0 for x in xrange(8)] for y in xrange(8)], [[0 for x in xrange(8)] for y in xrange(8)]] count = 0.0 for entry in index.itervalues(): try: world = get_world(entry["boid"]) if len(world["tiles"]) > 0: graphic_ = world["sprites"]["A"]["graphic"] if len(graphic_) > 1: frame1, frame2 = graphic_[0], graphic_[-1] for y in xrange(8): for x in xrange(8): sums[0][y][x] += 1 if frame1[y][x] else 0 sums[1][y][x] += 1 if frame2[y][x] else 0 count += 1 except Exception as e: pass for y in xrange(8): for x in xrange(8): avgs[0][y][x] = sums[0][y][x] / count > 0.5 avgs[1][y][x] = sums[1][y][x] / count > 0.5 """ for y in xrange(0, 8): for x in xrange(0, 8): avg = avgs[0][y][x] * 255 color = (avg, avg, avg) graphic[0].fill(color, (x * 2, y * 2, 2, 2)) avg = avgs[1][y][x] * 255 color = (avg, avg, avg) graphic[1].fill(color, (x * 2, y * 2, 2, 2))""" renderer.render_frame_to_surface(graphic[0], avgs[0], (255, 255, 255), (0, 0, 0)) renderer.render_frame_to_surface(graphic[1], avgs[1], (255, 255, 255), (0, 0, 0)) pygame.image.save(graphic[0], "average1.png") pygame.image.save(graphic[1], "average2.png")
class Game(object): """Manages other game modules.""" def __init__(self, min_cycle_time=10): self.min_cycle_time = min_cycle_time self._run = False self._last_update = 0 self._last_mouse_pos = None self._selecting = False self._select_start_pos = None self._selection_rect = None self._mouse_right_down = False pygame.init() screen_width, screen_height = screen_size = (1024, 768) self._screen = pygame.display.set_mode(screen_size, pygame.DOUBLEBUF) self._map = Map('default') self._camera = Camera(screen_size) self._renderer = Renderer(self._screen, self._camera) self._objects = ObjectManager(self._map.size) self._event_mgr = EventManager() self._event_mgr.subscribe(pygame.QUIT, self._handle_quit) self._event_mgr.subscribe(self._camera.move_event, self._camera_moved) self._input = InputManager(self._event_mgr) self._input.set_keybind(pygame.K_ESCAPE, self.stop) self._input.set_keybind(pygame.K_q, self.stop) self._input.set_hotarea((0, 0, screen_width, 2), self._camera.set_move, {'y': -1}) self._input.set_hotarea((0, screen_height - 2, screen_width, 2), self._camera.set_move, {'y': 1}) self._input.set_hotarea((0, 0, 2, screen_height - 2), self._camera.set_move, {'x': -1}) self._input.set_hotarea((screen_width - 2, 0, 2, screen_height), self._camera.set_move, {'x': 1}) self._input.set_hotarea((2, 2, screen_width - 4, screen_height - 4), self._camera.stop_moving) self._event_mgr.subscribe(self._input.mouse_drag_start, self._select_start) self._event_mgr.subscribe(self._input.mouse_drag_update, self._select_update) self._event_mgr.subscribe(self._input.mouse_drag_end, self._select_end) self._event_mgr.subscribe(self._input.lclick, self._leftclick) self._event_mgr.subscribe(self._input.rclick, self._rightclick) self._event_mgr.subscribe(self._input.rsclick, self._right_shiftclick) def run(self): """Run the main game loop.""" self._load() self._last_update = pygame.time.get_ticks() self._run = True while self._run: gametime = pygame.time.get_ticks() time_passed = gametime - self._last_update if time_passed < self.min_cycle_time: pygame.time.wait(1) # give other threads some cpu time continue self._update(gametime, time_passed) self._draw() self._shutdown() def _load(self): unit_tex = self._renderer.load_texture('cross.png') for x in range(0, 48, 16): unit_pos = (x, 16) unit_rect = Rect(unit_pos, self._renderer.texture_size(unit_tex)) unit_id = self._objects.create(Unit, unit_rect) self._renderer.assign_texture(unit_id, unit_tex) def _shutdown(self): pass def _update(self, gametime, time_passed): self._event_mgr.update() self._objects.update(gametime) self._camera.update(time_passed) self._last_update = gametime #noinspection PyUnusedLocal def _camera_moved(self, event): if self._selecting: self._update_selection_rectangle(self._last_mouse_pos) def _select_start(self, event): self._selecting = True self._select_start_pos = self._camera.point_to_map(event.pos) self._update_selection_rectangle(event.pos) #noinspection PyUnusedLocal def _select_end(self, event): self._selecting = False self._objects.select_area(self._selection_rect) def _select_update(self, event): self._last_mouse_pos = event.pos self._update_selection_rectangle(event.pos) def _update_selection_rectangle(self, pos): map_pos = self._camera.point_to_map(pos) self._selection_rect = Rect(min(self._select_start_pos[0], map_pos[0]), min(self._select_start_pos[1], map_pos[1]), abs(map_pos[0] - self._select_start_pos[0]), abs(map_pos[1] - self._select_start_pos[1])) def _leftclick(self, event): self._objects.select_at(self._camera.point_to_map(event.pos)) def _rightclick(self, event): self._objects.send_selected(self._camera.point_to_map(event.pos)) def _right_shiftclick(self, event): self._objects.send_selected(self._camera.point_to_map(event.pos), True) def _draw(self): self._renderer.frame_start() self._renderer.draw_map(self._map) objs = self._objects.query(self._camera.view_rect) self._renderer.draw_objects(objs) if self._selecting: self._renderer.draw_rectangle(self._selection_rect, (255, 0, 0)) self._renderer.frame_end() def _draw_objects(self, surface, area): pass #noinspection PyUnusedLocal def _handle_quit(self, event): self.stop() def stop(self): self._run = False
def draw_avatars(index): pygame.init() renderer = Renderer() width = 35 height = int(math.ceil(len(index) / float(width))) print(width, height) gap = 0 page1 = pygame.Surface( (width * (8 * 2 + gap) + gap, height * (8 * 2 + gap) + gap)) page2 = pygame.Surface( (width * (8 * 2 + gap) + gap, height * (8 * 2 + gap) + gap)) values1 = [] values2 = [] urls = [] titles = [] for entry in index.itervalues(): try: world = get_world(entry["boid"]) if len(world["tiles"]) > 0: frame1, frame2 = get_avatar_frames(renderer, world) values1.append(frame1) values2.append(frame2) urls.append(entry["url"]) titles.append(entry["title"]) except Exception as e: print("Couldn't parse '%s' (%s)" % (entry["title"], entry["boid"])) #traceback.print_exc() maps = [] for y in xrange(height): for x in xrange(width): if y * width + x >= len(values1): break i = y * width + x pos = (x * (8 * 2 + gap) + gap, y * (8 * 2 + gap) + gap) page1.blit(values1[i], pos) page2.blit(values2[i], pos) maps.append((pos, urls[i], titles[i])) pygame.image.save(page1, "avatars1.png") pygame.image.save(page2, "avatars2.png") print(len(index), len(values1)) with open("avatars.html", "w") as html: html.write('<html><body><img src="avatars.gif" usemap="#avatars">\n') html.write('<map name="avatars">\n') for map in maps: pos, url, title = map x, y = pos html.write( '<area shape="rect" coords="%s,%s,%s,%s" href="%s" title="%s">\n' % (x, y, x + 16, y + 16, url, title)) html.write("</map>\n") html.write("</body></html>\n")
f_count = 1000 # fault count per mesa f_height = 1.0 # max fault height mat_list = [(0.2, 50.0), (0.3, 100.0), (0.0, 1.0), (0.2, 10.0), (0.7, 1000.0)] # material list road_maxdist = 20 # max dist for next road segment - meters road_iterations = 50 # max road placement attemps road_width = 10 # road width - meters ValidateInput(hm_width, hm_height, hm_cellsize, m_origins, m_scale, mp_segments, mp_angularvar, mp_extangularvar, mp_lengthvar, mp_extensionprob, f_radiusvar, f_distance, f_count, f_height, mat_list, road_maxdist, road_iterations, road_width) # init random.seed(_seed) app = Renderer() heightmap = hmp.HeightMap(hm_width, hm_height) matlist = material.MaterialList(mat_list) CFFkernels = CFF.InitKernels(f_radiusvar, f_height) masI = [] for i in range(0, m_origins): magent = maI.MesaAgentI(i, hm_width, hm_height, m_scale, mp_segments, mp_angularvar, mp_extangularvar, mp_lengthvar, mp_extensionprob, f_radiusvar, f_distance, f_count, f_height) magent.Run(heightmap, CFFkernels) masI.append(magent) printer.DrawMesaAgentI(masI, heightmap,
class GridEnv: """Custom Environment that follows gym interface""" def __init__(self, map, agents_info, dynamic_obs_num=0): self.window = None #Window("Test") #self.window.show(block=False) #load map info self.map = map self.obstacles = map["map"]["obstacles"] #load agents info. Pose, goal and name are all python list format with length agents_num. self.agents_num, self.agents_pose, self.agents_goal, self.agents_name = self.get_agents_info( agents_info) print("Agents number: ", self.agents_num) #Env constant self.tilesize = 16 self.font = cv2.FONT_HERSHEY_SIMPLEX self.visibility = 5 self.traj_color = np.random.randint(256, size=(self.agents_num, 3)) #Map the grid index to object type. self.idx_to_object = { 0: "free", 1: "obstacle", 2: "agent", 3: "dynamic obstacle", 4: "unseen", 5: "goal", } self.object_to_idx = dict( zip(self.idx_to_object.values(), self.idx_to_object.keys())) #initialize canvas 0 self.row = map["map"]["dimensions"][1] self.col = map["map"]["dimensions"][0] print("row: ", self.row, " col: ", self.col) self.background_img = np.ones( shape=(self.row * self.tilesize, self.col * self.tilesize, 3), dtype=np.uint8) * 255 self.renderer = Renderer(self.row, self.col, self.tilesize, self.traj_color) #simulation variable self.time = 0 self.descrip = str(self.time) self.traj = [] self.background_grid = np.zeros(shape=(self.row, self.col), dtype=int) self.current_grid = None for i in range(self.agents_num): self.traj.append([self.agents_pose[i]]) # Draw the goal and static obstacles on the background image self.background_img = self.renderer.draw_background( self.background_img, self.agents_goal, self.obstacles) self.background_grid = self.update_background_grid( self.background_grid) #initialize dynamic obstacles self.dynamic_obs_num = dynamic_obs_num self.dynamic_obs_pose = [] self.dynamic_obs_future_traj = [] self.dynamic_obs_manager = RobotManager(self.background_grid, self.idx_to_object, self.dynamic_obs_num) def reset(self): self.time = 0 self.traj = [] for i in range(self.agents_num): self.traj.append([self.agents_pose[i]]) self.background_img = np.ones( shape=(self.row * self.tilesize, self.col * self.tilesize, 3), dtype=np.uint8) * 255 self.background_img = self.renderer.draw_background( self.background_img) def render(self, show_traj=False, dynamic_obs=True): ''' @param [boolean] show_traj : Determine if we render the agents' trajactories. @param [boolean] dynamic_obs : TODO, remove this param Return the rendered image. ''' img = self.background_img.copy() if dynamic_obs: self.renderer.draw_dynamic_obs(img, self.dynamic_obs_pose) self.renderer.draw_trajectory(img, self.dynamic_obs_future_traj) if show_traj: self.renderer.draw_trajectory(img, self.traj) self.renderer.draw_agents(img, self.agents_pose) self.renderer.draw_obs(img, self.agents_pose, self.visibility) return img def agent_conflict(self, pose, idx): ''' Check if the agent's movement may be conflict with other agents. @param [numpy_array] pose : The idx-th agent's position. @param [int] idx : The index of the agent to be checked Return check conflict result, [boolean]. ''' for i in range(self.agents_num): if i == idx: continue if (pose == self.agents_pose[i]).all(): return True return False def move_agents(self, pose, act): ''' Move the agent and check if the agent will collide with obstacles, @param [numpy_array] pose : The agent's position. @param [string] act : The agent's action. Return False if collision exists, otherwise return new pose, [numpy_array]. ''' if act == '^': pose_new = pose + np.array([0, -1]) elif act == 'v': pose_new = pose + np.array([0, 1]) elif act == '>': pose_new = pose + np.array([1, 0]) elif act == '<': pose_new = pose + np.array([-1, 0]) elif act == '.': pose_new = pose + np.array([0, 0]) # Make sure the agent is not out of the map pose_new[0] = max(0, min(self.col - 1, pose_new[0])) pose_new[1] = max(0, min(self.row - 1, pose_new[1])) #color = self.background_img[pose_new[1]*self.tilesize,pose_new[0]*self.tilesize] pose_new_type = self.background_grid[pose_new[1], pose_new[0]] # Hit the obstacles in the map #if (color == OBSTACLE_COLOR).all(): if pose_new_type == self.object_to_idx["obstacle"]: return np.array([-1, -1]) else: return pose_new def get_obs(self, grid_map): # Get the observation of each agent on the current grid map observation = list() for i in range(self.agents_num): pos = self.agents_pose[i] xmin = max(int(pos[1] - self.visibility), 0) ymin = max(int(pos[0] - self.visibility), 0) xmax = min(int(pos[1] + 1 + self.visibility), self.row) ymax = min(int(pos[0] + 1 + self.visibility), self.col) observation.append(grid_map[xmin:xmax, ymin:ymax]) return observation def update_background_grid(self, grid_map): for o in self.obstacles: grid_map[int(o[1])][int(o[0])] = self.object_to_idx["obstacle"] return grid_map def get_agents_info(self, agents_info): ''' Parse the agents infomation. ''' agents_num = len(agents_info) agents_pose = [] agents_goal = [] agents_name = [] for agent in agents_info: agents_pose.append(np.array(agent["start"])) agents_goal.append(np.array(agent["goal"])) agents_name.append(agent["name"]) return agents_num, agents_pose, agents_goal, agents_name def step(self, action): ''' Parameters: ---------- @param [list] action : Agents action list for the current step. ['^','v','<','>','.'] Return the list of agents pose (array), list of observations (array) and static map (array) ''' assert ( len(action) == self.agents_num ), "The length of action list should be the same as the agents number" self.current_grid = self.background_grid.copy() #Let the dynamic obstacle move first self.dynamic_obs_manager.move_robots(self.current_grid) self.dynamic_obs_pose = self.dynamic_obs_manager.robot_poses self.dynamic_obs_future_traj = self.dynamic_obs_manager.robot_future_traj # Move the agents one by one for i in range(self.agents_num): act = action[i] pose = self.agents_pose[i] pose_new = self.move_agents(pose, act) if (pose_new == np.array([-1, -1])).all(): print("Collision with obstacles on agent ", i, "!!!") continue else: self.agents_pose[i] = pose_new pos = self.agents_pose[i] # update the agent info on current grid map self.current_grid[int(pos[1])][int( pos[0])] = self.object_to_idx["agent"] # Check if the agents collide with each other for i in range(self.agents_num): pose = self.agents_pose[i] if self.agent_conflict(pose, i): print("Agents ", i, " collide with other agents!") self.traj[i].append(self.agents_pose[i]) observations = self.get_obs(self.current_grid) print("grid size: ", self.current_grid.shape) print("img size: ", self.background_img.shape) print("Agent 1's observations: ", observations[1]) return self.agents_pose, observations, self.background_grid
def __init__(self, map, agents_info, dynamic_obs_num=0): self.window = None #Window("Test") #self.window.show(block=False) #load map info self.map = map self.obstacles = map["map"]["obstacles"] #load agents info. Pose, goal and name are all python list format with length agents_num. self.agents_num, self.agents_pose, self.agents_goal, self.agents_name = self.get_agents_info( agents_info) print("Agents number: ", self.agents_num) #Env constant self.tilesize = 16 self.font = cv2.FONT_HERSHEY_SIMPLEX self.visibility = 5 self.traj_color = np.random.randint(256, size=(self.agents_num, 3)) #Map the grid index to object type. self.idx_to_object = { 0: "free", 1: "obstacle", 2: "agent", 3: "dynamic obstacle", 4: "unseen", 5: "goal", } self.object_to_idx = dict( zip(self.idx_to_object.values(), self.idx_to_object.keys())) #initialize canvas 0 self.row = map["map"]["dimensions"][1] self.col = map["map"]["dimensions"][0] print("row: ", self.row, " col: ", self.col) self.background_img = np.ones( shape=(self.row * self.tilesize, self.col * self.tilesize, 3), dtype=np.uint8) * 255 self.renderer = Renderer(self.row, self.col, self.tilesize, self.traj_color) #simulation variable self.time = 0 self.descrip = str(self.time) self.traj = [] self.background_grid = np.zeros(shape=(self.row, self.col), dtype=int) self.current_grid = None for i in range(self.agents_num): self.traj.append([self.agents_pose[i]]) # Draw the goal and static obstacles on the background image self.background_img = self.renderer.draw_background( self.background_img, self.agents_goal, self.obstacles) self.background_grid = self.update_background_grid( self.background_grid) #initialize dynamic obstacles self.dynamic_obs_num = dynamic_obs_num self.dynamic_obs_pose = [] self.dynamic_obs_future_traj = [] self.dynamic_obs_manager = RobotManager(self.background_grid, self.idx_to_object, self.dynamic_obs_num)
class Game(object): def __init__(self): # This will hold the actual units, # and will be used for logic. initial_grid = Grid(GRID_WIDTH, GRID_HEIGHT) self.__populate_grid__(initial_grid) # This will be the initial state. self.state = State(initial_grid, 0) # Keep track of how many turn self.renderer = Renderer() # Generate a homerow of pieces. def __homerow__(self, owner, top=True): if top: y = GRID_HEIGHT - 1 direction = -1 else: y = 0 direction = 1 row = [Rook(owner, direction), Knight(owner, direction), Bishop(owner, direction)] row += [Queen(owner, direction), King(owner, direction)] row += [Bishop(owner, direction), Knight(owner, direction), Rook(owner, direction)] return row # Populate a board with units in their default placement. def __populate_grid__(self, grid): # Bottom side of the board. grid.tiles[0] = self.__homerow__(PLAYER1, top=False) grid.tiles[1] = [Pawn(PLAYER1, 1) for i in range(GRID_WIDTH)] # Top side of the board. grid.tiles[GRID_HEIGHT - 1] = self.__homerow__(PLAYER2, top=True) grid.tiles[GRID_HEIGHT - 2] = [Pawn(PLAYER2, -1) for i in range(GRID_WIDTH)] def draw_state(self): self.renderer.render_state(self.state) # Gets a move from the player. def get_user_move(self, player): moveset = self.state.get_player_moves(player) coords = [m[:2] for m in moveset] #print moveset print '\nCommand format: <unit x><unit y> to <target x><target y>' valid = False while not valid: user_in = raw_input('Please enter your move: ') try: split_input = user_in.split(' to ') unit_x, unit_y = [split_input[0][0], split_input[0][1]] target_x, target_y = [split_input[1][0], split_input[1][1]] unit_x = string.ascii_lowercase.index(unit_x.lower()) unit_y = int(unit_y) - 1 target_x = string.ascii_lowercase.index(target_x.lower()) target_y = int(target_y) - 1 except: print "Sorry, I don't understand your coordinates." continue # Get the unit object. unit = self.state.grid.get(unit_x, unit_y) # Make sure a unit exists in that tile. # And that it's owned by the player # currently making a move. if not unit or unit.owner != player: print "Sorry, you don't own that unit." continue else: # Make sure the target is a valid move. move = [[unit_x, unit_y], [target_x, target_y]] if move in coords: # Return the appropriate move object. return moveset[coords.index(move)] else: print "Sorry, that isn't a valid move." continue def execute(self, cur_state, move): origin, target, flag = move if flag: if flag['action'] == CASTLE: #self.castle(origin, target, flag['side']) print 'Castling not yet implmented.' elif flag['action'] == PROMOTION: print 'Promotion not yet implemented.' new_state = self.move(cur_state, origin, target) new_state.turn += 1 return new_state def move(self, cur_state, origin, target): # Move and Unit Information ox, oy = origin tx, ty = target unit = cur_state.grid.get(ox, oy) target_unit = cur_state.grid.get(tx, ty) # Current State Information turn = cur_state.turn p1_caps = cur_state.p1_caps p2_caps = cur_state.p2_caps #Update that the unit has moved. if not unit.has_moved: unit.has_moved = True # If the target is a unit... if target_unit: # Record the capture. if unit.owner == PLAYER1: p1_caps.append(target_unit) else: p2_caps.append(target_unit) # Construct the new state where the unit is moved. # (Since in the event of a capture the captured unit # will be overwritten in the grid, no special # handling is required.) new_grid = copy(cur_state.grid) new_grid.set(unit, tx, ty) new_grid.set(None, ox, oy) return State(new_grid, turn, p1_caps, p2_caps) def advance_turn(self): if self.state.turn % 2 == 0: player = PLAYER1 else: player = PLAYER2 move = self.get_user_move(player) self.state = self.execute(self.state, move) self.draw_state() def play(self): self.draw_state() while True: self.advance_turn()
from rendering import Renderer def load_graph(graph_filename): with tf.gfile.GFile(graph_filename, 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) return graph_def import dlib det = dlib.get_frontal_face_detector() pred = dlib.shape_predictor('shape_predictor_68_face_landmarks.dat') renderer = Renderer() def get_landmarks(image): detection = det(image, 1)[0] face_shape = pred(image, detection) l_eye_x = np.mean([face_shape.part(i).x for i in range(42, 48)]) l_eye_y = np.mean([face_shape.part(i).y for i in range(42, 48)]) r_eye_x = np.mean([face_shape.part(i).x for i in range(36, 42)]) r_eye_y = np.mean([face_shape.part(i).y for i in range(36, 42)]) l_eye = (l_eye_x, l_eye_y) r_eye = (r_eye_x, r_eye_y)
def get_renderer(): renderer = Renderer() renderer.start() renderer.wait_till_init() return renderer
def renderer_only(): renderer = Renderer() renderer.set_energy_terms(Optimizer.energy_dic.keys()) renderer.set_penalty_terms(['penalty']) from PIL import Image renderer.set_target_image(Image.open("..\\img\\target_mickey.png").convert('L')) renderer.start() renderer.wait_till_init() return renderer
ROOT = os.path.dirname(__file__) pygame.init() pygame.mouse.set_visible(False) gameDisplay = pygame.display.set_mode(SCREEN) buffer = pygame.Surface((256, 256)) pygame.display.set_caption('bitspy') clock = pygame.time.Clock() pygame.time.set_timer(pygame.USEREVENT, 1000) TIMER = 0 RENDERER = Renderer() background = pygame.Surface((256, 256)) background.fill(RENDERER.BGR) bg_inc = 255 bg_src = [(x, y) for x in xrange(16) for y in xrange(16)] bg_dst = [(x, y) for x in xrange(16) for y in xrange(16)] BLACKLIST = set() WHITELIST = set() def refresh_lists(): global WHITELIST, BLACKLIST
class BitsyPlayer: OPERATORS = { "+": operator.add, "-": operator.sub, "*": operator.mul, "/": operator.div, ">": operator.gt, "<": operator.lt, "==": operator.eq, "<=": operator.le, ">=": operator.ge, } def __init__(self): self.screen = pygame.Surface((256, 256)) self.dialog = pygame.Surface((208, 38)) self.room_frame_0 = pygame.Surface((256, 256)) self.room_frame_1 = pygame.Surface((256, 256)) self.avatar_frame_0 = pygame.Surface((16, 16)) self.avatar_frame_1 = pygame.Surface((16, 16)) self.renderer = Renderer() self.avatar_x = 0 self.avatar_y = 0 self.avatar_room = None self.palette = None self.dialogue_lines = [] self.dialogue_char = 0 self.dialogue_style = { "shk": False, "wvy": False, "rbw": False, "clr": 0 } self.starting = False self.ending = False self.ended = True self.prev_frame = -1 def change_world(self, world): self.dialogue_lines = [] self.dialogue_char = 0 self.dialogue_states = {} self.prev_frame = -1 self.starting = True self.ending = False self.ended = False self.world = world self.perturb_palettes() self.renderer.prerender_world(world) self.avatar_x = self.world["sprites"]["A"]["x"] self.avatar_y = self.world["sprites"]["A"]["y"] for item in world["items"].itervalues(): variable = '{item "%s"}' % item["id"] if variable not in world["variables"]: world["variables"][variable] = 0 self.set_room(self.world["sprites"]["A"]["room"]) self.execute_script(self.world["title"]) # if not self.dialogue_lines: self.starting = False # because i use some fixed color replacements, need to make sure no palette # contains them... def perturb_palettes(self): for palette in self.world["palettes"].itervalues(): palette["colors"] = [ self.renderer.perturb_color(color) for color in palette["colors"] ] def get_room_from_id(self, id): return self.world["rooms"][id] def input(self, action, pressed): global TIMER if TIMER >= 90: TIMER = 0 switch_focus(launcher) return if (action == "MENU" or action == "QUIT") and pressed: switch_focus(launcher) return if self.dialogue_lines: if pressed: self.advance_dialogue() else: if action == "LEFT": if self.avatar_x == 0 and "L" in self.avatar_room["links"]: self.avatar_x = 15 self.set_room(self.avatar_room["links"]["L"]) else: self.move_into(max(0, self.avatar_x - 1), self.avatar_y) elif action == "RIGHT": if self.avatar_x == 15 and "R" in self.avatar_room["links"]: self.avatar_x = 0 self.set_room(self.avatar_room["links"]["R"]) else: self.move_into(min(15, self.avatar_x + 1), self.avatar_y) elif action == "UP": if self.avatar_y == 0 and "U" in self.avatar_room["links"]: self.avatar_y = 15 self.set_room(self.avatar_room["links"]["U"]) else: self.move_into(self.avatar_x, max(0, self.avatar_y - 1)) elif action == "DOWN": if self.avatar_y == 15 and "D" in self.avatar_room["links"]: self.avatar_y = 0 self.set_room(self.avatar_room["links"]["D"]) else: self.move_into(self.avatar_x, min(15, self.avatar_y + 1)) self.draw(self.prev_frame) def set_frame_count(self, frame_count): next_frame = (frame_count // 2) % 2 if next_frame != self.prev_frame: self.draw(next_frame) if self.dialogue_lines: self.draw_next_char() self.update_dialogue() self.draw_dialog() def draw(self, frame): self.prev_frame = frame self.screen.fill(self.palette[0]) if not self.ending and not self.starting: room = self.room_frame_0 if frame == 0 else self.room_frame_1 avi = self.avatar_frame_0 if frame == 0 else self.avatar_frame_1 self.screen.blit(room, (0, 0)) self.screen.blit(avi, (self.avatar_x * 16, self.avatar_y * 16)) if self.dialogue_lines: self.draw_dialog() def draw_dialog(self): self.update_dialogue() d_x = 24 d_y = 24 if self.starting or self.ending: d_y = 108 elif self.avatar_y < 8: d_y = 194 self.screen.blit(self.dialog, (d_x, d_y)) def avatar_occupying_object(self, object): return self.avatar_occupying(object["x"], object["y"]) def avatar_occupying(self, x, y): return self.avatar_x == x and self.avatar_y == y def use_exit(self, exit): dest = exit["dest"] self.avatar_x = dest["x"] self.avatar_y = dest["y"] self.set_room(dest["room"]) def use_ending(self, ending): if ending["id"] in self.world["endings"]: self.execute_script(self.world["endings"][ending["id"]]["text"]) #self.buffer_dialogue(*self.world["endings"][ending["id"]]["text"]) self.ending = True def take_item(self, item): self.avatar_room["items"].remove(item) item_id = item["id"] inventory = self.world["sprites"]["A"]["items"] if item_id in inventory: inventory[item_id] += 1 else: inventory[item_id] = 1 variable = '{item "%s"}' % item_id self.world["variables"][variable] += 1 self.execute_dialogue(self.world["items"][item_id]["dialogue"]) def get_tile_from_id(self, tile_id): if tile_id in self.world["tiles"]: return self.world["tiles"][tile_id] else: return None def check_wall(self, x, y): room = self.avatar_room tile_id = self.avatar_room["tilemap"][y][x] tile = self.get_tile_from_id(tile_id) if room["walls"]: return tile_id in room["walls"] elif tile is not None: return tile["wall"] else: return False def get_dialogue_text(self, id): return self.world["dialogues"][id]["text"] def move_into(self, x, y): room = self.avatar_room tile = self.avatar_room["tilemap"][y][x] for sprite in self.world["sprites"].values(): if sprite["room"] == self.avatar_room["id"] and x == sprite[ "x"] and y == sprite["y"] and sprite["id"] != "A": dialogue = sprite["dialogue"] if dialogue is not None: self.execute_dialogue(dialogue) return if not self.check_wall(x, y): self.avatar_x = x self.avatar_y = y for item in room["items"]: if self.avatar_occupying_object(item): self.take_item(item) self.pre_render_room() for ending in room["endings"]: if self.avatar_occupying_object(ending): self.use_ending(ending) return for exit in room["exits"]: if self.avatar_occupying_object(exit): self.use_exit(exit) return def pre_render_room(self): self.render_room_frame(self.room_frame_0, self.avatar_room, 0) self.render_room_frame(self.room_frame_1, self.avatar_room, 1) self.avatar_frame_0.blit(self.renderer.renders["sprite_A"][0], (0, 0)) self.avatar_frame_1.blit(self.renderer.renders["sprite_A"][-1], (0, 0)) RENDERER.recolor_surface(self.avatar_frame_0, self.palette) RENDERER.recolor_surface(self.avatar_frame_1, self.palette) def render_room_frame(self, surface, room, frame): for y in xrange(0, 16): for x in xrange(0, 16): id = room["tilemap"][y][x] if id == "0": surface.fill(RENDERER.BGR, (x * 16, y * 16, 16, 16)) continue tile = self.world["tiles"][id] surface.blit(self.renderer.renders["tile_" + id][frame], (x * 16, y * 16)) for item in room["items"]: surface.blit(self.renderer.renders["item_" + item["id"]][frame], (item["x"] * 16, item["y"] * 16)) for sprite in self.world["sprites"].values(): if sprite["id"] != "A" and sprite["room"] == room["id"]: surface.blit( self.renderer.renders["sprite_" + sprite["id"]][frame], (sprite["x"] * 16, sprite["y"] * 16)) RENDERER.recolor_surface(surface, self.palette) def set_room(self, id): room = self.get_room_from_id(id) self.avatar_room = room self.palette = self.world["palettes"][room["palette"]]["colors"] self.pre_render_room() def advance_dialogue(self): if self.skip_dialogue(): return self.dialogue_lines = self.dialogue_lines[2:] if not self.dialogue_lines: self.starting = False if self.ending: self.ended = True switch_focus(launcher) self.dialog.fill(RENDERER.BLK) self.dialogue_char = 0 self.draw_next_char() def skip_dialogue(self): skipped = False while self.draw_next_char(): skipped = True return skipped def draw_next_char(self): self.dialogue_char += 1 return self.dialogue_char < sum( len(line) for line in self.dialogue_lines) def get_rainbow_color(self, time, x): hue = abs(math.sin((time / 600.0) - (x / 8.0))) rgb = colorsys.hsv_to_rgb(hue, 1, 1) return tuple(c * 255 for c in rgb) def update_dialogue(self): def disturb(func, time, offset, mult1, mult2): return func(time * mult1 - offset * mult2) self.dialog.fill(RENDERER.BLK) limit = self.dialogue_char xoff = 8 yoff = 8 xspace = 6 yspace = 8 + 4 count = 0 cut = False for y, line in enumerate(self.dialogue_lines[:2]): for x, cell in enumerate(line): if count >= limit: cut = True break time = pygame.time.get_ticks() color = None char, style = cell ox, oy = 0, 0 if style["wvy"]: oy += math.sin((time / 250.0) - (x / 2.0)) * 4 if style["shk"]: oy += (3 * disturb(math.sin, time, x, 0.1, 0.5) * disturb(math.cos, time, x, 0.3, 0.2) * disturb(math.sin, time, y, 2.0, 1.0)) ox += (3 * disturb(math.cos, time, y, 0.1, 1.0) * disturb(math.sin, time, x, 3.0, 0.7) * disturb(math.cos, time, x, 0.2, 0.3)) if style["rbw"]: color = self.get_rainbow_color(time, x) if style["clr"] > 0: color = self.palette[style["clr"] - 1] glyph = RENDERER.font.get_glyph(char, color) position = (xoff + x * xspace + int(ox), yoff + y * yspace + int(oy)) self.dialog.blit(glyph, position) count += 1 if not cut: self.dialog.blit(RENDERER.arrow, (xoff + 182, yoff + 20)) def execute_set(self, set): _, dest, expression = set self.world["variables"][dest] = self.evaluate_expression(expression) def evaluate_condition(self, condition): if condition == "ELSE": return True operator, a, b = condition left = self.evaluate_expression(a) right = self.evaluate_expression(b) value = self.OPERATORS[operator](left, right) return value def evaluate_expression(self, expression): command, values = expression[0], expression[1:] if command == "NUMBER" or command == "STRING": return values[0] elif command == "VARIABLE": variable = values[0] if not variable in self.world["variables"]: self.world["variables"][variable] = 0 return self.world["variables"][variable] elif command == "OPERATOR": operator = values[0] left = self.evaluate_expression(values[1]) right = self.evaluate_expression(values[2]) return self.OPERATORS[operator](left, right) elif command == "FUNCTION": if values[0].startswith("item"): _, string = values[0].split(" ", 1) id = string.strip('"') for item in self.world["items"].itervalues(): if item["name"] == id: id = item["id"] inventory = self.world["sprites"]["A"]["items"] if id in inventory: return inventory[id] else: return 0 return self.world["variables"][values[0]] print("WARNING: didn't understand expression") print(expression) return 0 def execute_list(self, type, options): assert options, "trying to execute an empty %s!" % type if id(options) not in self.dialogue_states: self.dialogue_states[id(options)] = -1 curr = self.dialogue_states[id(options)] if type == "SHUFFLE": curr = random.randint(0, len(options) - 1) elif type == "CYCLE": curr = (curr + 1) % len(options) elif type == "SEQUENCE": curr = min(curr + 1, len(options) - 1) self.execute_node(options[curr]) self.dialogue_states[id(options)] = curr def style_text(self, text, style): return [(char, style) for char in text] def execute_node(self, node): command = node[0] if len(node) > 1: arguments = node[1] if command == "DO": if type(arguments) == str: print(arguments) else: for argument in arguments: self.execute_node(argument) elif command == "SAY": if type(arguments) == str: text = arguments else: value = self.evaluate_expression(arguments) text = str(value) self.buffer_dialogue(*text) elif command == "SET": self.execute_set(node) elif command == "IF": for condition, block in arguments: if self.evaluate_condition(condition): self.execute_node(block) break elif command == "CYCLE" or command == "SEQUENCE" or command == "SHUFFLE": self.execute_list(command, arguments) elif command == "\n": self.buffer_dialogue("\n") elif command == "SHK": self.toggle_dialogue_style("shk") elif command == "WVY": self.toggle_dialogue_style("wvy") elif command == "RBW": self.toggle_dialogue_style("rbw") elif command == "BR": self.buffer_dialogue("\n") elif command == "CLR1": self.set_dialogue_color(1) elif command == "CLR2": self.set_dialogue_color(2) elif command == "CLR3": self.set_dialogue_color(3) else: print(command) def toggle_dialogue_style(self, style): self.dialogue_style = dict(self.dialogue_style) self.dialogue_style[style] = not self.dialogue_style[style] def set_dialogue_style(self, **kwargs): self.dialogue_style = dict(self.dialogue_style) for key, value in kwargs.iteritems(): self.dialogue_style[key] = value def set_dialogue_color(self, color): self.dialogue_style = dict(self.dialogue_style) if self.dialogue_style["clr"] == color: self.dialogue_style["clr"] = 0 else: self.dialogue_style["clr"] = color def execute_dialogue(self, id): if id is None: return False dialogue = self.world["dialogues"][id] root = dialogue["root"] if root is None: self.set_dialogue_style(shk=False, wvy=False, rbw=False, clr=0) self.buffer_dialogue(*dialogue["text"]) self.word_wrap_dialogue() else: self.execute_script(root) return True #self.debug_dialogue() def execute_script(self, root): self.set_dialogue_style(shk=False, wvy=False, rbw=False, clr=0) self.execute_node(root) self.word_wrap_dialogue() def debug_dialogue(self): for line in self.dialogue_lines: print("".join(c[0] for c in line)) def buffer_dialogue(self, *chars): if self.dialogue_lines: row = self.dialogue_lines.pop() else: row = [] for char in chars: if char == "\n": self.dialogue_lines.append(row) row = [] else: row.append((char, self.dialogue_style)) self.dialogue_lines.append(row) def word_wrap_dialogue(self): y = 0 while y < len(self.dialogue_lines): row = self.dialogue_lines[y] if len(row) > 32: split = 32 for x in reversed(xrange(31)): if row[x][0] == " ": split = x break remainder = row[split:] if remainder[0][0] == " ": del remainder[0] self.dialogue_lines.insert(y + 1, remainder) del row[split:] y += 1