console_snake/main.py

82 lines
1.9 KiB
Python
Raw Permalink Normal View History

2022-10-26 21:57:29 +03:00
from settings import *
from player import Player
import keyboard as kb
from out import Out
2022-10-26 22:40:18 +03:00
from os import system
2022-10-27 19:59:23 +03:00
from time import sleep, time
2022-10-26 21:57:29 +03:00
class Game:
def __init__(self) -> None:
self.running = True
2022-10-27 15:29:28 +03:00
self.is_pause = False
2023-03-16 23:14:44 +03:00
self.pl = Player()
2022-11-06 22:18:02 +03:00
self.out = Out(self.pl)
2022-10-26 21:57:29 +03:00
kb.add_hotkey(QUIT_BUTTON, self.stop_game)
kb.add_hotkey(PAUSE_BUTTON, self.switch_pause)
2022-11-06 22:18:02 +03:00
kb.add_hotkey(
LEFT_BUTTON,
self.pl.left,
args=[self]
)
kb.add_hotkey(
RIGHT_BUTTON,
self.pl.right,
args=[self]
)
kb.add_hotkey(
UP_BUTTON,
self.pl.up,
args=[self]
)
kb.add_hotkey(
DOWN_BUTTON,
self.pl.down,
args=[self]
)
2022-10-26 21:57:29 +03:00
def switch_pause(self) -> None:
2022-10-27 15:29:28 +03:00
self.is_pause = not self.is_pause
2022-10-26 21:57:29 +03:00
def stop_game(self) -> None:
2022-11-06 22:18:02 +03:00
if not self.is_pause:
self.running = False
2022-10-26 21:57:29 +03:00
def play(self) -> None:
2022-10-26 22:40:18 +03:00
system("clear||cls")
2022-11-06 22:18:02 +03:00
print()
2022-10-27 19:59:23 +03:00
start_time = time()
different_between_time = 1 / FPS
2022-10-26 21:57:29 +03:00
while self.running:
try:
2022-10-27 19:59:23 +03:00
sleep(1 / FPS - different_between_time)
start_time = time()
2022-10-27 15:29:28 +03:00
if not self.is_pause:
self.pl.input()
self.pl.update()
self.out.draw()
2022-10-27 19:59:23 +03:00
end_time = time()
different_between_time = start_time - end_time
2022-10-26 21:57:29 +03:00
except IndexError as e:
self.running = False
print(e)
2022-10-27 00:29:36 +03:00
except KeyboardInterrupt:
return
2022-10-26 21:57:29 +03:00
2022-10-27 15:29:28 +03:00
input("Press enter to leave from game.\n")
2022-10-26 23:43:49 +03:00
2022-10-26 21:57:29 +03:00
def main() -> None:
2022-11-06 22:18:02 +03:00
game = Game()
game.play()
2022-10-26 21:57:29 +03:00
if __name__ == '__main__':
main()