-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChemGame.py
More file actions
3944 lines (3526 loc) · 153 KB
/
ChemGame.py
File metadata and controls
3944 lines (3526 loc) · 153 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
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
离子风暴数字版(可玩 MVP)。
当前模块包含:
1) 基于 table.py 的可运行对局引擎
2) Tkinter 桌面中文界面
3) 服务器联机与多人房间加入
"""
from __future__ import annotations
import json
import random
import re
import secrets
import socket
import threading
import time
import tkinter as tk
from collections import Counter, deque
from dataclasses import dataclass, field
from tkinter import messagebox, ttk
from typing import Any, Dict, List, Optional, Tuple
import table as t
Pair = Tuple[str, str]
_SUBSCRIPT_TRANS = str.maketrans("0123456789+-()", "₀₁₂₃₄₅₆₇₈₉₊₋₍₎")
_SUPERSCRIPT_TRANS = str.maketrans("0123456789+-()", "⁰¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁽⁾")
HEARTBEAT_INTERVAL_SECONDS = 1.0
HEARTBEAT_LAG_SECONDS = 3.0
HEARTBEAT_TIMEOUT_SECONDS = 8.0
HEARTBEAT_WATCHDOG_SECONDS = 1.0
_NON_ION_DISPLAY = {
t.Au: "金",
t.U: "铀",
t.Acid: "强酸",
t.Alk: "强碱",
t.Enough: "足量",
t.Imp: "杂质",
t.Flt: "过滤",
t.Fde: "褪色",
t.AW: "洗气",
t.Dtl: "蒸馏",
t.AS: "加钠",
t.Ban: "禁",
t.Rev: "逆转",
}
_ALL_CARDS_SORTED = sorted(t.initCard.keys(), key=len, reverse=True)
_SILICIC_ACID_PAIR: Pair = (t.H, t.SiO3)
_ACID_REACTIVE_PRECIP_ANIONS = set(t.toG.get(t.H, []) + t.toWE.get(t.H, []) + t.toS.get(t.H, []))
def _format_ion_display(ion: str) -> str:
out = ion
out = re.sub(r"_(\d+)", lambda m: m.group(1).translate(_SUBSCRIPT_TRANS), out)
out = re.sub(r"\^\{([^}]+)\}", lambda m: m.group(1).translate(_SUPERSCRIPT_TRANS), out)
out = re.sub(
r"\^([0-9+\-]+)",
lambda m: m.group(1).translate(_SUPERSCRIPT_TRANS),
out,
)
return out
def _display_card_name(card: str) -> str:
if card in t.Ion:
return _format_ion_display(card)
return _NON_ION_DISPLAY.get(card, card)
def _display_text(text: str) -> str:
out = text
for card in _ALL_CARDS_SORTED:
out = out.replace(card, _display_card_name(card))
return out
def _counter_to_dict(counter: Counter[str]) -> Dict[str, int]:
return {k: counter[k] for k in sorted(counter) if counter[k] > 0}
def _pair_counter_to_dict(counter: Counter[Pair]) -> Dict[str, int]:
items: Dict[str, int] = {}
for (a, b) in sorted(counter):
n = counter[(a, b)]
if n > 0:
items[f"{a} + {b}"] = n
return items
def _send_json(sock: socket.socket, payload: Dict[str, Any]) -> None:
data = json.dumps(payload, ensure_ascii=False) + "\n"
sock.sendall(data.encode("utf-8"))
def _recv_json_nonblocking(
sock: socket.socket, buffer: bytes
) -> Tuple[Optional[Dict[str, Any]], bytes, bool]:
while b"\n" not in buffer:
try:
chunk = sock.recv(4096)
except (socket.timeout, BlockingIOError, InterruptedError):
return None, buffer, False
if not chunk:
return None, buffer, True
buffer += chunk
line, buffer = buffer.split(b"\n", 1)
line = line.strip()
if not line:
return None, buffer, False
try:
msg = json.loads(line.decode("utf-8"))
except Exception:
msg = {"type": "_invalid"}
return msg, buffer, False
def _parse_host_input(raw: str, default_host: str = "127.0.0.1") -> Tuple[str, Optional[int]]:
"""
Parse host text entered by user.
Supported examples:
- 192.168.1.10
- 192.168.1.10:5000
- ws://192.168.1.10
- http://192.168.1.10:5000/path
- [::1]:5000
"""
s = str(raw or "").strip()
# Normalize common full-width punctuation from Chinese IME.
s = (
s.replace("\uFF1A", ":")
.replace("\uFF0F", "/")
.replace("\u3002", ".")
.replace("\uFF0E", ".")
.replace("\uFF0C", ".")
.replace("\u3000", " ")
)
s = s.strip()
if not s:
return default_host, None
m = re.match(r"^[a-zA-Z][a-zA-Z0-9+.\-]*://(.*)$", s)
if m:
s = str(m.group(1) or "").strip()
if "/" in s:
s = s.split("/", 1)[0].strip()
if not s:
return default_host, None
host = s
parsed_port: Optional[int] = None
if host.startswith("[") and "]" in host:
end = host.find("]")
inner = host[1:end].strip()
rest = host[end + 1 :].strip()
if rest.startswith(":") and rest[1:].isdigit():
try:
parsed_port = int(rest[1:])
except Exception:
parsed_port = None
host = inner or default_host
return host, parsed_port
# host:port (IPv4 / hostname only). Plain IPv6 has multiple ':' and is kept as-is.
if host.count(":") == 1:
base, tail = host.rsplit(":", 1)
if tail.isdigit():
try:
parsed_port = int(tail)
except Exception:
parsed_port = None
host = base.strip() or default_host
return host.strip() or default_host, parsed_port
def _normalize_host_input(raw: str, default_host: str = "127.0.0.1") -> str:
host, _ = _parse_host_input(raw, default_host=default_host)
return host
def _open_tcp_connection(host: str, port: int, timeout_seconds: float = 5.0) -> socket.socket:
"""
Open TCP connection with AF_UNSPEC so IPv4/IPv6 host text can both work.
"""
host_text = _normalize_host_input(host)
port_num = int(port)
timeout = max(0.5, float(timeout_seconds))
try:
infos = socket.getaddrinfo(host_text, port_num, socket.AF_UNSPEC, socket.SOCK_STREAM)
except Exception as exc:
raise ConnectionError(f"无法解析服务器地址: {host_text} ({exc})") from exc
deadline = time.time() + timeout
last_exc: Optional[BaseException] = None
for family, socktype, proto, _canon, sockaddr in infos:
remain = deadline - time.time()
if remain <= 0:
break
sock = socket.socket(family, socktype, proto)
try:
sock.settimeout(min(2.5, remain))
sock.connect(sockaddr)
sock.settimeout(0.4)
return sock
except Exception as exc:
last_exc = exc
try:
sock.close()
except Exception:
pass
if last_exc is not None:
raise ConnectionError(f"连接 {host_text}:{port_num} 失败: {last_exc}") from last_exc
raise TimeoutError(f"连接 {host_text}:{port_num} 超时。")
@dataclass
class PlayerState:
name: str
hand: Counter[str] = field(default_factory=Counter)
@property
def hand_size(self) -> int:
return sum(self.hand.values())
class GameEngine:
def __init__(
self,
player_names: List[str],
initial_hand_size: Optional[int] = None,
seed: Optional[int] = None,
) -> None:
if len(player_names) < 2:
raise ValueError("至少需要 2 名玩家。")
self.players: List[PlayerState] = [PlayerState(name=n) for n in player_names]
self.deck: List[str] = []
self.discard: List[str] = []
self.solution: Counter[str] = Counter()
self.precipitates: Counter[Pair] = Counter()
self.gases: Counter[Pair] = Counter()
self.weak_electrolytes: Counter[Pair] = Counter()
self.gold_count = 0
self.uranium_timers: List[int] = []
self.skip_turns: Counter[int] = Counter()
self.current_player = 0
self.direction = 1
self.actions_left = 1
self.played_card_this_turn = False
self.winner: Optional[int] = None
self.turn_number = 1
self.log: deque[str] = deque(maxlen=200)
self.pending_draw_effect: Optional[Dict[str, Any]] = None
self._pending_draw_effect_seq = 0
self._rng = random.Random(seed)
self._build_deck()
if initial_hand_size is None:
hand_size = self._default_hand_size(len(self.players))
else:
hand_size = int(initial_hand_size)
if hand_size < 2:
raise ValueError("初始手牌数必须至少为 2。")
hand_size = min(10, hand_size)
for idx in range(len(self.players)):
self._draw_cards(idx, hand_size)
self._log(f"对局开始。初始手牌数: {hand_size}。")
self._log(f"当前玩家: {self.players[self.current_player].name}。")
@staticmethod
def _default_hand_size(player_count: int) -> int:
if player_count == 2:
return 10
if player_count <= 4:
return 7
return 6
def _build_deck(self) -> None:
self.deck.clear()
for card, count in t.initCard.items():
self.deck.extend([card] * count)
self._rng.shuffle(self.deck)
def _log(self, text: str) -> None:
self.log.append(text)
def _next_index(self, idx: Optional[int] = None) -> int:
if idx is None:
idx = self.current_player
return (idx + self.direction) % len(self.players)
def _prev_index(self, idx: int) -> int:
return (idx - self.direction) % len(self.players)
def _direction_hint_text(self) -> str:
if not self.players:
return "按座位顺序"
if self.direction == 1:
order = list(range(len(self.players)))
prefix = "按座位顺序"
else:
order = list(range(len(self.players) - 1, -1, -1))
prefix = "按座位逆序"
chain = "→".join([str(idx + 1) for idx in order] + [str(order[0] + 1)])
return f"{prefix}({chain})"
def _remove_from_hand(self, player_idx: int, card: str, count: int = 1) -> bool:
hand = self.players[player_idx].hand
if count <= 0 or hand[card] < count:
return False
hand[card] -= count
if hand[card] <= 0:
hand.pop(card, None)
return True
def _draw_cards(self, player_idx: int, count: int) -> List[str]:
drawn: List[str] = []
for _ in range(max(0, count)):
if not self.deck:
break
card = self.deck.pop()
self.players[player_idx].hand[card] += 1
drawn.append(card)
return drawn
def _draw_all_from(self, start_idx: int, count_each: int) -> None:
idx = start_idx
for _ in range(len(self.players)):
self._draw_cards(idx, count_each)
idx = self._next_index(idx)
def _draw_min_hand_players_once(self) -> None:
if not self.players:
return
min_hand = min(p.hand_size for p in self.players)
for idx, player in enumerate(self.players):
if player.hand_size == min_hand:
self._draw_cards(idx, 1)
def _distribute_draws(self, start_idx: int, total: int) -> List[Tuple[int, int]]:
if total <= 0:
return []
details: List[Tuple[int, int]] = []
remaining = total
idx = start_idx
while remaining > 0 and self.deck:
# 按规则:一次发牌超过 3 张时,按顺序轮转,每人每轮最多摸 3 张;双人局不受此限制。
if len(self.players) == 2:
limit = remaining
else:
limit = min(3, remaining)
drawn = self._draw_cards(idx, limit)
got = len(drawn)
if got <= 0:
break
details.append((idx, got))
remaining -= got
idx = self._next_index(idx)
return details
@staticmethod
def _format_draw_details(players: List[PlayerState], details: List[Tuple[int, int]]) -> str:
if not details:
return "无人摸牌"
merged: Dict[int, int] = {}
order: List[int] = []
for idx, num in details:
if idx not in merged:
merged[idx] = 0
order.append(idx)
merged[idx] += num
parts = [f"{players[idx].name}+{merged[idx]}" for idx in order]
return ", ".join(parts)
@staticmethod
def _pair_key(ion_a: str, ion_b: str) -> Pair:
if ion_a in t.Cation:
return (ion_a, ion_b)
return (ion_b, ion_a)
def _cleanup_solution(self, ion: str) -> None:
if self.solution[ion] <= 0:
self.solution.pop(ion, None)
@staticmethod
def _pair_ion_coeff(pair: Pair, ion: str) -> int:
cation, anion = pair
coeffs = t.Balance.get(cation, {}).get(anion)
if not coeffs:
return 0
if ion == cation:
return int(coeffs[0])
if ion == anion:
return int(coeffs[1])
return 0
@staticmethod
def _is_silicic_acid_pair(pair: Pair) -> bool:
return pair == _SILICIC_ACID_PAIR
def _pair_reaction_allowed(
self,
zone_name: str,
pair: Pair,
trigger_ion: str,
target_ion: str,
) -> bool:
if self._pair_ion_coeff(pair, target_ion) <= 0:
return False
# Prevent no-op loops like H+ reacting with H2SiO3/H2O products repeatedly.
if self._pair_ion_coeff(pair, trigger_ion) > 0:
return False
if zone_name != "precipitates":
return True
cation, anion = pair
if self._is_silicic_acid_pair(pair):
# Silicic acid only reacts with hydroxide.
return trigger_ion == t.OH and target_ion == t.H
if trigger_ion == t.H:
# Acid can only attack precipitate anion that is acid-reactive.
return target_ion == anion and anion in _ACID_REACTIVE_PRECIP_ANIONS
if trigger_ion == t.OH:
# In precipitate zone, hydroxide only attacks silicic acid.
return False
return True
def _count_ion_in_pair_counter(
self,
zone_name: str,
zone: Counter[Pair],
ion: str,
trigger_ion: Optional[str] = None,
) -> int:
total = 0
for pair, groups in zone.items():
if groups <= 0:
continue
if trigger_ion is not None and not self._pair_reaction_allowed(
zone_name=zone_name,
pair=pair,
trigger_ion=trigger_ion,
target_ion=ion,
):
continue
coeff = self._pair_ion_coeff(pair, ion)
if coeff > 0:
total += coeff * groups
return total
def _count_ion_in_products(self, ion: str, trigger_ion: Optional[str] = None) -> int:
return (
self._count_ion_in_pair_counter("precipitates", self.precipitates, ion, trigger_ion)
+ self._count_ion_in_pair_counter(
"weak_electrolytes", self.weak_electrolytes, ion, trigger_ion
)
+ self._count_ion_in_pair_counter("gases", self.gases, ion, trigger_ion)
)
def _extract_ion_from_pair_counter(
self,
zone_name: str,
zone: Counter[Pair],
ion: str,
need: int,
trigger_ion: Optional[str] = None,
) -> Tuple[int, Counter[str]]:
if need <= 0:
return 0, Counter()
consumed = 0
released: Counter[str] = Counter()
for pair in sorted(list(zone.keys())):
if consumed >= need:
break
if trigger_ion is not None and not self._pair_reaction_allowed(
zone_name=zone_name,
pair=pair,
trigger_ion=trigger_ion,
target_ion=ion,
):
continue
cation, anion = pair
if ion == cation:
source_ion = cation
other_ion = anion
elif ion == anion:
source_ion = anion
other_ion = cation
else:
continue
source_per_group = self._pair_ion_coeff(pair, source_ion)
other_per_group = self._pair_ion_coeff(pair, other_ion)
if source_per_group <= 0:
continue
groups = zone.get(pair, 0)
while groups > 0 and consumed < need:
zone[pair] -= 1
groups -= 1
if zone[pair] <= 0:
zone.pop(pair, None)
remaining = need - consumed
take = min(source_per_group, remaining)
consumed += take
if source_per_group > take:
released[source_ion] += source_per_group - take
if other_per_group > 0:
released[other_ion] += other_per_group
return consumed, released
def _extract_ion_from_products(
self,
ion: str,
need: int,
trigger_ion: Optional[str] = None,
) -> int:
if need <= 0:
return 0
consumed_total = 0
released_total: Counter[str] = Counter()
zones = (
("precipitates", self.precipitates),
("weak_electrolytes", self.weak_electrolytes),
("gases", self.gases),
)
for zone_name, zone in zones:
if consumed_total >= need:
break
consumed, released = self._extract_ion_from_pair_counter(
zone_name=zone_name,
zone=zone,
ion=ion,
need=need - consumed_total,
trigger_ion=trigger_ion,
)
consumed_total += consumed
released_total.update(released)
for rel_ion, amount in released_total.items():
if amount > 0:
self.solution[rel_ion] += amount
return consumed_total
def _resolve_reaction_with_ion(self, ion: str) -> int:
if ion not in t.Ion:
return 0
reacted_cards = 0
def consume(other: str, into: Optional[Counter[Pair]], slightly_soluble: bool = False) -> int:
nonlocal reacted_cards
if other not in t.Balance[ion]:
return 0
coeff_ion, coeff_other = t.Balance[ion][other]
threshold_scale = 2 if slightly_soluble else 1
gained = 0
while True:
enough_ion = self.solution[ion] >= threshold_scale * coeff_ion
enough_other_in_solution = self.solution[other] >= threshold_scale * coeff_other
enough_other_in_products = (
self._count_ion_in_products(other, trigger_ion=ion)
>= threshold_scale * coeff_other
)
if not enough_ion:
break
if not enough_other_in_solution and not enough_other_in_products:
break
self.solution[ion] -= coeff_ion
self._cleanup_solution(ion)
if enough_other_in_solution:
self.solution[other] -= coeff_other
self._cleanup_solution(other)
else:
got = self._extract_ion_from_products(
other,
coeff_other,
trigger_ion=ion,
)
if got < coeff_other:
self.solution[ion] += coeff_ion
break
if into is not None:
into[self._pair_key(ion, other)] += 1
reacted_cards += coeff_ion + coeff_other
gained += 1
return gained
for other in t.toS[ion]:
consume(other, self.precipitates, slightly_soluble=False)
for other in t.toG[ion]:
consume(other, self.gases, slightly_soluble=False)
for other in t.toWE[ion]:
consume(other, self.weak_electrolytes, slightly_soluble=False)
for other in t.toSS[ion]:
consume(other, self.precipitates, slightly_soluble=True)
for other in t.toNE[ion]:
consume(other, None, slightly_soluble=False)
return reacted_cards
@staticmethod
def _reactable_list(ion: str) -> List[str]:
seq = t.toS[ion] + t.toG[ion] + t.toWE[ion] + t.toSS[ion] + t.toNE[ion]
seen = set()
out = []
for x in seq:
if x not in seen:
seen.add(x)
out.append(x)
return out
def _consume_reactable_ions_only(self, ion: str) -> int:
if ion not in t.Ion:
return 0
reacted_partner_cards = 0
for other in self._reactable_list(ion):
if other not in t.Balance[ion]:
continue
coeff_other = t.Balance[ion][other][1]
if coeff_other <= 0:
continue
threshold_scale = 2 if other in t.toSS[ion] else 1
while True:
if self.solution[other] >= threshold_scale * coeff_other:
self.solution[other] -= coeff_other
self._cleanup_solution(other)
reacted_partner_cards += coeff_other
continue
if self._count_ion_in_products(other, trigger_ion=ion) >= threshold_scale * coeff_other:
got = self._extract_ion_from_products(
other,
coeff_other,
trigger_ion=ion,
)
if got < coeff_other:
break
reacted_partner_cards += coeff_other
continue
break
return reacted_partner_cards
def _check_winner(self, player_idx: int) -> None:
if self.players[player_idx].hand_size == 0 and self.winner is None:
self.winner = player_idx
self.pending_draw_effect = None
self._log(f"{self.players[player_idx].name} 获胜。")
def _consume_action(self) -> bool:
if self.actions_left <= 0:
return False
self.actions_left -= 1
return True
def _apply_radiation_for_player(self, player_idx: int) -> None:
if not self.uranium_timers:
return
radiation_cards = len(self.uranium_timers)
if radiation_cards > 0:
self._draw_cards(player_idx, radiation_cards)
self._log(f"辐射: {self.players[player_idx].name} 摸 {radiation_cards} 张。")
for i in range(len(self.uranium_timers)):
self.uranium_timers[i] -= 1
self.uranium_timers = [x for x in self.uranium_timers if x > 0]
def _apply_radiation_for_current_player(self) -> None:
self._apply_radiation_for_player(self.current_player)
def _begin_turn_from(self, start_player: int) -> None:
self.actions_left = 1
self.played_card_this_turn = False
candidate = start_player
while True:
self.current_player = candidate
self.turn_number += 1
skip_count = self.skip_turns[self.current_player]
if skip_count > 0:
self.skip_turns[self.current_player] -= 1
if self.skip_turns[self.current_player] <= 0:
self.skip_turns.pop(self.current_player, None)
self._log(
f"第 {self.turn_number} 回合: {self.players[self.current_player].name} 被跳过。"
)
candidate = self._next_index(self.current_player)
continue
self._apply_radiation_for_current_player()
self._log(f"第 {self.turn_number} 回合: {self.players[self.current_player].name}。")
return
def _end_turn_internal(self) -> None:
self._begin_turn_from(self._next_index(self.current_player))
def _clear_board_cards(self) -> Tuple[int, int]:
removed_gold = self.gold_count
removed_uranium = len(self.uranium_timers)
self.solution.clear()
self.precipitates.clear()
self.gases.clear()
self.weak_electrolytes.clear()
self.gold_count = 0
self.uranium_timers.clear()
return removed_gold, removed_uranium
def _apply_removed_special_effects(
self, player_idx: int, removed_gold: int, removed_uranium: int
) -> None:
if removed_gold > 0:
self._draw_all_from(player_idx, 1)
self._draw_min_hand_players_once()
self._log("金被移除,触发共同富裕。")
if removed_uranium > 0:
self._draw_all_from(player_idx, 1)
self._log("铀被移除,触发核泄漏。")
def _draw_limit_per_player(self, remaining: int) -> int:
if remaining <= 0:
return 0
if len(self.players) == 2:
return remaining
return min(3, remaining)
def _start_pending_draw_effect(
self,
source_player: int,
effect_card: str,
total_draw: int,
post_removed_special: Optional[Tuple[int, int, int]] = None,
) -> None:
if total_draw <= 0:
if post_removed_special is not None:
owner, removed_gold, removed_uranium = post_removed_special
self._apply_removed_special_effects(owner, removed_gold, removed_uranium)
return
self._pending_draw_effect_seq += 1
self.pending_draw_effect = {
"id": self._pending_draw_effect_seq,
"effect_card": effect_card,
"source_player": int(source_player),
"remaining": int(total_draw),
"cursor": self._next_index(source_player),
"follow_open": True,
"awaiting_player": None,
"follow_allowed": False,
"counter_allowed": False,
"forced_next_player": None,
"post_removed_special": post_removed_special,
"canceled_by_counter": False,
}
self._advance_pending_draw_effect()
def _pending_waiting_player(self) -> Optional[int]:
pending = self.pending_draw_effect
if not pending:
return None
waiting = pending.get("awaiting_player")
if waiting is None:
return None
try:
idx = int(waiting)
except Exception:
return None
if 0 <= idx < len(self.players):
return idx
return None
def _advance_pending_draw_effect(self) -> None:
while self.pending_draw_effect is not None and self.winner is None:
pending = self.pending_draw_effect
remaining = int(pending.get("remaining", 0))
if remaining <= 0:
self._finalize_pending_draw_effect()
return
cursor = int(pending.get("cursor", self.current_player))
if cursor < 0 or cursor >= len(self.players):
pending["remaining"] = 0
self._finalize_pending_draw_effect()
return
effect_card = str(pending.get("effect_card", "")).strip()
source_player = int(pending.get("source_player", self.current_player))
follow_open = bool(pending.get("follow_open", False))
is_offline_placeholder = self.skip_turns[cursor] >= 10**8
can_follow = (
(not is_offline_placeholder)
and follow_open
and cursor == self._next_index(source_player)
and self.players[cursor].hand[effect_card] > 0
)
can_counter = (
(not is_offline_placeholder)
and self.players[cursor].hand[t.AS] > 0
)
if can_follow or can_counter:
pending["awaiting_player"] = cursor
pending["follow_allowed"] = can_follow
pending["counter_allowed"] = can_counter
return
draw_limit = self._draw_limit_per_player(remaining)
if draw_limit <= 0:
pending["remaining"] = 0
self._finalize_pending_draw_effect()
return
got = len(self._draw_cards(cursor, draw_limit))
if got <= 0:
pending["remaining"] = 0
self._finalize_pending_draw_effect()
return
pending["remaining"] = remaining - got
pending["cursor"] = self._next_index(cursor)
pending["follow_open"] = False
self._log(f"{self.players[cursor].name} 受到 {effect_card} 效果,摸 {got} 张。")
def _finalize_pending_draw_effect(self) -> None:
pending = self.pending_draw_effect
if pending is None:
return
forced_next = pending.get("forced_next_player")
remaining = int(pending.get("remaining", 0))
effect_card = str(pending.get("effect_card", "")).strip()
if remaining > 0:
self._log(f"{effect_card} 剩余未执行摸牌 {remaining} 张,效果结束。")
post_removed_special = pending.get("post_removed_special")
canceled_by_counter = bool(pending.get("canceled_by_counter", False))
self.pending_draw_effect = None
if (
(not canceled_by_counter)
and isinstance(post_removed_special, tuple)
and len(post_removed_special) == 3
):
owner, removed_gold, removed_uranium = post_removed_special
self._apply_removed_special_effects(
int(owner), int(removed_gold), int(removed_uranium)
)
if self.winner is not None:
return
if forced_next is not None:
self._begin_turn_from(int(forced_next))
return
if self.actions_left <= 0:
self._end_turn_internal()
def _handle_pending_draw_response(self, player_idx: int, decision: str) -> Tuple[bool, str]:
pending = self.pending_draw_effect
if pending is None:
return False, "当前没有待响应的加牌效果。"
waiting_player = self._pending_waiting_player()
if waiting_player is None or player_idx != waiting_player:
return False, "当前不是你的加牌响应时机。"
decision_key = str(decision or "").strip().lower()
follow_allowed = bool(pending.get("follow_allowed", False))
counter_allowed = bool(pending.get("counter_allowed", False))
effect_card = str(pending.get("effect_card", "")).strip()
source_player = int(pending.get("source_player", self.current_player))
player_name = self.players[player_idx].name
pending["awaiting_player"] = None
pending["follow_allowed"] = False
pending["counter_allowed"] = False
if decision_key == "follow":
if not follow_allowed:
return False, "当前不允许跟牌传递。"
if not self._remove_from_hand(player_idx, effect_card, 1):
return False, f"你没有可跟牌的 {effect_card}。"
self.discard.append(effect_card)
pending["source_player"] = player_idx
pending["cursor"] = self._next_index(player_idx)
pending["follow_open"] = True
pending["forced_next_player"] = self._next_index(player_idx)
self._apply_radiation_for_player(player_idx)
self._log(f"{player_name} 跟牌打出 {effect_card},将效果传递给下家。")
self._check_winner(player_idx)
if self.winner is not None:
self.pending_draw_effect = None
return True, "已跟牌。"
self._advance_pending_draw_effect()
return True, "已跟牌。"
if decision_key == "counter":
if not counter_allowed:
return False, "当前不允许加钠反制。"
if not self._remove_from_hand(player_idx, t.AS, 1):
return False, "你没有可用于反制的加钠。"
self.discard.append(t.AS)
self._apply_add_sodium_effect(player_idx, "加钠(反制)")
upper_neighbor = self._prev_index(player_idx)
if source_player == upper_neighbor:
pending["forced_next_player"] = self._next_index(player_idx)
self._apply_radiation_for_player(player_idx)
self._log(
f"{player_name} 对上家的 {effect_card} 使用加钠反制,"
"视为耗尽本回合。"
)
else:
self._draw_cards(player_idx, 1)
pending["forced_next_player"] = self._next_index(source_player)
self._log(
f"{player_name} 对 {self.players[source_player].name} 的 {effect_card} 使用加钠反制,"
f"额外摸 1 张,回合改到 {self.players[pending['forced_next_player']].name}。"
)
pending["remaining"] = 0
pending["canceled_by_counter"] = True
self._check_winner(player_idx)
self._finalize_pending_draw_effect()
return True, "已使用加钠反制。"
if decision_key not in {"draw", "accept", "pass"}:
return False, "无效的响应指令。"
remaining = int(pending.get("remaining", 0))
draw_limit = self._draw_limit_per_player(remaining)
got = len(self._draw_cards(player_idx, draw_limit))
pending["remaining"] = max(0, remaining - got)
pending["cursor"] = self._next_index(player_idx)
pending["follow_open"] = False
self._log(f"{player_name} 选择执行摸牌,摸 {got} 张。")
self._advance_pending_draw_effect()
return True, "已执行摸牌。"
def on_player_disconnected(self, player_idx: int) -> None:
waiting_player = self._pending_waiting_player()
if waiting_player is None or waiting_player != player_idx:
return
self._log(f"{self.players[player_idx].name} 在响应阶段离线,按“摸牌”处理。")
self._handle_pending_draw_response(player_idx, "draw")
def _apply_add_sodium_effect(self, player_idx: int, source_label: str) -> None:
removed_gold, removed_uranium = self._clear_board_cards()
self._log(
f"{self.players[player_idx].name} 使用 {source_label}。清空场面,全员摸 1 张。"
)
self._draw_all_from(player_idx, 1)
self._apply_removed_special_effects(player_idx, removed_gold, removed_uranium)
def _play_wangzha(self, player_idx: int) -> Tuple[bool, str]:
if not self._consume_action():
return False, "没有剩余行动次数。"
hand = self.players[player_idx].hand
if hand[t.Acid] < 1 or hand[t.Alk] < 1:
self.actions_left += 1
return False, "王炸需要手牌中同时有 1 张强酸和 1 张强碱。"
self._remove_from_hand(player_idx, t.Acid, 1)
self._remove_from_hand(player_idx, t.Alk, 1)
self.discard.extend([t.Acid, t.Alk])
self._apply_add_sodium_effect(player_idx, "王炸(强酸+强碱)")
self._check_winner(player_idx)
return True, "已打出王炸。"
def _play_ion(self, player_idx: int, card: str, count: int) -> Tuple[bool, str]:
if card not in t.Ion:
return False, f"{card} 不是离子牌。"
if count <= 0:
return False, "数量必须为正整数。"
if not self._consume_action():
return False, "没有剩余行动次数。"
if not self._remove_from_hand(player_idx, card, count):
self.actions_left += 1
return False, f"手牌中 {card} 数量不足。"
self.solution[card] += count
reacted_cards = self._resolve_reaction_with_ion(card)
extra_actions = (reacted_cards + 1) // 2 if reacted_cards > 0 else 0
self.actions_left += extra_actions
self._log(
f"{self.players[player_idx].name} 打出 {card} ×{count}。"
f"参与反应牌数={reacted_cards},额外行动={extra_actions}。"
)
self._check_winner(player_idx)
return True, "离子牌已打出。"
def _play_special(self, player_idx: int, card: str) -> Tuple[bool, str]:
if card not in t.Special:
return False, f"{card} 不是特殊牌。"
if not self._consume_action():
return False, "没有剩余行动次数。"
if not self._remove_from_hand(player_idx, card, 1):