From 5425d4a7fcf2ec67312489bbd350a5159515b501 Mon Sep 17 00:00:00 2001 From: Giovani Rodriguez Date: Mon, 5 Jul 2021 12:44:29 -0400 Subject: [PATCH] feat: add ability to close connection --- tetris/game.py | 2 ++ tetris/online.py | 21 +++++++++++++++++++-- 2 files changed, 21 insertions(+), 2 deletions(-) diff --git a/tetris/game.py b/tetris/game.py index 517dc7e..854a883 100644 --- a/tetris/game.py +++ b/tetris/game.py @@ -65,6 +65,7 @@ class Game: self.next_piece = PieceGenerator.get_piece((620, 160)) # (360, 100) if self.stack and self.current_piece.collide(self.stack): # TODO game over redo pygame.quit() + MultiplayerService.quit() sys.exit() if self.stack: @@ -73,6 +74,7 @@ class Game: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() + MultiplayerService.quit() sys.exit() def draw(self) -> None: diff --git a/tetris/online.py b/tetris/online.py index 92a2a5d..ef5d537 100644 --- a/tetris/online.py +++ b/tetris/online.py @@ -7,22 +7,39 @@ class MultiplayerService(): @classmethod def init(cls): - thread = Thread(target=asyncio.get_event_loop().run_until_complete, args=(_NetworkConnectionService.init(),)) + thread = Thread(target=asyncio.get_event_loop().run_until_complete,\ + args=(_NetworkConnectionService.init(),)) thread.start() + @classmethod + def quit(cls): + _NetworkConnectionService.close_connection() + class _NetworkConnectionService(): _websocket = None - _URI = "ws://localhost:5001" + _URI = "ws://webapi.tetri5.com" + _is_closed = False @classmethod async def init(cls): await cls._connect_to_server() + await cls._run_network_loop() + + @classmethod + def close_connection(cls): + cls._is_closed = True + @classmethod + async def _run_network_loop(cls): while True: await asyncio.sleep(16e-3) await cls._websocket.send("ping") print(await cls._websocket.recv()) + if cls._is_closed: + await cls._websocket.close() + break + @classmethod async def _connect_to_server(cls): print("Connecting to server...")