async def on_reaction(self, reaction, user): emoji = str(reaction.emoji) option = self.emoji_to_option[emoji] await self.message.clear_reaction(emoji) self.remaining_options.remove(option) if self.veto[self.step] == 'ban': self.selection_history += f"{self.team_to_letter[self.active_team()]} banned {option}\n" elif self.veto[self.step] == 'pick': if not self.choose_sides: self.match.pick(Map(self.maps[option]), self.active_team()) self.selection_history += f"{self.team_to_letter[self.active_team()]} picked {option}" await self.setup_choose_sides() else: self.match.maps[-1].choose_side(self.inactive_team(), option) self.selection_history += f" ({self.team_to_letter[self.inactive_team()]}: {option})\n" await self.unsetup_choose_sides() if len(self.remaining_options) == 1: option = self.remaining_options.pop() await self.message.clear_reaction(self.option_to_emoji[option]) self.match.pick(Map(self.maps[option]), None) self.selection_history += f"{option} was left over\n" if self.choose_sides: self.valid_users = self.inactive_team().players else: self.step += 1 self.valid_users = self.active_team().players await self.update()
def process_logic(self): if self.fear: current_time = time() self.time_fear = current_time - self.time_of_fear_start if self.time_fear >= FEAR_DURATION: self.fear = False self.time_of_fear_start = None self.time_fear = None for ghost in self.map.ghosts: if ghost.alive: ghost.change_sprites('normal') ghost.speed = CHARACTER_SPEED ghost.already_died = False for ghost in self.map.ghosts: ghost.logic(self.map.pacman, self) self.map.pacman.logic(self.map, self) if self.map.check_win(): self.best += self.point_counter self.high_score = self.best self.point_counter = 0 self.screen.fill(BGCOLOR) font_size = int(self.map.width // 10) font = pg.font.SysFont('Comic Sans MS', font_size) over = font.render("Level completed!", True, WHITE) self.screen.blit(over, (self.width // 10, font_size)) pg.display.flip() pg.time.wait(5000) self.map = Map(self.screen)
def run_calibration(n_rounds, current_period=0, verbose=0): if not os.path.isdir('../calibrations'): os.makedirs('../calibrations') map = Map() best_score = None for i in range(n_rounds): if i % 10 == 0: print(f'round {i}...') evaluations = [] array_params, pdict = build_parameters(current_period, verbose) map.from_arrays(**array_params) for _ in range(N_PERIODS): for _ in range(pdict['n_moves_per_period']): map.make_move() map.forward_all_cells() state_ids, state_numbers = map.get_states_numbers() evaluations.append((state_ids, state_numbers)) score = evaluate(evaluations, DAY, N_PERIODS) if best_score is None or ( score['hosp']['err'] <= best_score['hosp']['err'] and score['icu']['err'] <= best_score['icu']['err']): fpath = os.path.join(CALIBRATION_DIR, f'{i}.npy') to_save = { 'score': score, 'params': array_params, 'rt': map.get_r_factors(), 'pdict': pdict } print(f'New best score found: {score}, saved under {fpath}') print(f"corresponding pdict:\n{pdict}") best_score = score np.save(fpath, to_save) map.save(os.path.join('maps', 'week1'))
def refresh(self): self.fear = False self.time_fear = None self.time_of_fear_start = None self.check_gameover() if not self.gameover: self.map = Map(self.screen) self.change_high_score()
def main(): ex19_0 = get_input_by_lines(19, strip=False) ex19 = np.array(list(map(list, ex19_0))) map19 = Map(ex19) map19.set_pos(map19.find_start()) finished = False while not finished: finished = map19.step() print(''.join(map19.letters))
def tutorial(): tutplayer = Player('Tutorial') tutmap = Map(tut=True) tutplayer.linkMap(tutmap) while True: clearScreen() tutmap.update() choice = userInput() if choice == 'q': break elif choice in 'wasd': tutplayer.move(choice) del tutmap, tutplayer
def main(): ex19_0 = get_input_by_lines(19, strip=False) ex19 = np.array(list(map(list, ex19_0))) map19 = Map(ex19) map19.set_pos(map19.find_start()) finished = False cnt = 0 while not finished: finished = map19.step() if not finished: cnt += 1 print(cnt)
def save_map_and_filter(self): rospy.loginfo("Checking map from task {}".format(self.tcount)) n = len(self.M) rospy.loginfo("Saved map: \n" + str(self.curr_graph)) # copy current tgraph new_map = Map(copy(self.curr_graph)) # now do comparisons, map merging, and weight updates self.M, info = mf.filter1(self.M, new_map) self.M = mf.update_weights(self.M, new_map) # do no comparisons and just save the new map lol # self.M.append(new_map) return info
def run_calibration(n_rounds, current_period=0, verbose=0): if not os.path.isdir('../calibrations'): os.makedirs('../calibrations') memory_error = False map = Map() best_score = None for i in range(n_rounds): if i%10 == 0: print(f'round {i}...') evaluations = [] array_params, pdict = build_parameters(current_period, verbose) try: map.from_arrays(**array_params) except: print('Memory error') memory_error = True pass if memory_error: memory_error = False continue for prd in range(N_PERIODS): for _ in range(pdict['n_moves_per_period']): map.make_move(prop_cont_factor=pdict['prop_cont_factor']) map.forward_all_cells() state_ids, state_numbers = map.get_states_numbers() # Check if we are already in the good range at mid time evaluation = (state_ids, state_numbers) if prd == 6: ind_asymptomatic = np.where(evaluation[0] == 1)[0][0].astype(np.uint32) n_asymptomatic = evaluation[1][ind_asymptomatic] evaluations.append(evaluation) score, progressions = evaluate_move(evaluations) if best_score is None or score < best_score: fpath = os.path.join(CALIBRATION_DIR, f'move_3e_{i}.npy') to_save = {'score': score, 'params': array_params, 'pdict': pdict} print(f'New best score found: {score}, saved under {fpath}') print(f'Corresponding progressions: {progressions}') print(f'corresponding params:') pprint(pdict) best_score = score np.save(fpath, to_save)
def __init__(self, menu): self.size = SCR_WIDTH, SCR_HEIGHT self.menu = menu #SHOULD BE GIVEN MAP SIZE self.width = SCR_WIDTH #Should add smth for scoreboard self.height = SCR_HEIGHT self.size = (self.width, self.height) self.screen = pg.display.set_mode(self.size, pg.RESIZABLE) self.map = Map(self.screen) self.gameover = False self.fear = False self.point_counter = 0 self.high_score = 0 self.font_size = int(self.map.top // 4) self.death_counter = 0 self.font = pg.font.SysFont('Comic Sans MS', self.font_size) self.best = 0 self.time_of_fear_start = None self.time_fear = None
cellid2ind = {cell.get_id(): i for i, cell in enumerate(cells)} validated = 'OK' for i, agent in enumerate(agents): if move_proba_matrix[cellid2ind.get(agent.get_current_cell_id()), i] != 0: validated = 'Failed' break print(f'Check for move_proba_matrix 0 for current cells: {validated}') """ Test 3: Map Create a map with the `agents` and `cells` defined above 1. Check that after a move there are no duplicated agents 2. Check that after `all_home()` the cells have the same agents than at the beginning """ map = Map(cells, agents) repartition_0 = map.get_repartition() # 1. Check there is no duplicate agent map.make_move() repartition_1 = map.get_repartition() agent_list = list(chain.from_iterable(repartition_1.values())) validated = 'OK' if (len(agent_list) == len(list(set(agent_list))) and len(agent_list) == len(agents)) else 'Failed' print(f'Check for no duplicated agents after move in map: {validated}') # 2. Check the state after calling `all_home()` is same as the initial state map.all_home() repartition_2 = map.get_repartition() validated = 'OK' for cell_id, agents_cell in repartition_0.items(): if len(repartition_2.get(cell_id)) != len(agents_cell) or set(repartition_2.get(cell_id)) != set(agents_cell): validated = 'Failed'
# agents move now `f_unmove`x less than before lockdown f_unsafety = .33 unsafeties = np.load(os.path.join(map_path, 'unsafeties.npy')).flatten() unsafeties = np.multiply(unsafeties, f_unsafety) # agents move now `f_unmove`x less than before lockdown f_unmove = 1 p_moves = np.load(os.path.join(map_path, 'p_moves.npy')).flatten() n_p_moves = p_moves.shape[0] p_move = pdict['avg_p_move'] / f_unmove p_moves = get_p_moves(n_p_moves, p_move) print(f'DEBUG: mean of p_move: {np.mean(p_moves)}') res = {} map = Map() map.load(map_path) # map.set_verbose(3) map.set_p_moves(p_moves) map.set_unsafeties(unsafeties) new_hosps = [] for i in range(N_PERIODS): res[i] = {} for _ in range(n_moves_per_period): map.make_move(p_mask=.3) new_states = map.forward_all_cells(tracing_rate=0) new_hosp = new_states[new_states == 4].shape[0] new_hosps.append(new_hosp) state_ids, state_numbers = map.get_states_numbers()
attractivities[:N_HOME_CELLS] = 0 unsafeties = draw_beta(0, 1, AVG_UNSAFETY, N_CELLS).flatten() unsafeties[:N_HOME_CELLS] = 1 cells = [] for i in range(N_CELLS): cell = Cell(id=i, position=positions[i, :].flatten(), attractivity=attractivities[i], unsafety=unsafeties[i]) cells.append(cell) # =========== Map ============= map = Map(cells, agents, states, dscale=DSCALE, verbose=0) infected_agent_id = np.random.choice(range(N_AGENTS), size=N_INFECTED_AGENTS_START, replace=False) new_state_id = 1 print( f'Injecting {N_INFECTED_AGENTS_START} contaminated agents out of {N_AGENTS} in map' ) map.change_state_agents(np.array([infected_agent_id]), np.array([new_state_id])) stats = {} t_start = time()
def __init__(self, base_graph, polygon_dict, T=1, sim=True): # seq - list of vertices [v1, v2, ...] # base_map is map type rospy.init_node('lamp') self.sim = sim if self.sim == True: gz.pause() self.base_graph = base_graph self.poly_dict = polygon_dict base_tgraph = tgraph.TGraph(self.base_graph, self.poly_dict) (x, y) = base_tgraph.pos('s') self.pos = (x, y) self.travelled_dist = 0 # setup initial start pose for publishing self.start_pose = Pose( Point(x, y, 0.0), # Quaternion(*(quaternion_from_euler(0, 0, 1.57)))) Quaternion(*(quaternion_from_euler(0, 0, 3.14)))) # self.gaz_pose = (2, -4, 1.57) # (x, y, yaw (rad)), tristan self.gaz_pose = (18.5, 18.5, 3.14) # (x, y, yaw (rad)), test_large # set all edges to UNBLOCKED for initial map for (u, v) in base_tgraph.edges(): base_tgraph.set_edge_state(u, v, base_tgraph.UNBLOCKED) self.base_map = Map(base_tgraph) self.features = self.base_map.features() # store the different M for each costfn self.costfnM = [[Map(copy(base_tgraph))], [Map(copy(base_tgraph))], [Map(copy(base_tgraph))], [Map(copy(base_tgraph))]] self.M = self.costfnM[0] # initialize map storage self.T = T # number of tasks to execute self.tcount = 1 # current task being executed self.range = self.get_range() self.observation = None self.init_buffer = None # for edge_callback self.suspend = False # flag to temporarily suspend plan & edge callbacks self.path_blocked = False # flag for path being blocked, calls reactive algo self.at_final_goal = False # flag for reaching final destination self.entered_openloop = False self.mode = None # what kind of policy to follow (policy, openloop, naive) self.retries_left = NRETRIES self.localization_err = False self.costfn = 3 # costfn to use (dynamically cycle through them) self.client = actionlib.SimpleActionClient('move_base', MoveBaseAction) self.posearray_publisher = rospy.Publisher("waypoints", PoseArray, queue_size=1) self.v_publisher = rospy.Publisher("policy/current_edge", CurrEdge, queue_size=10) self.amcl_publisher = rospy.Publisher("initialpose", PoseWithCovarianceStamped, queue_size=1, latch=True) self.start_task("online") rospy.spin()
durations_hospital, durations_reanimation), axis=1) # =========== Map ============= map = Map(cell_ids, attractivities, unsafeties, xcoords, ycoords, unique_state_ids, unique_contagiousities, unique_sensitivities, unique_severities, transitions, agent_ids, home_cell_ids, p_moves, least_state_ids, current_state_ids, current_state_durations, durations, transitions_ids, dscale=DSCALE, current_period=0, verbose=0) stats = {} t_start = time() for i in range(N_PERIODS):
def init_map(): map = Map()
# creating the screen game window window = pygame.display.set_mode((480, 480)) pygame.display.set_caption('Mac Gyver et le labyrinthe infernal!') # loading images floor, wall = load_image('floor.png'), load_image('wall.png') syringe = load_image('seringue.png') intro = load_image('macgyver.jpg') # creating player class object mc_gyver = Player(0, 0, load_image('MacGyver.png')) guardian = Player(14, 14, load_image('Gardien.png')) # creating map class object map = Map(0, 0, mc_gyver) # loading the map map.loading() # creating elements of the object class aiguille = Object('aiguille', load_image('aiguille.png'), map) tube = Object('tube', load_image('tube_plastique.png'), map) ether = Object('ether', load_image('ether.png'), map) # main loop while play_game: # intro loop while menu:
attractivities[:n_home_cells] = 0 unsafeties = np.random.uniform(size=N_CELLS) unsafeties[:n_home_cells] = 1 cells = [] for i in range(N_CELLS): cell = Cell(id=i, position=positions[i, :].flatten(), attractivity=attractivities[i], unsafety=unsafeties[i]) cells.append(cell) # =========== Map ============= map = Map(cells, agents, states, verbose=2) n_infected_agents_start = 100 infected_agent_id = np.random.choice(range(N_AGENTS), size=n_infected_agents_start, replace=False) new_state_id = 1 print( f'Injecting {n_infected_agents_start} contaminated agents out of {N_AGENTS} in map' ) map.change_state_agents(np.array([infected_agent_id]), np.array([new_state_id])) N_PERIODS = 30
def Game(): pygame.init() display_width = 700 display_height = 700 gameDisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Pacman') clock = pygame.time.Clock() dead = False win = False #starting position of the player var = 0 for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 2: var = 1 break if var == 1: break x = j * 34 + 2 y = i * 34 + 2 x_change = 0 y_change = 0 #starting position of the enemy enemypos = [] var = 0 enemyarr = [] dotcount = 0 print(len(level), len((level[0]))) for i in range(len(level)): for j in range(len(level[i])): if level[i][j] == 3: enemypos += [[i, j]] enemyarr += [[i, j]] if level[i][j] == 0: dotcount += 1 if level[i][j] == 2: playerpos = [j, i] print(playerpos) print(playerpos) for i in range(len(enemypos)): enemypos[i][0], enemypos[i][ 1] = enemypos[i][1] * 34 + 2, enemypos[i][0] * 34 + 2 pl = Player.Player() e = Enemy.Enemy() m = Map.Map(level) score = 0 while not dead and not win: t = time.time() for event in pygame.event.get(): dead, x_change, y_change = pl.movePlayer(x_change, y_change, event) gameDisplay.fill(white) graph = m.renderMap(display_width, display_height, gameDisplay, level) #check whether position to be moving in is valid score, dead, x_change, y_change = m.checkCollision( score, x_change, y_change, x, y, level) #move player x += x_change y += y_change # print(x, y) # print(playerpos) playerpos[0] += x_change // 34 playerpos[1] += y_change // 34 # print(enemyarr) # e.moveEnemy(enemyarr, graph, playerpos[1], playerpos[0]) pl.renderPlayer(x, y, gameDisplay) e.renderEnemy(enemypos, gameDisplay) pygame.display.update() clock.tick(30) if score == dotcount: win = True pygame.quit() quit()