def update(self, dt): keys = pg.key.get_pressed() # TODO use game key controller self.acc *= 0 self.acc.x = keys[pg.K_d] - keys[pg.K_a] self.acc.y = keys[pg.K_s] - keys[pg.K_w] if self.acc.length() > 1: # prevent faster diagnoal movement self.acc.scale_to_length(1) # laws of motion self.vel += self.acc * self.speed * dt self.vel *= self.friction speed = self.vel.length() if speed < 0.05: self.vel *= 0 if self.lastdir == RIGHT: self.image_state = 'idle_right' else: self.image_state = 'idle_left' else: if self.acc.x > 0: self.image_state = 'run_right' self.lastdir = RIGHT elif self.acc.x < 0: self.image_state = 'run_left' self.lastdir = LEFT self.pos += self.vel # collision detection # the center of the hitbox is always at the sprite's position self.hitbox.centerx = self.pos.x utils.collide_with_walls(self, self.game.walls, 'x') self.hitbox.centery = self.pos.y utils.collide_with_walls(self, self.game.walls, 'y') # the rect(where the image is drawn)'s bottom is # aligned with the hitbox's bottom self.rect.midbottom = self.hitbox.midbottom self.animate(dt) # pathfinding stuff self.grid_pos = utils.pos_to_grid(self.pos, st.CELL_SIZE, st.CELL_OFFSET) try: maze_value = self.game.maze[self.grid_pos[0]][self.grid_pos[1]] except IndexError: maze_value = 1 # store grid pos if not on wall if maze_value == -1: self.last_grid_pos = self.grid_pos
def find_path(self, target, dt): self.counter += dt if self.counter >= self.pathfinding_interval: self.counter = 0 # translate position to grid start = utils.pos_to_grid(self.pos, st.CELL_SIZE, st.CELL_OFFSET) end = target.last_grid_pos # set target to last known player information grid_size = vec(len(self.game.maze), len(self.game.maze[0])) self.path_step = StepPathing(vec(start), vec(end), self.game.maze, grid_size, '*', 1) self.path = self.path_step.get_path()[1:-1] self.path_to_follow = deque([vec(utils.grid_to_pos(p, st.CELL_SIZE, st.CELL_OFFSET)) for p in self.path])
def __init__(self, game, kwargs): super().__init__(game, game.all_sprites, **kwargs) self.game.player = self images = self.game.graphics['knight'] self.images = { 'hit': images[0:1], 'idle_right': images[1:5], 'idle_left': [pg.transform.flip(i, True, False) for i in images[1:5]], 'run_right': images[5:8], 'run_left': [pg.transform.flip(i, True, False) for i in images[5:8]] } #print(self.images) self.image_state = 'idle_right' self.image = self.images[self.image_state][0] self.rect = self.image.get_rect() self.hitbox = pg.Rect(0, 0, 12, 12) self.pos = vec(self.x, self.y) self.hitbox.center = self.pos self.rect.midbottom = self.hitbox.midbottom # physics properties self.acc = vec() self.vel = vec() self.speed = 20 self.friction = 0.8 # animation self.lastdir = RIGHT self.anim_delay = 0.15 # A_star variables self.grid_pos = utils.pos_to_grid(self.pos, st.CELL_SIZE, st.CELL_OFFSET) self.last_grid_pos = self.grid_pos