MCPcopy Create free account
hub / github.com/TheAlgorithms/Python / get_surrounding_prey

Method get_surrounding_prey

cellular_automata/wa_tor.py:215–255  ·  view source on GitHub ↗

Returns all the prey entities around (N, S, E, W) a predator entity. Subtly different to the `move_and_reproduce`. >>> wt = WaTor(WIDTH, HEIGHT) >>> wt.set_planet([ ... [None, Entity(True, (0, 1)), None], ... [None, Entity(False, (1, 1)), None],

(self, entity: Entity)

Source from the content-addressed store, hash-verified

213 self.planet[entity.coords[0]][entity.coords[1]] = None
214
215 def get_surrounding_prey(self, entity: Entity) -> list[Entity]:
216 """
217 Returns all the prey entities around (N, S, E, W) a predator entity.
218
219 Subtly different to the `move_and_reproduce`.
220
221 >>> wt = WaTor(WIDTH, HEIGHT)
222 >>> wt.set_planet([
223 ... [None, Entity(True, (0, 1)), None],
224 ... [None, Entity(False, (1, 1)), None],
225 ... [None, Entity(True, (2, 1)), None]])
226 >>> wt.get_surrounding_prey(
227 ... Entity(False, (1, 1))) # doctest: +NORMALIZE_WHITESPACE
228 [Entity(prey=True, coords=(0, 1), remaining_reproduction_time=5),
229 Entity(prey=True, coords=(2, 1), remaining_reproduction_time=5)]
230 >>> wt.set_planet([[Entity(False, (0, 0))]])
231 >>> wt.get_surrounding_prey(Entity(False, (0, 0)))
232 []
233 >>> wt.set_planet([
234 ... [Entity(True, (0, 0)), Entity(False, (1, 0)), Entity(False, (2, 0))],
235 ... [None, Entity(False, (1, 1)), Entity(True, (2, 1))],
236 ... [None, None, None]])
237 >>> wt.get_surrounding_prey(Entity(False, (1, 0)))
238 [Entity(prey=True, coords=(0, 0), remaining_reproduction_time=5)]
239 """
240 row, col = entity.coords
241 adjacent: list[tuple[int, int]] = [
242 (row - 1, col), # North
243 (row + 1, col), # South
244 (row, col - 1), # West
245 (row, col + 1), # East
246 ]
247
248 return [
249 ent
250 for r, c in adjacent
251 if 0 <= r < self.height
252 and 0 <= c < self.width
253 and (ent := self.planet[r][c]) is not None
254 and ent.prey
255 ]
256
257 def move_and_reproduce(
258 self, entity: Entity, direction_orders: list[Literal["N", "E", "S", "W"]]

Callers 1

runMethod · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected