Kill snake on collision with itself.

This commit is contained in:
paulusja 2026-04-23 16:39:56 +02:00
parent 0e72331f45
commit d19c45abbc

View File

@ -18,11 +18,15 @@ class Snake(GameObject):
def __collides_with_wall(self, obj: GameObject): def __collides_with_wall(self, obj: GameObject):
return isinstance(obj, Wall) and self.get_bounding_boxes()[0].collidelist(obj.get_bounding_boxes()) > -1 return isinstance(obj, Wall) and self.get_bounding_boxes()[0].collidelist(obj.get_bounding_boxes()) > -1
def __collides_with_self(self, obj: GameObject):
return isinstance(obj, Snake) and self.get_bounding_boxes()[0].collidelist(obj.get_bounding_boxes()[1:]) > -1
def __update_on_collision(self, game_objs: list[GameObject]) -> None: def __update_on_collision(self, game_objs: list[GameObject]) -> None:
for obj in game_objs: for obj in game_objs:
if self.__collides_with_wall(obj): if self.__collides_with_wall(obj) or self.__collides_with_self(obj):
self.__is_dead = True self.__is_dead = True
@ -34,11 +38,12 @@ class Snake(GameObject):
if not self.__is_dead: if not self.__is_dead:
self.__update_on_collision(game_objs) self.__update_on_collision(game_objs)
self.__state_machine.update(user_input) if not self.__is_dead:
new_head = self.__state_machine.get_state().get_next_head(self.__segments[0]) self.__state_machine.update(user_input)
new_head = self.__state_machine.get_state().get_next_head(self.__segments[0])
self.__segments.insert(0, new_head)
self.__segments.pop() self.__segments.insert(0, new_head)
self.__segments.pop()
def get_bounding_boxes(self) -> list[pygame.rect.Rect]: def get_bounding_boxes(self) -> list[pygame.rect.Rect]:
return [seg.get_bounding_boxes()[0] for seg in self.__segments] return [seg.get_bounding_boxes()[0] for seg in self.__segments]