Add timer to console client
This commit is contained in:
parent
936e0c989e
commit
3fbd357dcf
2 changed files with 38 additions and 8 deletions
|
@ -1,10 +1,11 @@
|
|||
from os import get_terminal_size
|
||||
from typing import List
|
||||
from directions import *
|
||||
|
||||
from directions import *
|
||||
from game import Game
|
||||
from getkey import getkey
|
||||
from snake import Snake
|
||||
from timer import Timer
|
||||
|
||||
wid, hei = get_terminal_size()
|
||||
wid //= 2
|
||||
|
@ -13,7 +14,7 @@ snake: Snake = Snake("Snake", (0, 255, 0))
|
|||
game: Game = Game(wid, hei, snake)
|
||||
|
||||
|
||||
def init_draw_board():
|
||||
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
|
||||
|
@ -22,7 +23,7 @@ def init_draw_board():
|
|||
|
||||
out: List[str] = []
|
||||
for line in board:
|
||||
out.append("")
|
||||
out.append("\r")
|
||||
for cell in line:
|
||||
if cell == 0:
|
||||
out[-1] += "\033[38;2;0;0;0m" + "\u2588" * 2
|
||||
|
@ -30,12 +31,20 @@ def init_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
|
||||
print("\n".join(out), end='')
|
||||
print("\033c" + "\n".join(out), end='\033[0m')
|
||||
|
||||
|
||||
init_draw_board()
|
||||
def tick():
|
||||
game.tick()
|
||||
draw_board()
|
||||
|
||||
|
||||
timer: Timer = Timer(1, tick)
|
||||
timer.start()
|
||||
|
||||
draw_board()
|
||||
key: str = getkey()
|
||||
while key not in "\x03\x04\x1aqe":
|
||||
while key not in "\x03\x04\x1aqe" and not snake.dead:
|
||||
if key in ["\033[A", "w", "k"]: # UP
|
||||
snake.change_direction(NORTH)
|
||||
elif key in ["\033[B", "s", "j"]: # DOWN
|
||||
|
@ -44,6 +53,5 @@ while key not in "\x03\x04\x1aqe":
|
|||
snake.change_direction(EAST)
|
||||
elif key in ["\033[D", "a", "h"]: # LEFT
|
||||
snake.change_direction(WEST)
|
||||
game.tick()
|
||||
init_draw_board()
|
||||
key: str = getkey()
|
||||
timer.stop()
|
||||
|
|
22
timer.py
Normal file
22
timer.py
Normal file
|
@ -0,0 +1,22 @@
|
|||
import time
|
||||
from threading import Thread
|
||||
from typing import Callable
|
||||
|
||||
|
||||
class Timer(Thread):
|
||||
def __init__(self, interval: float, func: Callable):
|
||||
super().__init__()
|
||||
|
||||
self.interval: float = interval
|
||||
self.func: Callable = func
|
||||
self.running: bool = False
|
||||
|
||||
def run(self):
|
||||
self.running: bool = True
|
||||
time.sleep(self.interval)
|
||||
while self.running:
|
||||
self.func()
|
||||
time.sleep(self.interval)
|
||||
|
||||
def stop(self):
|
||||
self.running: bool = False
|
Reference in a new issue