summaryrefslogtreecommitdiff
path: root/swiftstory
diff options
context:
space:
mode:
authorOlivier Gayot <olivier.gayot@sigexec.com>2020-03-29 23:20:35 +0200
committerOlivier Gayot <olivier.gayot@sigexec.com>2020-03-29 23:52:42 +0200
commitfdc092990d5e3b9a28e7b646047a877e2cd88dcc (patch)
tree76bc7aa7cbcc63db16e4631712971f937138240a /swiftstory
parent6e44f62f44847643a697e56f42dbec77b72a5581 (diff)
Change the websocket library for the standard one
Signed-off-by: Olivier Gayot <olivier.gayot@sigexec.com>
Diffstat (limited to 'swiftstory')
-rw-r--r--swiftstory/Client.py36
-rw-r--r--swiftstory/Game.py30
-rw-r--r--swiftstory/Player.py8
-rw-r--r--swiftstory/SwiftStory.py51
4 files changed, 67 insertions, 58 deletions
diff --git a/swiftstory/Client.py b/swiftstory/Client.py
index 33b8e4b..b13e68b 100644
--- a/swiftstory/Client.py
+++ b/swiftstory/Client.py
@@ -1,16 +1,17 @@
+import websockets
+
from swiftstory.Status import error
from swiftstory.Game import Game
class Client():
- def __init__(self, socket, handler, game_manager):
+ def __init__(self, socket, game_manager):
self.game = None
self.game_manager = game_manager
- self.handler = handler
self.socket = socket
self.player = None
- def join_game(self, game_name, lang):
+ async def join_game(self, game_name, lang):
if self.game is not None:
return error('You are already in a game')
@@ -23,32 +24,32 @@ class Client():
if game is None:
return error('Invalid language')
- return game.try_join(self)
+ return await game.try_join(self)
def set_game(self, game):
self.game = game
def set_player(self, player):
self.player = player
- def play_white_card(self, card_id):
+ async def play_white_card(self, card_id):
if self.game is None:
return error('You have to join a game first')
- return self.game.try_play_card(self.player, card_id)
+ return await self.game.try_play_card(self.player, card_id)
- def pick_black_card(self):
+ async def pick_black_card(self):
if self.game is None:
return error('You have to join a game first')
- return self.game.try_become_judge(self.player)
+ return await self.game.try_become_judge(self.player)
- def collect_cards(self):
+ async def collect_cards(self):
if self.game is None:
error('You have to join a game first')
- return self.game.try_collect_cards(self.player)
+ return await self.game.try_collect_cards(self.player)
- def designate_card(self, card_id):
+ async def designate_card(self, card_id):
if self.game is None:
return error('You have to join a game first')
- return self.game.try_designate_card(self.player, card_id)
+ return await self.game.try_designate_card(self.player, card_id)
def view_player_cards(self):
if self.game is None:
@@ -65,9 +66,12 @@ class Client():
return error('You have to join a game first')
return self.game.try_view_black_card(self.player)
- def send_notification(self, message):
- self.socket.send_message(self.handler, message)
+ async def send_notification(self, message):
+ try:
+ await self.socket.send(message)
+ except websockets.exceptions.ConnectionClosed:
+ print("Recipient has disconnected.")
- def disconnect(self):
+ async def disconnect(self):
if self.player is not None:
- self.game.disconnect(self.player)
+ await self.game.disconnect(self.player)
diff --git a/swiftstory/Game.py b/swiftstory/Game.py
index 5e0961c..7e7da09 100644
--- a/swiftstory/Game.py
+++ b/swiftstory/Game.py
@@ -26,7 +26,7 @@ class Game():
self.board = Board(white_pick, black_pick)
- def try_join(self, client):
+ async def try_join(self, client):
if len(self.players) >= 10:
return error('too many players in this game')
@@ -50,7 +50,7 @@ class Game():
for p in self.players:
if p is not player:
- p.send_notification({'op': 'player_joined_game'})
+ await p.send_notification({'op': 'player_joined_game'})
cards = self.__view_player_cards(player)
@@ -64,7 +64,7 @@ class Game():
return success({'cards': cards, 'game_state': state})
- def try_become_judge(self, player):
+ async def try_become_judge(self, player):
if self.state is not self.WAITING_NEW_JUDGE:
# TODO what if the judge has quit ?
return error('Someone is judge already')
@@ -76,12 +76,12 @@ class Game():
for p in self.players:
if p is not player:
- p.send_notification({'op': 'judge_designed'})
+ await p.send_notification({'op': 'judge_designed'})
return self.try_view_black_card(player)
- def try_play_card(self, player, card_id):
+ async def try_play_card(self, player, card_id):
if self.state is not self.WAITING_COLLECTION:
return error('Who asked you to play now ?!')
@@ -99,12 +99,12 @@ class Game():
self.board.play_card(player, card)
- self.judge.send_notification({'op': 'card_played'})
+ await self.judge.send_notification({'op': 'card_played'})
return success({'card_id': card_id})
- def try_collect_cards(self, player):
+ async def try_collect_cards(self, player):
if self.state is not self.WAITING_COLLECTION:
return error('Do you think it\'s the moment for colletion !?')
@@ -118,12 +118,12 @@ class Game():
for p in self.players:
if p is not player:
- p.send_notification({'op': 'cards_collected'})
+ await p.send_notification({'op': 'cards_collected'})
return self.try_view_played_cards(player)
- def try_designate_card(self, player, card_id):
+ async def try_designate_card(self, player, card_id):
if self.state is not self.WAITING_DESIGNATION:
return error('Not now, moron !')
@@ -141,7 +141,7 @@ class Game():
except IndexError:
return error('Invalid card')
- winner.inc_score()
+ await winner.inc_score()
# put the cards back in the deck
self.board.recycle_played_cards()
@@ -153,7 +153,7 @@ class Game():
card_idx = p.cards[idx]
card_desc = self.white_desc[card_idx]
- p.send_notification({
+ await p.send_notification({
'op': 'received_card',
'content': {
'card': {
@@ -169,7 +169,7 @@ class Game():
for p in self.players:
if p is not player:
- p.send_notification({'op': 'judge_needed'})
+ await p.send_notification({'op': 'judge_needed'})
self.state = self.WAITING_NEW_JUDGE
@@ -205,7 +205,7 @@ class Game():
return error('The black card has not been revealed yet')
- def disconnect(self, player):
+ async def disconnect(self, player):
player.client = None
if self.judge is player:
@@ -213,14 +213,14 @@ class Game():
self.judge = None
for p in self.players:
- p.send_notification({'op': 'judge_needed'})
+ await p.send_notification({'op': 'judge_needed'})
for card, p in self.board.played_cards:
idx = p.receive_card(card)
card_idx = p.cards[idx]
card_desc = self.white_desc[card_idx]
- p.send_notification({
+ await p.send_notification({
'op': 'received_card',
'content': {
'card': {
diff --git a/swiftstory/Player.py b/swiftstory/Player.py
index cc64d17..a1d6cda 100644
--- a/swiftstory/Player.py
+++ b/swiftstory/Player.py
@@ -22,9 +22,9 @@ class Player():
def set_has_played(self, has=True):
self.has_played = has
- def inc_score(self):
+ async def inc_score(self):
self.score += 1
- self.send_notification({
+ await self.send_notification({
'op': 'updated_score',
'content': self.score,
})
@@ -34,10 +34,10 @@ class Player():
self.next_idx += 1
return self.next_idx - 1
- def send_notification(self, obj):
+ async def send_notification(self, obj):
if self.client is None:
return
message = json.dumps({'type': 'notification', 'content': obj})
- self.client.send_notification(message)
+ await self.client.send_notification(message)
diff --git a/swiftstory/SwiftStory.py b/swiftstory/SwiftStory.py
index 9e3051a..196c3dc 100644
--- a/swiftstory/SwiftStory.py
+++ b/swiftstory/SwiftStory.py
@@ -1,21 +1,18 @@
-#!/usr/bin/env python
+#!/usr/bin/env python3
+
+import asyncio
+import websockets
-from websocket_server import WebsocketServer
import swiftstory.GameManager
-import swiftstory.Client
+from swiftstory.Client import Client
from swiftstory.Status import error
import json
game_manager = swiftstory.GameManager.GameManager()
-def new_client_handler(client, server):
- client['client'] = swiftstory.Client.Client(server, client, game_manager)
-
-def client_left_handler(client, server):
- client['client'].disconnect();
-def message_received_handler(client, server, message):
+async def message_received_handler(client, websocket, message):
try:
json_msg = json.loads(message)
except JSONDecodeError:
@@ -29,15 +26,15 @@ def message_received_handler(client, server, message):
res = error('field `game_name\' is required')
else:
lang = json_msg.get('lang')
- res = client['client'].join_game(game_name, lang)
+ res = await client.join_game(game_name, lang)
elif op == 'view_player_cards':
- res = client['client'].view_player_cards()
+ res = client.view_player_cards()
elif op == 'view_black_card':
- res = client['client'].view_black_card()
+ res = client.view_black_card()
elif op == 'view_played_cards':
- res = client['client'].view_played_cards()
+ res = client.view_played_cards()
elif op == 'pick_black_card':
- res = client['client'].pick_black_card()
+ res = await client.pick_black_card()
elif op == 'designate_card':
card_id = None
try:
@@ -45,28 +42,36 @@ def message_received_handler(client, server, message):
except (KeyError, TypeError):
pass
finally:
- res = client['client'].designate_card(card_id)
+ res = await client.designate_card(card_id)
elif op == 'play_white_card':
try:
card_id = int(json_msg['card_id'])
except KeyError:
res = error('field `card_id\' is required')
else:
- res = client['client'].play_white_card(card_id)
+ res = await client.play_white_card(card_id)
elif op == 'collect_cards':
- res = client['client'].collect_cards()
+ res = await client.collect_cards()
else:
res = error('invalid command')
- server.send_message(client, res)
+ await websocket.send(res)
+
+
+async def swiftstory(websocket, path):
+ client = Client(websocket, game_manager)
+
+ async for message in websocket:
+ await message_received_handler(client, websocket, message)
+
+ await client.disconnect()
+
def main():
- server = WebsocketServer(1236, '0.0.0.0')
- server.set_fn_new_client(new_client_handler)
- server.set_fn_client_left(client_left_handler)
- server.set_fn_message_received(message_received_handler)
+ start_server = websockets.serve(swiftstory, '0.0.0.0', 1236)
- server.run_forever()
+ asyncio.get_event_loop().run_until_complete(start_server)
+ asyncio.get_event_loop().run_forever()
if __name__ == '__main__':
main()