Skip to content

Commit

Permalink
cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
krother committed Feb 2, 2024
1 parent 894e428 commit 3ffcc6f
Showing 1 changed file with 22 additions and 27 deletions.
49 changes: 22 additions & 27 deletions examples/snake.py
Original file line number Diff line number Diff line change
Expand Up @@ -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),
Expand All @@ -38,47 +38,42 @@
]


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()
else:
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
)


Expand All @@ -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
Expand Down

0 comments on commit 3ffcc6f

Please sign in to comment.