Skip to content
Commits on Source (3)
from random import choice
from random import randint
from pythonsnake.snake import Snake
......@@ -32,22 +32,10 @@ class Candy:
self.Y = y
def random_coord_X(self, grid_width: int, snake: Snake) -> int:
coord_to_exclude = []
for snake_part in snake.coord:
coord_to_exclude.append(snake_part["x"])
return choice(
[i for i in range(0, grid_width) if i not in coord_to_exclude]
)
return randint(0, grid_width-1)
def random_coord_Y(self, grid_height: int, snake: Snake) -> int:
coord_to_exclude = []
for snake_part in snake.coord:
coord_to_exclude.append(snake_part["y"])
return choice(
[i for i in range(0, grid_height) if i not in coord_to_exclude]
)
return randint(0, grid_height-1)
def new_coord(
self, grid_width: int, grid_height: int, snake: Snake
......
......@@ -29,6 +29,7 @@ class Controller:
return int(choice)
def start_game(self, mode: int) -> None:
#TODO: detect console size of the user
self.game = Game(50, 25)
if mode == 1:
......@@ -38,12 +39,13 @@ class Controller:
keyboard.unhook_all()
self.listen_escape_game()
self.listen_move()
while not self.game.lost:
self.view.display_grid(
self.game.move(self.game.current_direction + " arrow")
)
self.listen_move()
continue
time.sleep(1)
......@@ -54,11 +56,8 @@ class Controller:
def listen_move(self) -> None:
if keyboard.is_pressed("left arrow"):
self.view.display_grid(self.game.move("left arrow"))
if keyboard.is_pressed("right arrow"):
self.view.display_grid(self.game.move("right arrow"))
if keyboard.is_pressed("up arrow"):
self.view.display_grid(self.game.move("up arrow"))
if keyboard.is_pressed("down arrow"):
self.view.display_grid(self.game.move("down arrow"))
keyboard.on_press_key("left arrow", lambda _: self.view.display_grid(self.game.move("left arrow")))
keyboard.on_press_key("right arrow", lambda _: self.view.display_grid(self.game.move("right arrow")))
keyboard.on_press_key("up arrow", lambda _: self.view.display_grid(self.game.move("up arrow")))
keyboard.on_press_key("down arrow", lambda _: self.view.display_grid(self.game.move("down arrow")))
\ No newline at end of file
......@@ -63,7 +63,7 @@ class Game:
):
return False
# check if next position of snake haed is not another snake piece
# check if next position of snake head is not another snake piece
for snake_piece in self.snake.coord:
if (
snake_piece["x"] == snake_head["x"]
......
......@@ -5,12 +5,16 @@ import os
class TerminalView:
def __init__(self) -> None:
pass
self.in_progress = False
def cls(self) -> None:
os.system("cls" if os.name == "nt" else "clear")
def display_grid(self, gameState: Game) -> None:
if(self.in_progress == True):
return None
self.in_progress = True
grid_to_print = ""
for Y, line in enumerate(gameState.grid):
......@@ -71,6 +75,7 @@ class TerminalView:
)
self.cls()
print(grid_to_print, end="\r")
self.in_progress = False
def menu(self) -> None:
self.cls()
......