-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.py
231 lines (175 loc) · 6.07 KB
/
server.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
from flask import Flask, json, Response, request
from pathlib import Path
import uuid
from random import choice
from game import Game
from unpack import unpack_files
api = Flask(__name__)
possible_words = [x.strip() for x in Path('words.txt').read_text().split('\n') if x]
real_time_positions = dict()
def clear_realtime(game_id):
if game_id in real_time_positions:
del real_time_positions[game_id]
def get_words(n):
words = list()
for _ in range(n):
words.append(choice(possible_words))
return words
def ok_str(s):
assert(isinstance(s, str))
if len(s) < 2:
return False
for char in s:
if not char in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890_':
return False
if not (s[0] in 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'):
return False
return True
@api.route('/', methods=['GET'])
def main_page():
content = Path('static') / 'index.html'
assert(content.is_file())
return Response(content.read_text(encoding='utf-8'), mimetype="text/html")
@api.route('/games', methods=['GET'])
def get_games():
player = request.args.get('player', type=str, default='')
games = Game.list_games()
if player:
games = [g for g in games if player in g['players']]
return json.dumps(games)
@api.route('/host', methods=['GET'])
def host_game():
players = request.args.get('players', type=str, default='some_player,another_player')
players = players.split(',')
if len(players) < 2:
return "Error: Too few players", 400
for player in players:
if not ok_str(player):
return "Illegal character used in one of the players names. Only letters, numbers and underscores are allowed.", 400
game_name = request.args.get('game_name', type=str, default='')
if game_name:
if not ok_str(game_name):
return "Illegal game name", 400
else:
# Make something up
words = get_words(4)
words.append(str(uuid.uuid4())[:4])
game_name = '_'.join(words)
skip_join = request.args.get('skip_join', type=str, default="False").lower() == "true"
game = Game(players, game_name=game_name, skip_join=skip_join)
game.save(init=True)
return f"{game_name}", 200
@api.route('/view_game', methods=['GET'])
def view_game():
game_id = request.args.get('game_id', type=str, default=None)
if game_id is None:
return "Invalid game ID", 400
try:
game = Game.load(game_id)
except ValueError as err:
return f"Something went wrong: {err}", 400
except:
return "Failed to load game due to some unforeseen error", 400
return game.json(), 200
@api.route('/move_card', methods=['GET'])
def move_card():
game_id = request.args.get('game_id', type=str, default=None)
player = request.args.get('player', type=str, default=None)
card_name = request.args.get('card', type=str, default=None)
from_pile = request.args.get('from', type=str, default=None)
to_pile = request.args.get('to', type=str, default=None)
inputs = [game_id, player, card_name, from_pile, to_pile]
if any([x is None for x in inputs]):
return "Some input variable is missing", 400
try:
game = Game.load(game_id)
except ValueError as err:
return f"Something went wrong: {err}", 400
except:
return "Failed to load game due to some unforeseen error", 400
if not (player == game.turn):
return "Not your turn!", 400
if from_pile == player:
# Trying to play a card from the hand
to_pile = int(to_pile)
if to_pile == -1:
to_pile = None
# Create a new pile
card = game.find_card(card_name, player)
if card is None:
return f"Could not find card {card_name} in {player}'s hand", 400
try:
game.place_card(card, to_pile)
except Exception as err:
return f"Something went wrong: {err}", 400
elif to_pile == player:
# Trying to take a card into the hand
from_pile = int(from_pile)
card = game.find_card_in_pile(card_name, from_pile)
if card is None:
return f"Could not find card {card_name} in pile {from_pile}", 400
try:
game.take_back(card, from_pile)
except ValueError as err:
return f"Something went wrong: {err}", 400
else:
# Move a card already on the board
from_pile, to_pile = [int(x) for x in (from_pile, to_pile)]
card = game.find_card_in_pile(card_name, from_pile)
if card is None:
return f"Could not find card {card_name} in {from_pile}", 400
try:
game.move_card(card, from_pile, to_pile)
except ValueError as err:
return f"Something went wrong: {err}", 400
clear_realtime(game_id)
game.save(game_id)
return "ok", 200
@api.route('/retreat', methods=['GET'])
def retreat():
game_id = request.args.get('game_id', type=str, default=None)
player = request.args.get('player', type=str, default=None)
if game_id is None:
return "No game provided", 400
if player is None:
return "No player provided", 400
try:
game = Game.load(game_id)
except ValueError as err:
return f"Something went wrong: {err}", 400
except:
return "Failed to load game due to some unforeseen error", 400
if not player == game.turn:
return "Not your turn", 400
result = game.retreat()
if result:
clear_realtime(game_id)
game.save(game_id)
return "ok", 200
else:
return "Cannot retreat the same turn you got into the game!", 400
@api.route("/keso", methods=['GET'])
def keso():
game_id = request.args.get('game_id', type=str, default=None)
player = request.args.get('player', type=str, default=None)
if game_id is None:
return "No game provided", 400
if player is None:
return "No player provided", 400
try:
game = Game.load(game_id)
except ValueError as err:
return f"Something went wrong: {err}", 400
except:
return "Failed to load game due to some unforeseen error", 400
if not player == game.turn:
return "Not your turn", 400
out, _ = game.finish()
if not out:
return "You still have cards on the table!", 400
clear_realtime(game_id)
game.save(game_id)
return "ok", 200
if __name__ == '__main__':
unpack_files()
api.run(host='0.0.0.0', port=31416)