feat: add ability to close connection
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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...")
|
||||
|
||||
Reference in New Issue
Block a user