def move_towards(self, x, y=None): """Move towards the x, y coords, if possible.""" x, y = flatten_args(x, y) dx = x - self.x dy = y - self.y # Normalize the distance to length 1 (preserving direction), then # convert it to a movment direction. if dx > 0: x = 1 elif dx < 0: x = -1 else: x = 0 if dy > 0: y = 1 elif dy < 0: y = -1 else: y = 0 if self.can_move_dir(x, y): self.move(x, y) # If we can't move in the direction we want to, then try to # move vertically or horizontally else: if self.can_move_dir(x, 0): self.move(x, 0) else: self.move(0, y)
def move_to(self, x, y=None): """Move to (x, y), if possible.""" x, y = flatten_args(x, y) self.dirty = True if self.can_move(x, y): self.x = x self.y = y return True else: return False
def move(self, dx, dy=None): """Move dx and dy spaces, if possible.""" dx, dy = flatten_args(dx, dy) self.dirty = True if self.can_move_dir(dx, dy): self.x += dx self.y += dy return True else: return False
def try_move(self, dx, dy=None): """ Try to move dx and dy spaces. If there's a monster in the way, attack instead. """ dx, dy = flatten_args(dx, dy) x = self.x + dx y = self.y + dy # Search for an attackable object. target = None for mon in CS.map.grid[x][y].monsters: target = mon # attack if target found, move otherwise if target is not None: self.attack(target) else: self.move(dx, dy)
def can_move(self, x, y=None): """Can the object move into this location?""" x, y = flatten_args(x, y) can_move = True if x < 0 or y < 0 or x >= CS.map.w or y >= CS.map.h: can_move = False if CS.map.grid[x][y].blocks_movement: can_move = False for mon in CS.map.grid[x][y].monsters: if mon.blocks_movement: can_move = False break if CS.u.x == x and CS.u.y == y: can_move = False return can_move
def move(self, dx, dy=None): """Move by (dx, dy) cells.""" dx, dy = flatten_args(dx, dy) Network.request('m', (dx, dy))
def can_move_dir(self, x, y=None): """Can the character move in this direction?""" x, y = flatten_args(x, y) return self.can_move(self.x + x, self.y + y)