From a34198e2906085dbef2d6798634bb844137a2c93 Mon Sep 17 00:00:00 2001 From: paulusja Date: Thu, 23 Apr 2026 18:26:21 +0200 Subject: [PATCH] Fix bug that prey might be placed elsewhere when prey's collision detection is done before snake's collision detection: Replace prey in following update step and not during collision detection. --- snake/prey.py | 21 ++++++++++++++------- 1 file changed, 14 insertions(+), 7 deletions(-) diff --git a/snake/prey.py b/snake/prey.py index ed19026..fd5f4d9 100644 --- a/snake/prey.py +++ b/snake/prey.py @@ -8,26 +8,33 @@ class Prey(GameObject): self.__bounding_box = pygame.rect.Rect(0, 0, size, size) self.__color = color self.__window_size = window_size + self.__next_pos = None self.__place_randomly() def __place_randomly(self) -> None: - self.__bounding_box.center = [random.randint(0, max_val) - for max_val in self.__window_size] + self.__next_pos = [random.randint(0, max_val) + for max_val in self.__window_size] - def __collides_with_other(self, game_objs: list[GameObject]) -> bool: + def __collides_with_other(self, pos: tuple, game_objs: list[GameObject]) -> bool: + box = pygame.rect.Rect(self.__bounding_box) + box.center = pos + for obj in game_objs: - if not isinstance(obj, Prey) and self.get_bounding_boxes()[0].collidelist(obj.get_bounding_boxes()) > -1: + if not isinstance(obj, Prey) and box.collidelist(obj.get_bounding_boxes()) > -1: return True + def draw(self, surface: pygame.surface.Surface) -> None: pygame.draw.rect(surface, color=self.__color, rect=self.__bounding_box) def update(self, user_input: int, game_objs: list[GameObject]): - while self.__collides_with_other(game_objs): - self.__place_randomly() - + self.__bounding_box.center = self.__next_pos + + while self.__collides_with_other(self.__next_pos, game_objs): + self.__place_randomly() + def get_bounding_boxes(self) -> list[pygame.rect.Rect]: return [self.__bounding_box]