def test_1(): map = Map("ressource/map01.txt") assert len(map.start) == 1 assert len(map.goal) == 1 toto = Hero(map) toto.position = map.start[0] assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('left') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('up') # outside the map assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('right') # in the wall assert toto.position.getx == 0 assert toto.position.gety == 0 toto.move('down') # OK assert toto.position.getx == 1 # new x assert toto.position.gety == 0 map.items.append(Position(5, 5)) # put an Item in the list len_items = len(map.items) toto.position = Position(4, 5) # put the hero near the item toto.move('down') # move onto the new items print('coucou {}'.format(toto.position)) assert len_items == len( map.items) + 1 # the item has been removed from the list
def load_structure(self): # e = Event() # switched = e.setval # switched = Event.setval print(self.switched) with open("data/levels/" + self.file) as levels: for line in levels: self._coord_let.append(line.strip('\n')) for i in range(15): for k, v in enumerate(self._coord_let[i]): if v == constants.WALL_CHAR: self.coords_wall.append( (k * self.switched, i * self.switched)) elif v == constants.ROAD_CHAR: self.coords_road.append( Position(k * self.switched, i * self.switched)) elif v == constants.START_CHAR: self._coords_start.append( Position(k * self.switched, i * self.switched)) self.coords_road.append( Position(k * self.switched, i * self.switched)) elif v == constants.FINNISH_CHAR: self.coords_road.append( Position(k * self.switched, i * self.switched)) self.coords_finnish.append( Position(k * self.switched, i * self.switched)) print(self.switched)
def show(): # get current_user location to show at center of map post_data = request.get_json() print(post_data) user = User.get_or_none(id=post_data.get('id')) current_location = Position.get(Position.user == user.id) locations = [] # positions = (Position.select() # .where( # Position.user!=user.id, # Position.updated_at+datetime.timedelta(minutes=180) > datetime.datetime.now() # )) positions = (Position.select().where( Position.updated_at + datetime.timedelta(minutes=180) > datetime.datetime.now())) for position in positions: locations.append({ 'user': position.user.username, 'position': { 'lat': float(position.lat), 'lng': float(position.lng) } }) return jsonify({ 'ok': True, 'locations': locations, 'current_user': user.username, 'current_location_lat': float(current_location.lat), 'current_location_lng': float(current_location.lng) })
def play_game(args): assert isinstance(args.field_paths, list) or isinstance( args.field_paths, str) if isinstance(args.field_paths, str): args.field_paths = [args.field_paths] fields = read_fields(args.field_paths) if args.players is None: args.players = int(input('How many players will play? — ')) positions = [] if args.start_positions is not None: for position in args.start_positions: x, y = map(int, position[1:-1].split(',')) positions.append(Position(x, y)) if not args.random_positions: if args.players - len(positions) > 0: print('Field size: {}x{}'.format(fields[0].x_size, fields[0].y_size)) for i in range(len(positions), args.players): position = input( 'Start position as x,y or "random" for Player {}: '.format( i)) if position == 'random': positions.append(random_position_on_field(fields[0])) else: x, y = position.split(',') positions.append(Position(int(x), int(y))) game = Game(fields, args.players, positions) game.start_game()
def bypass_field(game_field, bypass: Bypass): for x in range(game_field.x_size): for y in range(game_field.y_size): exit_is_reachable, bypass = player_bypass_from(game_field, bypass, Position(x, y)) if not exit_is_reachable: return Position(x, y) bypass.reset_except_exit_ways() return None
def start(self): """This function starts the game, moves the player to a direction inputed if authorized, calls the exit function, catches items.""" self.running = True while self.running: initial_position = copy(self.player.position) print("\nYour position is : " + str(initial_position)) direction = str( input("Where do you want to go ? \n Type 'u' 'd' 'l' ou 'r' ") ) self.player.position.update(direction) print("Objects are here : " + str(self.items_positions)) if self.player.position == Position(14, 14): self.exit() else: if self.player.position in self.items_positions: self.player.bag += 1 print( "Well done, you go " + str(self.player.bag) + " object(s)." ) else: pass if self.player.position in self.labyrinth._paths: print("\nYou're one step ahead !") else: print("\nThis step is forbidden !") self.player.position = initial_position print("Your position is now : " + str(self.player.position))
def start(self): self.running = True while self.running: position_initiale = copy(self.player.position) print("\nVotre position est : " + str(position_initiale)) direction = str( input("Où voulez-vous aller ? \n Tapez 'u' 'd' 'l' ou 'r' ")) self.player.position.update(direction) print("Les objets sont ici : " + str(self.items_positions)) #Voyons si nous sommes sur la case de sortie if self.player.position == Position(14, 14): self.exit() else: # Voyons s'il y a un objet sur cette position if self.player.position in self.items_positions: self.player.bag += 1 print("Bravo, vous avez " + str(self.player.bag) + " objet(s).") else: pass # Voyons si la direction invite à une position valide if self.player.position in self.labyrinth._paths: print("\nVous avez avancé d'une case !") else: print("\nCe chemin n'est pas autorisé !") self.player.position = position_initiale print("Votre position est maintenant : " + str(self.player.position))
def generate_walls(game_field): player = Player() current_position = Position(0, 0) game_field.add_player_at(player, current_position) visited = [[False for _ in range(game_field.y_size)] for _ in range(game_field.x_size)] while True: visited[current_position.x][current_position.y] = True random_direction = calc_random_direction() new_position = current_position + random_direction if not game_field.field.is_out_of_field(new_position) and \ not visited[new_position.x][new_position.y]: game_field.field.remove_wall_at(current_position, random_direction) game_field.player_go_to(player, new_position) current_position = new_position continue if game_field.field.has_wall_at(current_position, random_direction): game_field.field.remove_wall_at(current_position, random_direction) there_are_unvisited_positions = False for direction in Direction: new_position = current_position + direction if not game_field.field.is_out_of_field(new_position) and \ not visited[new_position.x][new_position.y]: there_are_unvisited_positions = True break if not there_are_unvisited_positions: current_position = try_place_player_somewhere( game_field, player, visited) if current_position is None: break
def __init__(self, duration: int, coords: tuple): assert duration >= 0 assert isinstance(coords, tuple) and len(coords) == 3 super().__init__() self.duration = duration self.destination_field_id = coords[0] self.destination_position = Position(coords[1], coords[2])
def update(self): """ The same loop as the console display : loop on the x and y and display the right stripe on each position. Args: Returns: """ self.screen.blit(self.hero.hero_img, self.hero.rect) item = 0 for x in range(NB_LINES + 1): for y in range(NB_COLS + 1): myposx = x * SPRITE_WIDTH myposy = y * SPRITE_HEIGTH mypos = Position(x, y) if self.map.is_path_position(mypos): if self.hero.position == mypos: self.screen.blit(self.hero.hero_img, self.hero.rect) elif self.map.get_goal == mypos: self.screen.blit(self.goal_img, (myposx, myposy)) elif self.map.get_start == mypos: self.screen.blit(self.start_img, (myposx, myposy)) elif mypos in self.map.items: self.screen.blit(self.items[item], (myposx, myposy)) item += 1 else: self.screen.blit(self.path_img, (myposx, myposy)) else: self.screen.blit(self.wall_img, (myposx, myposy)) pygame.display.update()
def __repr__(self): """ print the map ! loop on x,y and at each position we look for the model (wall, path, Item Hero...) and add it onto the current line Args: Returns: """ clear() for x in range(NB_LINES + 1): line = '' for y in range(NB_COLS + 1): mypos = Position(x, y) # test si chemin --> si ok peut aussi etre le debut ou la sortie ou un Item if self.map.is_path_position(mypos): if self.hero.position == mypos: line += MC_GYVER elif self.map.get_goal == mypos: line += 'G' elif self.map.get_start == mypos: line += 'S' elif mypos in self.map.items: line += 'I' else: line += ' ' else: line += 'W' self.display_line(line) return '\n'
def generate_sym_field(field, teleport_sleep_count, unique_cells): empty_sym = Empty().to_symbol() empty_wall_sym = ' ' sym_field = [[] for _ in range(field.x_size * 2 - 1)] for i in range(field.x_size * 2 - 1): for j in range(field.y_size * 2 - 1): cell_position = Position(i // 2, j // 2) cell = field[cell_position] if i % 2 == 0: if j % 2 == 0: cell_symbol = cell.to_symbol() if isinstance(cell, Teleport) or isinstance(cell, Sleep): teleport_sleep_count += 1 cell_symbol = str(teleport_sleep_count) sym_field[i].append(cell_symbol) unique_cells[cell_symbol] = deepcopy(cell) else: wall_sym = RIGHT.to_symbol() if field.has_wall_at( cell_position, RIGHT) else empty_wall_sym sym_field[i].append(wall_sym) else: if j % 2 == 0: cell_sym = DOWN.to_symbol() if field.has_wall_at( cell_position, DOWN) else empty_sym sym_field[i].append(cell_sym) else: sym_field[i].append(empty_wall_sym) return sym_field, teleport_sleep_count
def __init__(self, board, init_position): super().__init__() self.image = board.py.images["path"] self.rect = self.image.get_rect() self.rect.topleft = init_position.position[1], init_position.position[0] self.position = Position(self.rect.topleft[0], self.rect.topleft[1]) self.order = None
def create(): lat = request.form.get('lat') lng = request.form.get('lng') position = Position.get_or_none(Position.user == current_user.id) if position == None: Position.create(user=current_user.id, lat=lat, lng=lng) return jsonify({'ok': True, 'message': 'Position has been saved'}) else: position.lat = lat position.lng = lng if not position.save(): resp = jsonify({'message': 'Unable to save position'}) resp.status_code = 400 return resp return jsonify({'ok': True, 'message': 'Position has been saved'})
def new(): post_data = request.get_json() lat = post_data.get('lat') lng = post_data.get('lng') user = User.get_or_none(id=post_data.get('id')) position = Position.get_or_none(Position.user == user.id) if position == None: Position.create(user=user.id, lat=lat, lng=lng) return jsonify({'ok': True, 'message': 'Position has been saved'}) else: position.lat = lat position.lng = lng if not position.save(): resp = jsonify({'message': 'Unable to save position'}) resp.status_code = 400 return resp return jsonify({'ok': True, 'message': 'Position has been saved'})
def catch_item(self): if self.position.xy in self.jeu.labyrinth.item_positions: self.bag += 1 print("Bravo, vous avez " + str(self.bag) + " objet(s).") print(self.jeu.labyrinth.item_positions) item = self.jeu.labyrinth.item_positions[self.position.xy] item.status = "catched" item.position = Position(self.bag - 1, 15) del self.jeu.labyrinth.item_positions[self.position.xy] self.jeu.labyrinth.item_positions[(self.bag - 1, 15)] = item
def __init__(self, start_position=Position()): global total_ids self.id = total_ids total_ids += 1 self.inventory = Inventory() self.sleep_inventories = [] self.stun = 0 self.sleep_times = [] self.field_id = [0] self.start_position = start_position
def catch_item(self): """This function verifies if there is an object on the position of the player, changes its status and position if so, and deletes it from the objects list.""" if self.position.xy in self.jeu.labyrinth.item_positions: print("Well done, you got " + str(self.bag) + " object(s).") self.bag += 1 self.jeu.labyrinth.item_positions[self.position.xy].status = "catched" self.jeu.labyrinth.item_positions[self.position.xy].position = Position( self.bag, 15) del self.jeu.labyrinth.item_positions[self.position.xy]
def load_from_file(self): """load datafile containing the shape of the map""" with open(self.filename) as file: for y, line in enumerate(file): # y axis for x, col in enumerate(line): # x axis if col == constants.PATH_CHAR: # if character correspond to PATH_CHAR constant defined in settings # add a Position instance in the attribute paths self.paths.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE)) elif col == constants.START_GAME: # if character correspond to START_GAME constant defined in settings # add a Position instance in the attribute start # and add a Position instance in the attribute path # cause you always can come back by this position self.paths.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE)) self.start.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE)) elif col == constants.GOAL_CHAR: # if character correspond to GOAL_CHAR constant defined in settings # add a Position instance in the attribute goal # and add a Position instance in the attribute path # cause you always can path again by this position self.paths.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE)) self.goal.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE)) elif col == constants.WALL_CHAR: # if character correspond to WALL_CHAR constant defined in settings # add a Position instance in the attribute walls self.walls.append\ (Position(x*constants.SPRITES_SIZE, y*constants.SPRITES_SIZE))
def run(self): stat, vac_skills = self.get_st.get_statistics() Position.save_positions(stat.positions) Statistic.save_statistics(stat.skill_percent, stat.skills) Way.save_ways(stat.ways) Vacancy.save_vacancies(stat.total_info, vac_skills) clear_cached_data() stat.positions = {} stat.ways = {} stat.skill_percent = {} stat.skills = {} stat.total_info = [] iloop = asyncio.new_event_loop() asyncio.set_event_loop(iloop) tasks = [ Task(self.task_id).complete_task(), Statistic.delete_stats_older_than_month(), Vacancy.delete_vacancies_older_than_month(), Way.delete_ways_older_than_month(), Position.delete_positions_older_than_month() ] iloop.run_until_complete(asyncio.wait(tasks))
def define_path(self, filename): """This function creates the labyrinth's path from the text file map.txt.""" with open(filename) as file: content = file.readlines() for num_line, line in enumerate(content): for num_c, c in enumerate(line): if c == "P": self.paths.append(Position(num_c, num_line)) elif c == "D": self.start = Position(num_c, num_line) elif c == "A": self.end = Position(num_c, num_line) elif c == "-": self.walls.append(Position(num_c, num_line)) elif c == "#": self.bar.append(Position(num_c, num_line)) self.width = num_c + 1 self.length = num_line + 1 self.paths.append(self.end) self.paths.append(self.start)
def show(): # get current_user location to show at center of map current_location = Position.get(Position.user == current_user.id) locations = [] positions = (Position.select().where( Position.user != current_user.id, Position.updated_at + datetime.timedelta(minutes=15) > datetime.datetime.now())) for position in positions: locations.append({ 'user': position.user.username, 'position': { 'lat': float(position.lat), 'lng': float(position.lng) } }) return jsonify({ 'ok': True, 'locations': locations, 'current_user': current_user.username, 'current_location_lat': float(current_location.lat), 'current_location_lng': float(current_location.lng) })
def try_place_player_somewhere(game_field, player, visited): for x in range(game_field.x_size): for y in range(game_field.y_size): if visited[x][y]: current_position = Position(x, y) for direction in Direction: new_position = current_position + direction if not game_field.field.is_out_of_field(new_position) and \ not visited[new_position.x][new_position.y]: game_field.field.remove_wall_at( current_position, direction) game_field.player_go_to(player, new_position) return new_position return None
def display_map(self, map_size, paths): """ display walls and pathes arg : Map_size (x and y), paths positions""" for i in range(map_size[0] + 1): for j in range(map_size[1] + 1): if Position(i, j) not in paths: self.blit( self.images["wall"], (j * const.SIZE_OF_SPRITE, i * const.SIZE_OF_SPRITE)) else: self.blit( self.images["path"], (j * const.SIZE_OF_SPRITE, i * const.SIZE_OF_SPRITE))
def setUp(self): """Define test variables and initialize DB""" self.client = application.test_client self.position_json = { "latitudeE7": 488182212, "altitude": 88, "longitudeE7": 22446445, "timestampMs": "1562563557125", "verticalAccuracy": 6, "accuracy": 14 } self.position: Position = Position(**self.position_json) with application.app_context(): db.create_all()
def define_path(self, filename): """ Cette fonction map les chemins et les positions du labyrinthe en fonction d'un fichier texte. """ with open(filename) as file: content = file.readlines() for num_line, line in enumerate(content): for num_c, c in enumerate(line): if c == "P": self.paths.append(Position(num_c, num_line)) elif c == "D": self.start = Position(num_c, num_line) elif c == "A": self.end = Position(num_c, num_line) elif c == "-": self.walls.append(Position(num_c, num_line)) elif c == "#": self.bar.append(Position(num_c, num_line)) self.width = num_c + 1 self.length = num_line + 1 self.paths.append(self.end) self.paths.append(self.start) self.random_positions = random.sample(self.paths[:-2], 3)
def check_field(game_field): exit_found, bypass = find_exit(game_field) if not exit_found: return Position(0, 0) game_field.reset() reset_player_total_ids() bad_position = bypass_field(game_field, bypass) game_field.reset() reset_player_total_ids() if bad_position: raise LookupError(bad_position)
def fix_bad_rubber_room(game_field): try: check_field(game_field) except LookupError as error: position = error.args[0] _, bypass = find_exit(game_field, start_position=position) for x in range(game_field.x_size): for y in range(game_field.y_size): current_position = Position(x, y) if bypass[current_position].visited and isinstance( game_field.field[current_position], RubberRoom): game_field.field.put_cell_at(current_position, Empty()) return True raise Exception('Field has no exit way by some position') else: return False
def find_exit(game_field): bypass = Bypass(game_field.x_size, game_field.y_size) queue = deque() start_position = Position(0, 0) add_player(game_field, queue, start_position) while queue: current_position, current_cell = DFS(game_field, queue, bypass) if isinstance(current_cell, Exit): exit_position = current_position mark_exit_way(bypass, exit_position) return exit_position, bypass return False, bypass
def place_componants(self): """ Instanciation of syringe's componants : They shouldn't be outside a path neither then at the same place of an other or start and goal postition """ places = [] # used positions checking list for elt in self.objects: while 1: randrange_x = randrange(0, constants.LAST_POS, constants.SPRITES_SIZE) randrange_y = randrange(0, constants.LAST_POS, constants.SPRITES_SIZE) place = Position(randrange_x, randrange_y) if place in self.mase: # check in available sprites (paths) if place not in self.mase.start: # check out of start sprite if place not in self.mase.goal: # check out of goal sprite if place not in places: # check not already used sprite break places.append(place) infos = [place, False] self.componants[elt] = infos