Compare commits

...

3 Commits

Author SHA1 Message Date
Plaza521 58fdba4d82
Add game class 2023-10-26 02:38:17 +03:00
Plaza521 419dc147c0
Add timer.py
Class to control fps in game
2023-10-26 02:12:37 +03:00
Plaza521 79e400d1ea
Add screen.py
Class to simplify the output and not think about moving cursor to start of screen (clear command works slow)
2023-10-26 01:34:51 +03:00
4 changed files with 107 additions and 0 deletions

44
main.py Normal file
View File

@ -0,0 +1,44 @@
from threading import Thread
from screen import Screen
from timer import Timer
from getkey import getkey
class Tetris:
def __init__(self) -> None:
self.screen = Screen(10, 20, '..')
self.last_char = ''
self.input_thread = Thread(target=self.input, daemon=True)
self.input_thread.start()
self.timer = Timer()
def start(self) -> None:
self.running = True
while self.running:
self.timer.control_fps(30)
self.screen.print()
def stop(self) -> None:
self.running = False
self.timer.running = False
self.input_running = False
def input(self) -> None:
self.input_running = True
while self.input_running:
self.last_char = getkey()
match self.last_char:
case 'q':
self.stop()
return
def main() -> None:
game = Tetris()
game.start()
if __name__ == "__main__":
main()

1
requirements.txt Normal file
View File

@ -0,0 +1 @@
getkey==0.6.5

44
screen.py Normal file
View File

@ -0,0 +1,44 @@
from typing import List, Any
from sys import platform
if platform == "win32":
from ctypes import windll, c_long, Structure
STD_OUTPUT_HANDLE = -11
STDHANDLE = windll.kernel32.GetStdHandle(STD_OUTPUT_HANDLE)
class COORDSET(Structure):
_fields_ = [("X", c_long), ("Y", c_long)]
def set_cursor_position(x: int, y: int) -> None:
windll.kernel32.SetConsoleCursorPosition(STDHANDLE, COORDSET(x, y))
else:
def set_cursor_position(x: int, y: int) -> None:
print(f"\033[{x};{y}H")
class Screen:
def __init__(
self,
width: int,
height: int,
fill_object: Any = None
) -> None:
self.width: int = width
self.height: int = height
self.frame: List[List[Any]] = \
[[fill_object] * width for line in range(height)]
def __getitem__(self, key: int) -> List[Any]:
return self.frame[key]
def fill(self, fill_object: Any = None) -> None:
self.frame: List[List[Any]] = \
[[fill_object] * width for line in range(height)]
def print(self) -> None:
set_cursor_position(0, 0)
for line in self.frame:
for point in line:
print(point, end='')
print()

18
timer.py Normal file
View File

@ -0,0 +1,18 @@
from time import time
class Timer:
def __init__(self) -> None:
self.running = False
self.old = 0
def control_fps(self, fps: int) -> int:
if not self.running:
self.old = time()
return
delay_between_frames = 1 / fps
now = time()
while now - self.old < delay_between_frames:
now = time()
self.old = now