Add apples
This commit is contained in:
parent
3fbd357dcf
commit
b80fe9c16d
3 changed files with 21 additions and 2 deletions
|
@ -18,6 +18,8 @@ def draw_board():
|
|||
board: List[List[int]] = [[0 for _ in range(wid)] for _ in range(hei)]
|
||||
for x, y in game.snake.body:
|
||||
board[y][x] = 1
|
||||
for x, y in game.apples:
|
||||
board[y][x] = 3
|
||||
x, y = game.snake.body[-1]
|
||||
board[y][x] = 2
|
||||
|
||||
|
@ -31,6 +33,8 @@ def draw_board():
|
|||
out[-1] += "\033[38;2;0;127;0m" + "\u2588" * 2
|
||||
elif cell == 2:
|
||||
out[-1] += "\033[38;2;0;255;0m" + "\u2588" * 2
|
||||
elif cell == 3:
|
||||
out[-1] += "\033[38;2;255;0;0m" + "\u2588" * 2
|
||||
print("\033c" + "\n".join(out), end='\033[0m')
|
||||
|
||||
|
||||
|
@ -39,7 +43,7 @@ def tick():
|
|||
draw_board()
|
||||
|
||||
|
||||
timer: Timer = Timer(1, tick)
|
||||
timer: Timer = Timer(.15, tick)
|
||||
timer.start()
|
||||
|
||||
draw_board()
|
||||
|
|
14
game.py
14
game.py
|
@ -1,3 +1,6 @@
|
|||
import random
|
||||
from typing import Tuple, Set
|
||||
|
||||
try:
|
||||
from snake import Snake
|
||||
except ImportError:
|
||||
|
@ -10,10 +13,21 @@ class Game:
|
|||
self.height: int = height
|
||||
self.snake: Snake = snake
|
||||
self.register_snake()
|
||||
self.tick_counter: int = 0
|
||||
self.apples: Set[Tuple[int, int]] = set()
|
||||
|
||||
def register_snake(self):
|
||||
assert self.width > 4 and self.height > 2, "Board is too small."
|
||||
self.snake.register(self, [(2 + i, 2) for i in range(3)])
|
||||
|
||||
def eat_apple(self, x: int, y: int):
|
||||
if (x, y) in self.apples:
|
||||
self.apples.remove((x, y))
|
||||
return True
|
||||
return False
|
||||
|
||||
def tick(self):
|
||||
if self.tick_counter % 20 == 0 and len(self.apples) < len(self.snake.body):
|
||||
self.apples.add((random.randint(0, self.width - 1), random.randint(0, self.height - 1)))
|
||||
self.snake.tick()
|
||||
self.tick_counter += 1
|
||||
|
|
3
snake.py
3
snake.py
|
@ -40,7 +40,8 @@ class Snake:
|
|||
if not (0 <= headx < self.board.width and 0 <= heady < self.board.height):
|
||||
self.dead: bool = True
|
||||
return
|
||||
self.body.pop(0)
|
||||
if not self.board.eat_apple(headx, heady):
|
||||
self.body.pop(0)
|
||||
if (headx, heady) in self.body:
|
||||
self.dead: bool = True
|
||||
return
|
||||
|
|
Reference in a new issue