-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.py
More file actions
464 lines (409 loc) · 15.8 KB
/
server.py
File metadata and controls
464 lines (409 loc) · 15.8 KB
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
import json
import socket
import sys
import time
from pathlib import Path
from typing import Any, Optional
from dataclasses import dataclass
import select
@dataclass
class Player:
"""Represents a connected or previously connected player."""
sock: socket.socket
addr: tuple[str, int]
username: str
score: int = 0
answered: bool = False
connected: bool = True
def encode_message(message: dict[str, Any]) -> bytes:
return json.dumps(message).encode("utf-8")
def send_message(conn: socket.socket, message: dict[str, Any]):
"""Send a JSON message to a client, terminated with a single newline."""
# Validate message type early
if not isinstance(message, dict):
raise TypeError("message must be a dict")
data = encode_message(message) + b"\n"
# Use sendall for atomic send; propagate exceptions so callers can mark
# the connection as disconnected and cleanup. This avoids swallowing
# network errors silently.
try:
conn.sendall(data)
except (ConnectionError, OSError):
# Let the caller handle marking connections as disconnected.
raise
def broadcast(players: list[Player], message: dict[str, Any]):
"""Send a message to all currently connected players."""
for p in players:
if p.connected:
try:
send_message(p.sock, message)
except (ConnectionError, OSError):
p.connected = False
try:
p.sock.close()
except (ConnectionError, OSError):
pass
def format_ready_info(cfg: dict[str, Any]) -> str:
"""Format the READY info string using all available config keys.
Falls back to the raw string if any placeholders are missing.
"""
try:
return str(cfg.get("ready_info", "")).format(**cfg)
except Exception:
return str(cfg.get("ready_info", ""))
def compute_correct_answer(qtype: str, short_question: str) -> str:
if qtype == "Mathematics":
val = eval_math_expression(short_question)
return str(int(round(val))) if float(val).is_integer() else str(val)
if qtype == "Roman Numerals":
return str(roman_to_int(short_question))
if qtype == "Usable IP Addresses of a Subnet":
return str(usable_ips(short_question))
if qtype == "Network and Broadcast Address of a Subnet":
net, bcast = network_broadcast(short_question)
return f"{net} and {bcast}"
return ""
def build_trivia_question(cfg: dict[str, Any], qtype: str, qnum: int, short_question: str) -> str:
q_template = cfg["question_formats"][qtype]
question_line = q_template.format(short_question)
return f"{cfg['question_word']} {qnum} ({qtype}):\n{question_line}"
def leaderboard_state(cfg: dict[str, Any], players: list[Player]) -> str:
# Include all players (even if disconnected) with their current static scores
active = list(players)
active.sort(key=lambda p: (-p.score, p.username))
lines: list[str] = []
rank = 0
prev_score: Optional[int] = None
for idx, p in enumerate(active, start=1):
if prev_score is None or p.score != prev_score:
rank = idx
prev_score = p.score
noun = cfg["points_noun_singular"] if p.score == 1 else cfg["points_noun_plural"]
lines.append(f"{rank}. {p.username}: {p.score} {noun}")
return "\n".join(lines)
def final_standings_text(cfg: dict[str, Any], players: list[Player]) -> str:
# Include all players in final standings
active = list(players)
active.sort(key=lambda p: (-p.score, p.username))
lines: list[str] = [cfg["final_standings_heading"]]
rank = 0
prev_score: Optional[int] = None
for idx, p in enumerate(active, start=1):
if prev_score is None or p.score != prev_score:
rank = idx
prev_score = p.score
noun = cfg["points_noun_singular"] if p.score == 1 else cfg["points_noun_plural"]
lines.append(f"{rank}. {p.username}: {p.score} {noun}")
winners: list[str] = []
if active:
top = active[0].score
winners = sorted([p.username for p in active if p.score == top])
if len(winners) == 1:
lines.append(cfg["one_winner"].format(winners[0]))
elif len(winners) > 1:
lines.append(cfg["multiple_winners"].format(", ".join(winners)))
else:
lines.append(cfg["multiple_winners"].format(""))
return "\n".join(lines)
def recv_json(conn: socket.socket) -> Optional[dict[str, Any]]:
"""Receive one client message (client messages are not newline-terminated).
Robust to TCP fragmentation: accumulates bytes until a valid JSON document
can be decoded or the socket times out/closes.
"""
buf = bytearray()
MAX_LEN = 8192 # sanity cap
decoder = json.JSONDecoder()
# We try to decode the first valid JSON object in the incoming byte stream.
# If multiple JSON objects arrive concatenated, we return the first and
# let the caller proceed; remaining bytes (if any) will be discarded in
# this simple per-call implementation. This keeps behaviour predictable
# while still being robust to TCP fragmentation.
while True:
# Attempt to decode current buffer if it contains any data
if buf:
try:
s = buf.decode("utf-8")
except UnicodeDecodeError:
# Invalid UTF-8 in client message — treat as malformed
return None
try:
obj, idx = decoder.raw_decode(s)
# Only accept object mappings (dict) as valid messages
if not isinstance(obj, dict):
return None
return obj
except json.JSONDecodeError:
# Not yet a complete JSON document — read more bytes
pass
# Read more data
try:
chunk = conn.recv(2048)
except socket.timeout:
# Caller may be using timeouts to implement waiting windows; treat
# a timeout as 'no complete message received yet'
return None
except Exception:
# Any other recv error -> connection problem
return None
if not chunk:
# Connection closed cleanly by peer
return None
buf.extend(chunk)
if len(buf) > MAX_LEN:
# Message too large or malicious; stop reading
return None
# ------------ Helpers that depend on question types ------------
def eval_math_expression(expr: str) -> float:
tokens = tokenize_expr(expr)
rpn = infix_to_rpn(tokens)
return eval_rpn(rpn)
def tokenize_expr(expr: str) -> list[str]:
tokens: list[str] = []
i = 0
while i < len(expr):
c = expr[i]
if c.isspace():
i += 1
continue
if c.isdigit():
j = i
while j < len(expr) and expr[j].isdigit():
j += 1
tokens.append(expr[i:j])
i = j
continue
if c in "+-*/()":
tokens.append(c)
i += 1
continue
raise ValueError("Invalid character in expression")
return tokens
def infix_to_rpn(tokens: list[str]) -> list[str]:
prec = {"+": 1, "-": 1, "*": 2, "/": 2}
output: list[str] = []
op_stack: list[str] = []
for t in tokens:
if t.isdigit():
output.append(t)
elif t in "+-*/":
while op_stack and op_stack[-1] in prec and prec[op_stack[-1]] >= prec[t]:
output.append(op_stack.pop())
op_stack.append(t)
elif t == "(":
op_stack.append(t)
elif t == ")":
while op_stack and op_stack[-1] != "(":
output.append(op_stack.pop())
if not op_stack or op_stack[-1] != "(":
raise ValueError("Mismatched parentheses")
op_stack.pop()
else:
raise ValueError("Invalid token")
while op_stack:
op = op_stack.pop()
if op in ("(", ")"):
raise ValueError("Mismatched parentheses at end")
output.append(op)
return output
def eval_rpn(tokens: list[str]) -> float:
stack: list[float] = []
for t in tokens:
if t.isdigit():
stack.append(float(t))
elif t in "+-*/":
b = stack.pop(); a = stack.pop()
if t == "+":
stack.append(a + b)
elif t == "-":
stack.append(a - b)
elif t == "*":
stack.append(a * b)
elif t == "/":
stack.append(a / b)
else:
raise ValueError("Invalid RPN token")
if len(stack) != 1:
raise ValueError("Invalid RPN evaluation")
return stack[0]
def roman_to_int(s: str) -> int:
values = {"I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000}
total = 0
i = 0
s = s.strip().upper()
while i < len(s):
v = values.get(s[i], 0)
if i + 1 < len(s):
v2 = values.get(s[i+1], 0)
if v < v2:
total += (v2 - v)
i += 2
continue
total += v
i += 1
return total
def ip_to_int(ip: str) -> int:
parts = [int(p) for p in ip.split(".")]
n = 0
for p in parts:
n = (n << 8) | (p & 0xFF)
return n
def int_to_ip(n: int) -> str:
return ".".join(str((n >> (24 - 8*i)) & 0xFF) for i in range(4))
def usable_ips(cidr: str) -> int:
_ip, prefix_str = cidr.split("/")
prefix = int(prefix_str)
host_bits = 32 - prefix
if prefix >= 32:
return 1 if prefix == 32 else 0
if prefix == 31:
return 0
total = (1 << host_bits)
return max(0, total - 2)
def network_broadcast(cidr: str) -> tuple[str, str]:
ip, prefix_str = cidr.split("/")
prefix = int(prefix_str)
ipn = ip_to_int(ip)
mask = (0xFFFFFFFF << (32 - prefix)) & 0xFFFFFFFF if prefix > 0 else 0
network = ipn & mask
broadcast = network | (~mask & 0xFFFFFFFF)
return int_to_ip(network), int_to_ip(broadcast)
def generate_short_question(qtype: str) -> str:
"""Delegate question generation to questions.py as per specs."""
import questions
if qtype == "Mathematics":
return questions.generate_mathematics_question()
if qtype == "Roman Numerals":
return questions.generate_roman_numerals_question()
if qtype == "Usable IP Addresses of a Subnet":
return questions.generate_usable_addresses_question()
if qtype == "Network and Broadcast Address of a Subnet":
return questions.generate_network_broadcast_question()
return ""
def main():
# Structure:
# 0. Load and validate the config. Start hosting immediately (bind to port, listen for connections)
# 1. Wait for the game to begin (wait for 'players' HIs)
# 2. Send READY
# 3. For each question type:
# a. Generate the question
# b. Broadcast QUESTION
# c. Wait question_seconds or until all answers received
# d. Grade, send RESULTs, then LEADERBOARD (except after last question)
argv = sys.argv[1:]
if not argv or len(argv) < 2 or argv[0] != "--config":
print("server.py: Configuration not provided", file=sys.stderr)
sys.exit(1)
cfg_path = argv[1]
p = Path(cfg_path)
if not (p.exists() and p.is_file()):
print(f"server.py: File {cfg_path} does not exist", file=sys.stderr)
sys.exit(1)
with open(p, "r", encoding="utf-8") as f:
cfg: dict[str, Any] = json.load(f)
host = "0.0.0.0"
port = int(cfg["port"])
max_players = int(cfg["players"])
try:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
server.listen()
except (OSError, PermissionError, ValueError):
print(f"server.py: Binding to port {port} was unsuccessful", file=sys.stderr)
sys.exit(1)
players: list[Player] = []
# Wait for the required number of players to join
while len(players) < max_players:
conn, addr = server.accept()
# Add a short timeout for the HI handshake so a silent client cannot block READY
conn.settimeout(2.0)
msg = recv_json(conn)
if not msg or msg.get("message_type") != "HI":
conn.close()
continue
username = str(msg.get("username", ""))
# Reject empty usernames
if not username:
conn.close()
continue
# Restore default blocking mode for the rest of the game flow
conn.settimeout(None)
players.append(Player(sock=conn, addr=addr, username=username))
# READY phase
info = format_ready_info(cfg)
broadcast(players, {"message_type": "READY", "info": info})
time.sleep(float(cfg["question_interval_seconds"]))
total_q = len(cfg["question_types"])
qnum = 0
for qtype in cfg["question_types"]:
qnum += 1
short_q = generate_short_question(qtype)
trivia_q = build_trivia_question(cfg, qtype, qnum, short_q)
time_limit = cfg["question_seconds"]
# Reset per-round flags
for p_obj in players:
p_obj.answered = False
# Broadcast QUESTION
broadcast(players, {
"message_type": "QUESTION",
"question_type": qtype,
"trivia_question": trivia_q,
"short_question": short_q,
"time_limit": time_limit,
})
correct_ans = compute_correct_answer(qtype, short_q)
start_ts = time.time()
while True:
remaining = float(time_limit) - (time.time() - start_ts)
if remaining <= 0:
break
if all((not p.connected) or p.answered for p in players):
break
rlist = [p.sock for p in players if p.connected and not p.answered]
if not rlist:
break
readable, _, _ = select.select(rlist, [], [], max(0.0, remaining))
for rs in readable:
p_obj = next((pp for pp in players if pp.sock is rs), None)
if not p_obj or not p_obj.connected:
continue
msg = recv_json(rs)
if not msg:
p_obj.connected = False
p_obj.sock.close()
continue
mtype = msg.get("message_type")
if mtype == "BYE":
p_obj.connected = False
p_obj.sock.close()
continue
if mtype == "ANSWER" and isinstance(msg.get("answer"), str):
ans = msg.get("answer")
is_correct = (ans == correct_ans)
if is_correct:
p_obj.score += 1
fb = cfg["correct_answer"].format(answer=ans, correct_answer=correct_ans)
else:
fb = cfg["incorrect_answer"].format(answer=ans, correct_answer=correct_ans)
try:
send_message(p_obj.sock, {"message_type": "RESULT", "correct": is_correct, "feedback": fb})
except (ConnectionError, OSError):
p_obj.connected = False
p_obj.sock.close()
p_obj.answered = True
if qnum < total_q:
# LEADERBOARD between questions
state = leaderboard_state(cfg, players)
broadcast(players, {"message_type": "LEADERBOARD", "state": state})
time.sleep(float(cfg["question_interval_seconds"]))
else:
# Final standings immediately after the last question
final_text = final_standings_text(cfg, players)
broadcast(players, {"message_type": "FINISHED", "final_standings": final_text})
break # exit loop
# Cleanup
for p_obj in players:
p_obj.sock.close()
server.close()
if __name__ == "__main__":
main()