Pygame Pacman - Enemy Random Movement
Ive made a pacman game using python and pygame and I have one of the ghosts that just makes random movements around the maze. Does anyone know if there is a way for me to make the
Solution 1:
A possible improvement could be to keep the direction for a certain distance. Add an attribute for the current direction and number of steps. Keep the direction as long as there are steps left and the enemy doesn't hit a wall:
class Enemy:
def __init__(self):
# [...]
self.dir = (0, 0)
self.steps = 0
def get_random_direction(self):
self.steps -= 1
if self.steps > 0:
next_pos = vec(self.grid_pos.x + self.dir[0], self.grid_pos.y + self.dir[1])
if next_pos not in self.app.walls:
return vec(self.dir)
possible_directions = []
for dir_x, dir_y in [(1, 0), (0, 1), (-1, 0), (0, -1)]:
next_pos = vec(self.grid_pos.x + dir_x, self.grid_pos.y + dir_y)
if next_pos not in self.app.walls:
possible_directions.append((dir_x, dir_y))
self.steps = random.randint(3, 10)
self.dir = random.choice(possible_directions)
return vec(self.dir)
Post a Comment for "Pygame Pacman - Enemy Random Movement"