4848STATE_WAITING_FOR_PONG = "WAITING_FOR_PONG" # noqa: E221
4949STATE_DONE = "DONE" # noqa: E221
5050
51+ # ── Mutable round counter ─────────────────────────────────────────────────────
52+
53+ rounds_left = NUM_ROUNDS
54+
55+
56+ # ── Handlers ─────────────────────────────────────────────────────────────────
57+
58+ async def handle_ready (writer : StreamWriter ) -> str :
59+ global rounds_left
60+ if rounds_left > 0 :
61+ rounds_left -= 1
62+ round_num = NUM_ROUNDS - rounds_left
63+ writer .write (b"PING\n " )
64+ print (f"Alice [round { round_num } ]: sent PING" )
65+ return STATE_WAITING_FOR_PONG
66+ else :
67+ writer .write (b"BYE\n " )
68+ print ("Alice: sent BYE, done." )
69+ return STATE_DONE
70+
71+
72+ async def handle_pong (writer : StreamWriter ) -> str :
73+ print ("Alice: received PONG" )
74+ return STATE_WAITING_FOR_READY
75+
76+
77+ # ── Dispatch table ────────────────────────────────────────────────────────────
78+
79+ ALICE_DISPATCH = {
80+ (STATE_WAITING_FOR_READY , "READY" ): handle_ready ,
81+ (STATE_WAITING_FOR_PONG , "PONG" ): handle_pong , # noqa: E241
82+ }
83+
5184
5285# ── Event loop ───────────────────────────────────────────────────────────────
5386
5487async def run_alice (reader : StreamReader , writer : StreamWriter ) -> None :
88+ global rounds_left
5589 rounds_left = NUM_ROUNDS
5690
57- async def handle_ready (writer : StreamWriter ) -> str :
58- nonlocal rounds_left
59- if rounds_left > 0 :
60- rounds_left -= 1
61- round_num = NUM_ROUNDS - rounds_left
62- writer .write (b"PING\n " )
63- print (f"Alice [round { round_num } ]: sent PING" )
64- return STATE_WAITING_FOR_PONG
65- else :
66- writer .write (b"BYE\n " )
67- print ("Alice: sent BYE, done." )
68- return STATE_DONE
69-
70- async def handle_pong (writer : StreamWriter ) -> str :
71- print ("Alice: received PONG" )
72- return STATE_WAITING_FOR_READY
73-
74- dispatch = {
75- (STATE_WAITING_FOR_READY , "READY" ): handle_ready ,
76- (STATE_WAITING_FOR_PONG , "PONG" ): handle_pong , # noqa: E241
77- }
78-
7991 state = STATE_WAITING_FOR_READY
8092
8193 while state != STATE_DONE :
@@ -86,7 +98,7 @@ async def handle_pong(writer: StreamWriter) -> str:
8698 msg = data .decode ("utf-8" )
8799 print (f"Alice [{ state } ]: received '{ msg } '" )
88100
89- handler = dispatch .get ((state , msg ))
101+ handler = ALICE_DISPATCH .get ((state , msg ))
90102
91103 if handler is None :
92104 print (f"Alice [{ state } ]: no transition for '{ msg } ' — ignoring." )
0 commit comments