From 3ffcc6f42e389106ea4e6591cc3a173b1b93c64f Mon Sep 17 00:00:00 2001 From: Kristian Rother Date: Fri, 2 Feb 2024 14:02:38 +0100 Subject: [PATCH] cleanup --- examples/snake.py | 49 +++++++++++++++++++++-------------------------- 1 file changed, 22 insertions(+), 27 deletions(-) diff --git a/examples/snake.py b/examples/snake.py index b1465d8..8cbd50d 100644 --- a/examples/snake.py +++ b/examples/snake.py @@ -22,14 +22,14 @@ MOVE_SPEED = 100 MOVES = { - "a": (-1, 0), - "d": (1, 0), - "w": (0, -1), - "s": (0, 1), + "a": (-1, 0), # left + "d": (1, 0), # right + "w": (0, -1), # up + "s": (0, 1), # down } RAINBOW = [ - (0, 0, 255), + (0, 0, 255), # BGR - blue, green red (0, 128, 255), (0, 255, 255), (0, 255, 0), @@ -38,34 +38,28 @@ ] -def ticker(speed: int): - counter = speed - while True: - for _ in range(counter): - yield False - yield True - - Color = tuple[int, int, int] +Position = tuple[int, int] + class Food(BaseModel): - position: tuple[int, int] + position: Position color: Color class Snake(BaseModel): - tail: list[tuple[int, int]] = [] - colors: list[Color] - direction: str = (1, 0) + tail: list[Position] = [] # the tail is a queue + colors: list[Color] = [] + direction: Position = (1, 0) - @property + @property # decorator: allows us to use .head like an attribute def head(self): return self.tail[0] def move(self, food): - x, y = self.head - dx, dy = self.direction - new_head = x + dx, y + dy + x, y = self.head # calls the function automatically + dx, dy = self.direction # unpack a tuple into two variables + new_head = x + dx, y + dy # create a new position tuple self.tail.insert(0, new_head) if new_head != food.position: self.tail.pop() @@ -73,12 +67,13 @@ def move(self, food): self.colors.insert(0, food.color) def collides(self): + x, y = self.head return ( self.head in self.tail[1:] - or self.head[0] < 0 - or self.head[1] < 0 - or self.head[0] == COLS - or self.head[1] == ROWS + or x < 0 + or y < 0 + or x == COLS + or y == ROWS ) @@ -102,8 +97,8 @@ def draw(snake, food): snake = Snake(tail=[(5, 5)], colors=[(255, 0, 255)]) food = Food(position=(10, 5), color=next(color_gen)) -frame_tick = ticker(FRAME_SPEED) -move_tick = ticker(MOVE_SPEED) +frame_tick = cycle([True] + [False] * FRAME_SPEED) +move_tick = cycle([True] + [False] * MOVE_SPEED) while not snake.collides(): # draw everything