def get_actions(state): actions = [] pos = find_empty_position(state.matrix) if pos.x - 1 >= 0: actions.append( Action(swap_values, matrix=state.matrix, first_pos=pos, second_pos=Position(pos.x - 1, pos.y))) if pos.x + 1 < len(state.matrix): actions.append( Action(swap_values, matrix=state.matrix, first_pos=pos, second_pos=Position(pos.x + 1, pos.y))) if pos.y - 1 >= 0: actions.append( Action(swap_values, matrix=state.matrix, first_pos=pos, second_pos=Position(pos.x, pos.y - 1))) if pos.y + 1 < len(state.matrix[0]): actions.append( Action(swap_values, matrix=state.matrix, first_pos=pos, second_pos=Position(pos.x, pos.y + 1))) return actions
def is_valid_move(self, move: Move, rubrics): """given a move and the rubrics, returns True if the move is valid for this piece or throws exception""" # rook can move in straight lines: either up, down, left or right. # it cant jump over other pieces. source_x, source_y = move.from_pos.x, move.from_pos.y dest_x, dest_y = move.to_pos.x, move.to_pos.y if source_x != dest_x and source_y != dest_y: raise InvalidMoveException("rook cant move on both axes at once") # calculate the actual path taken to ensure we're not jumping over other pieces, which is illegal path = [] if dest_x > source_x: # move right for i in range(source_x + 1, dest_x, 1): path.append(Position(i, source_y)) elif dest_x < source_x: # move left for i in range(source_x - 1, dest_x, -1): path.append(Position(i, source_y)) elif dest_y > source_y: # move up for i in range(source_y + 1, dest_y, 1): path.append(Position(dest_x, i)) else: # move down for i in range(source_y - 1, dest_y, -1): path.append(Position(dest_x, i)) # ensure there's nothing in our path: for rubric in path: if rubrics[rubric.x][rubric.y].piece_type != PieceType.PLACEHOLDER: raise InvalidMoveException( "cant jump over piece in position %s,%s" % (rubric.x, rubric.y)) return True
class Robot: def __init__(self, x, y, theta, std_actuators): self._std_actuators = std_actuators self._position = Position(x, y, theta) self._noisy_position = Position(x, y, theta) self._delta_w = .3 self._delta_v = 1 self._w = 0 self._v = 0 def move(self, direction): """ Get the robot's direction from key arrows and move the robot accordingly """ self._v = self._delta_v if direction else -self._delta_v self._position.predict_position(self._v, self._w) self._noisy_position.predict_position(self._v, self._w, self._std_actuators) def change_orientation(self, orientation): """ Get the robot's angular velocity from key arrows and orient the robot accordingly """ delta_w = self._delta_w if orientation else -self._delta_w self._w = self._w + delta_w
def initialize(self, height, width, treasure_number, traps, start_pos): """ Initializes DungeonMap param: height (int) height of the map param: width (int) width of the map param: treasure_number (int) number of treasures on map param: traps (iterateble) traps to put on map param: start_pos (Position) player starting position on map """ try: is_input_valid = width * height > treasure_number + len(traps) except TypeError as error: raise DungeonMapInitializationError( "Incorrect parameter type in " "DungeonMap initialize. \n {}".fromat(str(error))) else: if not is_input_valid: try: raise DungeonMapInitializationError( "Incorrect parameters in " "DungeonMap initialize. Map can't fit all of the cells." ) #made because try daoesn't work without exept except DungeonMapInitializationError: raise self.width = width self.height = height self.cells = [[empty_cell.legend for i in range(height)] for j in range(width)] logger.debug("empty map generated") try: self.cells[start_pos.x][start_pos.y] = entrance_cell.legend except IndexError: raise DungeonMapInitializationError( "Incorrect parameters in " "DungeonMap initialize. Strating position is out of DungeonMap " "boundaries") while treasure_number > 0: pos = Position.generate_random_position(width, height) if self.cell(pos) == empty_cell.legend: self.cells[pos.x][pos.y] = treasure_cell.legend treasure_number -= 1 logger.debug("treasures generated") while traps: pos = Position.generate_random_position(width, height) if self.cell(pos) == empty_cell.legend: self.cells[pos.x][pos.y] = traps.pop() logger.debug("traps generated")
def __init__(self, x, y, theta, std_actuators): self._std_actuators = std_actuators self._position = Position(x, y, theta) self._noisy_position = Position(x, y, theta) self._delta_w = .3 self._delta_v = 1 self._w = 0 self._v = 0
def setUp(self): self.dungeonGame = DungeonGame() #initializing map with 2 cells DungeonGame.dmap.initialize(2, 1, 0, [], Position(0, 0)) #setting enemy and player position to be the same DungeonGame.player.position = Position(0, 0) DungeonGame.enemy.position = Position(0, 0)
def list_next_potential_positions(self, rubrics): """returns a list of potential and valid next positions for this piece, ignoring Check-semantics""" valid_positions = [] x = self.position.x y = self.position.y coordinates = [(x + 1, y), (x - 1, y), (x, y - 1), (x, y + 1), (x + 1, y + 1), (x - 1, y + 1), (x + 1, y - 1), (x - 1, y - 1)] positions_on_board = [] # filter out off-board positions (for pieces on the edge of the board) for coordinate in coordinates: try: positions_on_board.append( Position(coordinate[0], coordinate[1])) except Position.InvalidPositionError: pass # filter in vacant positions and positions belonging to the other side for position in positions_on_board: target_piece = rubrics[position.x][position.y] if target_piece.piece_type == PieceType.PLACEHOLDER: valid_positions.append(target_piece.position) elif target_piece.color != self.color: valid_positions.append(target_piece.position) return valid_positions
def __init__(self): self._rubrics = [[PlaceHolder(Position(y, x)) for x in range(8)] for y in range(8)] self._pieces = {PieceColor.WHITE: {}, PieceColor.BLACK: {}} self._removed_pieces = {PieceColor.WHITE: {}, PieceColor.BLACK: {}} self._current_side_color = PieceColor.WHITE self._other_side_color = PieceColor.BLACK
def __init__(self, map_name="level1", spawn_name="spawn1"): pygame.init() self.FPS = 60 self.BG_COLOR = pygame.Color("black") self.GAME_AREA_POS = Position(96, 32) self.GAME_AREA_SIZE = (15, 15) self.GAME_AREA_SIZE_PIXELS = (self.GAME_AREA_SIZE[0] * 16, self.GAME_AREA_SIZE[1] * 16) self.screen = pygame.display.set_mode( (self.GAME_AREA_SIZE_PIXELS[0] + self.GAME_AREA_POS.x, self.GAME_AREA_SIZE_PIXELS[1] + self.GAME_AREA_POS.y), pygame.SCALED) self.clock = pygame.time.Clock() self.hero = Hero() self.wait = False # Wait for something to end, stop character updates self.actions = [] # Map data self.map_surface = pygame.Surface(self.GAME_AREA_SIZE_PIXELS) self.tmx_data = None self.map_data = None self.map_layer = None self.map_sprite_group = None self.spawns = None self.impassables = None self.doors = None self.load_map(map_name, spawn_name)
def __init__(self, x, y, color): self._alife = True self._color = color self._direction = ( Vector(1, 1) if self._color is TOP_COLOR else Vector(-1, 1) ) self._pos = Position(x, y) self._or_pos = Position(x, y) self._moves_n = 0 self._moves = None self.init_moves() Piece.count += 1 self._id = Piece.count Piece.pieces[color].append(self)
def intepret(self, code): stat = FractalStat(position=Position(0.0, 0.0), angle=0.0) self.drawer.move_to(stat.position) for ch in code: try: self.action_map[ch](stat) except KeyError: pass self.drawer.draw_end()
def list_to_chunks(l): chunks = {} for item in l: pos = Position(item[0], item[1]) chunk = Chunk.from_string(item[2]) chunks[pos] = chunk return chunks
def respawn_enemy(self): """ Respawns enemy at random not occupied by Player cell. """ DungeonMap.enemy = choice(enemies_list) enemy_position = Position.generate_random_position(DungeonGame.dmap.width,\ DungeonGame.dmap.height) while enemy_position == DungeonGame.player.position: enemy_position = Position.generate_random_position(DungeonGame.dmap.width,\ DungeonGame.dmap.height) DungeonMap.enemy.position = enemy_position logger.debug("enemy spawned at {},{}".format(DungeonGame.enemy.position.x,\ DungeonGame.enemy.position.y))
def board_str(self): """Return board representation.""" board = BOARD_FORMAT for x, y in Position.iter(8, 8): piece = self._board[x][y] r = " - " if (x + y) % 2 else " " board = board.replace("%s %s" % (x, y), piece.repr() if piece else r) return board
def move(self, pos, npos): """Move piece at pos to npos if possible.""" pos = Position(*pos) npos = Position(*npos) # Check square contains piece of right color piece = self.get(pos) if piece is None: raise InvalidMove("No piece on that position") elif piece.color is not self._playing_color: raise InvalidMove("You must move piece of your color") # Check whether move is possible move = piece.get_move(npos - pos) move.check(self) action_batch = move.create_batch(self) self._apply(action_batch) self.change_player()
def write(self, char): with self.chunkpool as pool: chunk = pool.get( Position(chunkx(self.cursorx), chunky(self.cursory))) if chunk: chunk.set(inchunkx(self.cursorx), inchunky(self.cursory), char) pool.save_changes_delayed() self.move_cursor(1, 0, False)
def delete(self): with self.chunkpool as pool: chunk = pool.get( Position(chunkx(self.cursorx - 1), chunky(self.cursory))) if chunk: chunk.delete(inchunkx(self.cursorx - 1), inchunky(self.cursory)) pool.save_changes_delayed() self.move_cursor(-1, 0, False)
def initialize(self, height, width, treasure_number, traps, start_pos): """ Initializes DungeonMap param: height (int) height of the map param: width (int) width of the map param: treasure_number (int) number of treasures on map param: traps (iterateble) traps to put on map param: start_pos (Position) player starting position on map """ if width * height < treasure_number + len(traps) + 1: logger.debug("Incorrect parameters in DungeonMap initialize." " Map can't fit all of the cells") return self.width = width self.height = height self.cells = [[empty_cell.legend for i in range(height)] for j in range(width)] logger.debug("empty map generated") self.cells[start_pos.x][start_pos.y] = entrance_cell.legend while treasure_number > 0: pos = Position.generate_random_position(width, height) if self.cell(pos) == empty_cell.legend: self.cells[pos.x][pos.y] = treasure_cell.legend treasure_number -= 1 logger.debug("treasures generated") while traps: pos = Position.generate_random_position(width, height) if self.cell(pos) == empty_cell.legend: self.cells[pos.x][pos.y] = traps.pop() logger.debug("traps generated")
def set_pieces(self, board_layout_filename): """parse the given file into the state of the board""" def get_ctor(piece_type_str: str): """gets the ctor function for the given piece type string""" if piece_type_str == "PAWN": return Pawn if piece_type_str == "ROOK": return Rook if piece_type_str == "HORSE": return Horse if piece_type_str == "BISHOP": return Bishop if piece_type_str == "KING": return King if piece_type_str == "QUEEN": return Queen def get_instance(klass, *args): return klass(*args) board_json = json.loads(open(board_layout_filename).read()) white_pieces = self._pieces[PieceColor.WHITE] black_pieces = self._pieces[PieceColor.BLACK] for piece_json in board_json['WHITE']: x, y, name, piece_type = int(piece_json['x']), int( piece_json['y']), piece_json['name'], piece_json['piece_type'] ctor = get_ctor(piece_type) piece = get_instance(get_ctor(piece_type), PieceColor.WHITE, Position(x, y), name) white_pieces[name] = piece self._rubrics[x][y] = piece for piece_json in board_json['BLACK']: x, y, name, piece_type = int(piece_json['x']), int( piece_json['y']), piece_json['name'], piece_json['piece_type'] piece = get_ctor(piece_type)(PieceColor.BLACK, Position(x, y), name) black_pieces[name] = piece self._rubrics[x][y] = piece
class Character(): representation = None position = None size = None def __init__(self, x, y, width, height): self.position = Position(x, y) self.size = Size(width, height) def update_position(self, x, y): self.position.x = x self.position.y = y self.representation.pos = self.position.get_tuple()
def estimate_position(self): """ Compute the barycenter of all the particles Return its position and the covariance in x and y """ N = self._nb_of_particles x_array = [p._position._x for p in self._particles] y_array = [p._position._y for p in self._particles] covariance = np.cov(x_array,y_array) return(Position(np.sum(x_array)/N,np.sum(y_array)/N,0),covariance)
def visible_chunk_coords(self): coords = [] xstart = chunkx(self.worldx) - self.chunkpreload ystart = chunky(self.worldy) - self.chunkpreload xend = xstart + chunkx(self.width) + 2 + 2 * self.chunkpreload yend = ystart + chunky(self.height) + 2 + 2 * self.chunkpreload for x in range(xstart, xend): for y in range(ystart, yend): coords.append(Position(x, y)) return coords
def is_valid_move(self, move: Move, rubrics): """given a move and the rubrics, returns True if the move is valid for this piece or throws exception""" # bishop can move in one of the four diagonals # it cant jump over other pieces. source_x, source_y = move.from_pos.x, move.from_pos.y dest_x, dest_y = move.to_pos.x, move.to_pos.y if abs(dest_x - source_x) != abs(dest_y - source_y): raise InvalidMoveException("bishop can only move diagonally") # calculate the actual path taken to ensure we're not jumping over other pieces, which is illegal path = [] distance = abs(dest_x - source_x + 1) if dest_x > source_x: # moving right if dest_y > source_y: # moving up for i in range(1, distance): path.append(Position(source_x + i, source_y + i)) else: # moving down for i in range(1, distance): path.append(Position(source_x + i, source_y - i)) else: # moving left if dest_y > source_y: # moving up for i in range(1, distance): path.append(Position(source_x - i, source_y + i)) else: # moving down for i in range(1, distance): path.append(Position(source_x - i, source_y - i)) # ensure there's nothing in our path: for rubric in path: if rubrics[rubric.x][rubric.y].piece_type != PieceType.PLACEHOLDER: raise InvalidMoveException( "cant jump over piece in position %s,%s" % (rubric.x, rubric.y)) return True
def handle_request_chunks(self, coords): diffs = {} coords = [Position(coor[0], coor[1]) for coor in coords] with self.pool as pool: pool.load_list(coords) for pos in coords: chunk = pool.get(pos) diff = chunk.as_diff() diffs[pos] = diff self.loaded_chunks.add(pos) ddiffs = jsonify_diffs(diffs) message = {"type": "apply-changes", "data": ddiffs} self.sendMessage(json.dumps(message))
def draw(self): with self.chunkpool as pool: for x in range(chunkx(self.width) + 2): # +2, not +1, or there will be empty gaps for y in range(chunky(self.height) + 2): # in the bottom and right borders pos = Position(x + chunkx(self.worldx), y + chunky(self.worldy)) chunk = pool.get(pos) if chunk: self.draw_chunk_to(x * CHUNK_WIDTH, y * CHUNK_HEIGHT, chunk, (pos.x + pos.y) % 2) else: self.draw_empty_to(x * CHUNK_WIDTH, y * CHUNK_HEIGHT) self.update_cursor() self.noutrefresh()
def load(self, path): print('Loading \'' + path + '\'') with open(path, newline='\n') as csvfile: reader = csv.reader(csvfile, delimiter=' ', quotechar='|') rows = list(reader) self.i = rows[0][0] self.nbVehicles = int(rows[1][0]) self.nbPoints = int(rows[2][0]) self.warehouse = Position(int(rows[3][0]), int(rows[3][1])) for i in range(4, 4 + self.nbVehicles): self.vehicles.append( Vehicle(float(rows[i][0]), float(rows[i][1]), self.warehouse)) for i in range(4 + self.nbVehicles, 4 + self.nbVehicles + self.nbPoints): self.points.append( Point(float(rows[i][0]), float(rows[i][1]), float(rows[i][2]), float(rows[i][3]), float(rows[i][4])))
def init_new_game(self): """ Initializes new games """ logger.info(text.new_game_start) input() logger.info(text.administration) input() logger.info(text.enter_proficiency_prompt) user_input = input().lower() if user_input in DungeonGame.player.proficiencies: DungeonGame.player.proficiency = user_input else: DungeonGame.player.proficiency = "none" logger.info(text.enter_dungeon_width_prompt) width = input_number_from_boundaries(DungeonGame.MIN_MAP_WIDTH,\ DungeonGame.MAX_MAP_WIDTH) logger.info(text.enter_dungeon_height_prompt) height = input_number_from_boundaries(DungeonGame.MIN_MAP_HEIGHT,\ DungeonGame.MAX_MAP_HEIGHT) size = width * height number_of_treasures = max (size * DungeonGame.treasure_rarity,\ DungeonGame.treasure_to_win) number_of_traps = min (size - number_of_treasures - 1, size * DungeonGame.trap_rarity) traps = Trap.generate_traps(number_of_traps) starting_position = Position.generate_random_position(width, height) DungeonGame.dmap.initialize(height, width, number_of_treasures, traps, starting_position) DungeonGame.player.health = DungeonGame.default_health DungeonGame.player.bag = 0 DungeonGame.player.position = starting_position DungeonGame.player.discovered_map.initialize_discovered_map(height, width,\ starting_position) self.respawn_enemy()
def draw_fractal(axiom='X', angle=angle, length=length, num_iters=5): stack = [] sticks, num_iters = create_turtle() screen = sticks.getscreen() if num_iters>=8: length = 2 sticks._tracer(0) elif num_iters >= 6: length = 7 sticks._delay(0) else: length = 20 sticks._delay(2) # sticks._tracer(0) sticks.hideturtle() sticks.left(90) generated_string = create_lsystem(axiom=axiom, num_iters=num_iters) print('Generated string: {}'.format(generated_string)) for i, char in enumerate(generated_string): if char == 'F': sticks.forward(length) elif char == '+': sticks.left(angle) elif char == '-': sticks.right(angle) elif char == '[': position = sticks.pos() state = Position(position[0], position[1], sticks.heading()) stack.append(state) elif char == ']': state = stack.pop() position = (state.x, state.y) ang = state.angle sticks.up() sticks.goto(position) sticks.setheading(ang) sticks.down() screen.exitonclick()
def _print_chunks(self): """ Meant for debugging. """ if self._chunks: minx, maxx, miny, maxy = self._get_min_max() sizex, sizey = maxx - minx + 1, maxy - miny + 1 print("┌" + "─"*sizex*2 + "┐") for y in range(miny, maxy + 1): line = [] for x in range(minx, maxx + 1): chunk = self._chunks.get(Position(x, y)) if chunk: if chunk.empty(): line.append("()") else: line.append("[]") else: line.append(" ") line = "".join(line) print("│" + line + "│") print("└" + "─"*sizex*2 + "┘")
def process(self, target, vertices): """ PURPOSE calculate mouse pointer position, on Target monitor, from Target monitor location on `camera` sensor PARAMETERS * vertices : vertices of Target monitor on `camera` sensor (a `Quadrilateral` instance) RETURNS * nothing NOTES * Upon (successful) completion of this procedure, `self.position` ia the `Position` instance the mouse pointer should be (moved to) on the Target monitor. """ self.target = target self.vertices = vertices self.position = None vertices = numpy.float32([ vertices.upperleft, vertices.upperright, vertices.lowerleft, vertices.lowerright ]) # vertices orderd as expected by cv2.getPerspectiveTransform transform = cv2.getPerspectiveTransform(vertices, self.monitor) xy = cv2.perspectiveTransform(self.center[None, None, :], transform) self.position = Position(x=int(xy[0, 0, 0]), y=int(xy[0, 0, 1])) self.log.debug(' computed position is: %s', str(self.position))