@@ -126,6 +126,7 @@ def __init__(
126126 super ().__init__ (entity )
127127
128128 self .is_setup = False
129+ self .flee_position = None
129130
130131 def setup (self ,spawned_entity : Actor , spawn_rate : int ):
131132 self .spawned_entity = spawned_entity
@@ -169,23 +170,27 @@ def perform(self) -> None:
169170
170171 # If the distance is less than 5, move away from the player.
171172 if distance < 5 :
172- # Get the direction to the player.
173- direction_x = self .engine .player .x - self .entity .x
174- direction_y = self .engine .player .y - self .entity .y
175-
176- # Normalize the direction.
177- direction_x = max (min (direction_x , 1 ), - 1 )
178- direction_y = max (min (direction_y , 1 ), - 1 )
179-
180- # Round the direction.
181- direction_x = - round (direction_x )
182- direction_y = - round (direction_y )
183-
184- # Move the spawner in the direction of the player.
185- return MovementAction (
186- self .entity , direction_x , direction_y ,
187- ).perform ()
188-
173+ if not self .flee_position :
174+ # Get a flee position, that is more than 5 tiles away from the player, but less than 20 tiles away.
175+ self .flee_position = (
176+ self .entity .x + random .randint (- 5 , 20 ),
177+ self .entity .y + random .randint (- 5 , 20 ),
178+ )
179+
180+ while not self .engine .game_map .in_bounds (* self .flee_position ) or self .engine .game_map .get_blocking_entity_at_location (* self .flee_position ) or self .engine .game_map .tiles ["walkable" ][self .flee_position [0 ], self .flee_position [1 ]] == False :
181+ self .flee_position = (
182+ self .entity .x + random .randint (- 5 , 20 ),
183+ self .entity .y + random .randint (- 5 , 20 ),
184+ )
185+ else :
186+ # Get the direction to the flee position.
187+ self .path = self .get_path_to (self .flee_position [0 ], self .flee_position [1 ])
188+
189+ if self .path :
190+ dest_x , dest_y = self .path .pop (0 )
191+ return MovementAction (
192+ self .entity , dest_x - self .entity .x , dest_y - self .entity .y ,
193+ ).perform ()
189194
190195 # Add 1 to the spawn timer.
191196 self .spawn_timer += 1
0 commit comments