Repository navigation
Expand file tree
/
Copy pathstate_manager.py
More file actions
3033 lines (2793 loc) · 132 KB
/
Copy pathstate_manager.py
File metadata and controls
3033 lines (2793 loc) · 132 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# SPDX-License-Identifier: MIT
"""
比赛状态管理器
@file state_manager.py
@brief 管理比赛全局状态,包括阶段、比分、血量等
@author Fudan EGA Team
@date 2025-12-07
@copyright Copyright (c) 2025 Fudan University EGA Team (复旦大学星云 EGA 机器人战队).
功能说明:
- 管理比赛阶段(准备/比赛/结算)
- 管理红蓝方比分和机器人血量
- 提供状态读写的线程安全访问
"""
import time
import threading
from datetime import datetime
class StateManager:
BASE_HP_MAX = 5000
BASE_HP_STEP = 50
SCORE_MIN = 0
SCORE_MAX = 999
ECONOMY_MIN = 0
ECONOMY_MAX = 100000
TEAM_NAMES = ("red", "blue")
FORTRESS_CAPTURE_DURATION_SEC = 20
def __init__(self):
self.lock = threading.Lock()
self.running = False
# 按协议消息分组维护后端状态;红蓝方数据仍保留在服务端,
# 发送 MQTT/UDP 时再根据客户端视角转换成己方/敌方字段。
self.game_status = self._create_game_status_state()
self.global_logistics_status = self._create_global_logistics_status_state()
self.global_unit_status = self._create_global_unit_status_state()
self.referee_info_by_team = {
"red": self._create_rune_state(),
"blue": self._create_rune_state(),
}
self.active_rune_team = "red"
self.referee_info = dict(self.referee_info_by_team[self.active_rune_team])
self.air_support = {
"red_status": 0,
"blue_status": 0,
"red_left_time": 30,
"blue_left_time": 30,
"red_default_time": 30,
"blue_default_time": 30,
"red_cost_coins": 0,
"blue_cost_coins": 0,
"red_mode": "free",
"blue_mode": "free",
"red_is_being_targeted": 0,
"blue_is_being_targeted": 0,
"red_shooter_status": 1,
"blue_shooter_status": 1,
"active_team": "",
"last_command_team": "",
}
self.tech_core_motion_state = {
"maximum_difficulty_level": 1,
"basic_state": 1,
"status": 1, # 兼容旧版模拟器界面和状态结构
"putin_state": 0,
"move_state": 0,
"rotate_state": 0,
"enemy_core_status": 0,
"remain_time_all": 0,
"remain_time_step": 0,
}
self.deploy_mode_status_by_team = self._create_deploy_mode_status_by_team()
self.deploy_mode_status = 0
self.current_robot_id = 1
self.global_special_mechanism = {
"mechanism_id": [1, 2],
"mechanism_time_sec": [0, 0],
}
self.robot_performance_selection_sync = {
"shooter": 1,
"chassis": 1,
"sentry_control": 0,
}
self.robot_static_status = self._create_robot_static_status_state()
self.robot_dynamic_status = self._create_robot_dynamic_status_state()
self.robot_module_status = self._create_robot_module_status_state()
self.sentry_status_sync = {
"posture_id": 0,
"is_weakened": False,
"is_powered": False,
}
self.robot_path_plan_info = {
"intention": 1,
"start_pos_x": 0,
"start_pos_y": 0,
"offset_x": [],
"offset_y": [],
"sender_id": 7,
}
self.last_sentry_ctrl_result = {
"command_id": 0,
"result_code": 0,
}
self.sentry_ctrl_result_queue = []
self.last_game_result = {
"winner": 0,
"winner_label": "未结算",
"reason": "",
"end_reason": 255,
"red_score": 0,
"blue_score": 0,
}
self.pending_game_result_reason = ""
self.pending_game_result_end_reason = 255
self.event_queue = [] # 0x0101 EVENT_DATA 专用队列
self.warning_queue = [] # 0x0104 REFEREE_WARNING 专用队列
self.game_result_queue = [] # 0x0002 GAME_RESULT 专用队列
self._game_result_enqueued = False
self.kicked_all = False # 踢出全员标记(用于裁判系统“踢出所有”)
self.penalty_counts = {} # 判罚计数字典: key=(level, offending_robot_id), value=次数
# 机器人位置 (x, y, 角度) - 归一化 0.0 到 1.0 还是米?
# 协议使用米。地图通常为 28m x 15m。
self.positions = [
{"x": 2.0, "y": 2.0, "angle": 0.0}, # 红方 1
{"x": 5.0, "y": 2.0, "angle": 0.0}, # 红方 3
{"x": 8.0, "y": 2.0, "angle": 0.0}, # 红方 6
{"x": 11.0, "y": 2.0, "angle": 0.0}, # 红方 7
{"x": 17.0, "y": 10.0, "angle": 180.0}, # 蓝方 101
{"x": 20.0, "y": 10.0, "angle": 180.0}, # 蓝方 103
{"x": 23.0, "y": 10.0, "angle": 180.0}, # 蓝方 106
{"x": 26.0, "y": 10.0, "angle": 180.0}, # 蓝方 107
]
self._initial_positions = [dict(position) for position in self.positions]
self._match_simulation_clock_active = False
self.match_simulation_status = {
"state": "idle",
"status": "idle",
"mode": "quick",
"speed": 1.0,
"features": {"positions": True, "hp": True, "events": True},
"elapsed": 0.0,
"elapsed_sec": 0.0,
"remaining": 90.0,
"remaining_sec": 90.0,
"duration": 90.0,
"duration_sec": 90.0,
"current_stage": 0,
"phase": "idle",
"pause_reason": "",
"recent_events": [],
}
self.logs = []
# --- 复活相关 ---
# 机器人 ID 顺序与 robot_health 列表索引保持一致
default_robot_count = len(self.global_unit_status.get("robot_health", []))
# 机器人 ID 列表:默认使用当前模拟器重点联调的 8 台机器人
# 红方: 1/3/6/7,蓝方: 101/103/106/107
if default_robot_count == 8:
self.robot_ids = [1, 3, 6, 7, 101, 103, 106, 107]
else:
# 兜底使用从 1 开始的连续 ID
self.robot_ids = list(range(1, default_robot_count + 1))
self.robot_injury_stats = {
rid: self._empty_robot_injury_stat() for rid in self.robot_ids
}
# 黄牌统计状态
self.last_yellow_ts = {rid: 0.0 for rid in self.robot_ids}
self.yellow_streak = {rid: 0 for rid in self.robot_ids}
self.yellow_count = {rid: 0 for rid in self.robot_ids}
self.double_yellow_count = 0
# 复活信息以 robot_id 为键保存
self.respawn_info = {}
for rid in self.robot_ids:
self.respawn_info[rid] = {
"is_pending": False, # 是否在复活队列中
"start_ts": 0.0, # 触发时间戳
"total_progress": 0, # 需要的总进度
"current_progress": 0, # 当前进度
"can_free": False, # 是否允许免费复活
"can_pay": False, # 是否允许金币买活
"gold_cost": 100, # 默认金币消耗
"immediate_exchange_count": 0, # 累计立即复活次数
"is_dead": False, # 是否处于死亡状态
"last_immediate_ts": 0.0, # 最近一次立即复活时间戳
"notified_complete": False # 读条完成是否已通知(防止重复入队)
}
# 进度推进时间基准
self._last_respawn_tick = time.time()
# 默认最大 HP(与初始化 robot_health 保持一致)
self._default_robot_max_hp = 600
self._default_respawn_gold_cost = 100
# --- 飞镖相关 ---
self.dart_status_by_team = {
"red": self._create_dart_status(),
"blue": self._create_dart_status(),
}
self.active_dart_team = "red"
self.dart_status = dict(self.dart_status_by_team[self.active_dart_team])
self.last_buff_status = self._create_buff_status_state()
self.last_event_command = self._create_event_command_state()
self.custom_byte_block_form = self._create_custom_byte_block_form_state()
self.custom_byte_block_hex = ""
self.log("System", "Server Initialized")
@staticmethod
def _create_game_status_state():
return {
"current_round": 1,
"total_rounds": 3,
"red_score": 0,
"blue_score": 0,
"current_stage": 0, # 0: 未开始
"stage_countdown_sec": 300,
"stage_elapsed_sec": 0,
"is_paused": False,
}
@staticmethod
def _create_rune_state():
return {
"rune_status": 1,
"activated_arms": 0,
"average_rings": 0,
"last_rune_activation": "",
}
@staticmethod
def _create_deploy_mode_status_by_team():
return {
"red": 0,
"blue": 0,
}
@staticmethod
def _normalize_rune_type(rune_type):
try:
value = int(rune_type)
except Exception:
text = str(rune_type or "").strip().lower()
return 2 if text in {"large", "big", "2"} else 1
return 2 if value == 2 else 1
@classmethod
def _rune_type_label(cls, rune_type):
return "大能量机关" if cls._normalize_rune_type(rune_type) == 2 else "小能量机关"
@staticmethod
def _create_dart_status():
return {
"target_id": 2,
"open": 0,
"opening_started_ts": 0.0,
"opening_duration_sec": 2.0,
}
@staticmethod
def _create_event_command_state():
return {
"event_id": 14,
"param": "",
}
@staticmethod
def _create_custom_byte_block_form_state():
return {
"encoding": "hex",
"hex_data": "01 02 03 04",
"text_data": "SIM",
}
@staticmethod
def _create_buff_status_state():
return {
"robot_id": 0,
"buff_type": 1,
"buff_level": 1,
"buff_max_time": 30,
"buff_left_time": 30,
}
def _create_robot_static_status_state(self):
return {
"connection_state": 1,
"field_state": 0,
"alive_state": 1,
"robot_id": int(self.current_robot_id or 1),
"robot_type": int(self.current_robot_id or 1) % 100,
"performance_system_shooter": 1,
"performance_system_chassis": 1,
"level": 1,
"max_health": 600,
"max_heat": 240,
"heat_cooldown_rate": 20.0,
"max_power": 120,
"max_buffer_energy": 60,
"max_chassis_energy": 120,
}
@staticmethod
def _create_robot_dynamic_status_state():
return {
"current_health": 600,
"current_heat": 0.0,
"last_projectile_fire_rate": 0.0,
"current_chassis_energy": 0,
"current_buffer_energy": 0,
"current_experience": 100,
"experience_for_upgrade": 1000,
"total_projectiles_fired": 0,
"remaining_ammo": 0,
"is_out_of_combat": False,
"out_of_combat_countdown": 0,
"can_remote_heal": True,
"can_remote_ammo": True,
}
@staticmethod
def _create_robot_module_status_state():
return {
"power_manager": 1,
"rfid": 1,
"light_strip": 1,
"small_shooter": 1,
"big_shooter": 1,
"uwb": 1,
"armor": 1,
"video_transmission": 1,
"capacitor": 1,
"main_controller": 1,
"laser_detection_module": 1,
}
@staticmethod
def _normalize_sentry_posture_id(posture_id):
try:
value = int(posture_id)
except Exception:
value = 1
return value if value in (1, 2, 3) else 1
@classmethod
def _resolve_sentry_command_effect(cls, command_id):
try:
value = int(command_id or 0)
except Exception:
value = 0
command_name_map = {
1: "supply_hp_ammo",
3: "remote_ammo",
4: "remote_heal",
5: "confirm_respawn",
6: "pay_respawn",
7: "attack_posture",
8: "defense_posture",
9: "move_posture",
10: "enhanced_attack_posture",
11: "enhanced_defense_posture",
12: "enhanced_move_posture",
}
posture_map = {
7: 1,
8: 2,
9: 3,
10: 1,
11: 2,
12: 3,
}
return {
"command_id": value,
"name": command_name_map.get(value, "unknown"),
"is_valid": value in command_name_map,
"posture_id": posture_map.get(value),
}
@staticmethod
def _create_global_logistics_status_state():
return {
"red_economy": 550,
"blue_economy": 550,
"red_total_economy_obtained": 550,
"blue_total_economy_obtained": 550,
"red_total_damage": 0,
"blue_total_damage": 0,
"red_tech_level": 1,
"blue_tech_level": 1,
"red_encryption_level": 1,
"blue_encryption_level": 1,
}
@staticmethod
def _create_global_unit_status_state():
return {
"base_health": 5000,
"base_status": 0,
"base_shield": 1000,
"outpost_health": 1500,
"outpost_status": 1,
# --- 分队伍数据 ---
"red_base_health": 5000,
"blue_base_health": 5000,
"red_base_status": 0,
"blue_base_status": 0,
"red_base_shield": 1000,
"blue_base_shield": 1000,
"red_outpost_health": 1500,
"blue_outpost_health": 1500,
"red_outpost_status": 1,
"blue_outpost_status": 1,
"red_outpost_destroyed": False,
"blue_outpost_destroyed": False,
"robot_health": [600] * 8, # 8 个机器人
"robot_max_hp": [600] * 8, # 8 个机器人最大血量
"robot_bullets": [0] * 8,
"robot_heat": [0] * 8,
"robot_heat_manual_hold": [False] * 8,
"robot_fire_rate": [0] * 8,
"robot_speed_over_limit": [False] * 8,
"robot_power_over_limit": [False] * 8,
"robot_level": [1] * 8,
"robot_power": [0] * 8,
"total_damage_red": 0,
"total_damage_blue": 0
}
def _get_robot_fire_rate_limit(self, robot_id):
"""根据机器人类型返回射速上限(m/s)。"""
try:
normalized_id = int(robot_id) % 100
except Exception:
normalized_id = 0
if normalized_id == 1:
return 12.0
if normalized_id == 2:
return 30.0
return 25.0
def _get_robot_power_limit(self, robot_id):
"""返回机器人功率超限阈值(W)。"""
return 120.0
@staticmethod
def _stage_default_countdown(stage):
defaults = {
0: 300,
1: 180,
2: 15,
3: 5,
4: 420,
5: 0,
}
try:
return int(defaults.get(int(stage), 0))
except Exception:
return 0
@staticmethod
def _winner_label(winner):
labels = {
0: "平局",
1: "红方",
2: "蓝方",
}
try:
return labels.get(int(winner), "未知")
except Exception:
return "未知"
@staticmethod
def _empty_robot_injury_stat():
return {
"total_damage": 0,
"collision_damage": 0,
"small_projectile_damage": 0,
"large_projectile_damage": 0,
"dart_splash_damage": 0,
"module_offline_damage": 0,
"offline_damage": 0,
"penalty_damage": 0,
"server_kill_damage": 0,
"killer_id": 0,
}
@staticmethod
def _normalize_robot_performance_value(value, maximum, default=0):
try:
normalized = int(value)
except Exception:
normalized = int(default)
return max(0, min(int(maximum), normalized))
@staticmethod
def _normalize_robot_status_uint(value, default=0, minimum=0, maximum=4294967295):
try:
normalized = int(value)
except Exception:
normalized = int(default)
return max(int(minimum), min(int(maximum), normalized))
@staticmethod
def _normalize_robot_status_float(value, default=0.0, minimum=None, maximum=None):
try:
normalized = float(value)
except Exception:
normalized = float(default)
if minimum is not None:
normalized = max(float(minimum), normalized)
if maximum is not None:
normalized = min(float(maximum), normalized)
return normalized
@staticmethod
def _normalize_robot_status_bool(value, default=False):
if isinstance(value, str):
normalized = value.strip().lower()
if normalized in {"1", "true", "yes", "on"}:
return True
if normalized in {"0", "false", "no", "off"}:
return False
if value is None:
return bool(default)
return bool(value)
@classmethod
def _normalize_robot_injury_stat_payload(cls, payload):
normalized = cls._empty_robot_injury_stat()
for key in normalized.keys():
try:
normalized[key] = max(0, int((payload or {}).get(key, 0) or 0))
except Exception:
normalized[key] = 0
non_small_keys = (
"collision_damage",
"large_projectile_damage",
"dart_splash_damage",
"module_offline_damage",
"offline_damage",
"penalty_damage",
"server_kill_damage",
)
non_small_sum = sum(int(normalized.get(key, 0)) for key in non_small_keys)
total_damage = int(normalized.get("total_damage", 0))
small_projectile_damage = total_damage - non_small_sum
if small_projectile_damage < 0:
total_damage = non_small_sum
small_projectile_damage = 0
normalized["total_damage"] = total_damage
normalized["small_projectile_damage"] = small_projectile_damage
return normalized
def _resolve_robot_id(self, robot_ref):
try:
rid = int(robot_ref)
except Exception:
return None
if rid in self.robot_ids:
return rid
if 0 <= rid < len(self.robot_ids):
return self.robot_ids[rid]
return None
def _record_robot_damage_locked(
self,
robot_index,
damage,
*,
damage_key="penalty_damage",
killer_id=0,
):
try:
damage_value = max(0, int(damage))
except Exception:
return
if damage_value <= 0 or not (0 <= robot_index < len(self.robot_ids)):
return
rid = self.robot_ids[robot_index]
stats = self.robot_injury_stats.setdefault(
rid, self._empty_robot_injury_stat()
)
stats["total_damage"] = int(stats.get("total_damage", 0)) + damage_value
if damage_key in stats:
stats[damage_key] = int(stats.get(damage_key, 0)) + damage_value
stats["killer_id"] = max(0, int(killer_id or 0))
def can_pay_for_respawn(self, robot_id, cost):
"""
检查指定机器人是否有足够的金币支付复活费用。
参数 robot_id: 机器人 id(与 self.robot_ids 中的 id 对应)
参数 cost: 需要支付的金币数(int)
返回: bool - 是否可以支付
"""
try:
if cost is None:
return False
cost = int(cost)
except Exception:
return False
# 根据机器人 id 判断队伍(小于 100 视为红,>=100 视为蓝)
try:
team = "blue" if int(robot_id) >= 100 else "red"
except Exception:
team = "red"
if team == "red":
econ = self.global_logistics_status.get("red_economy", 0)
else:
econ = self.global_logistics_status.get("blue_economy", 0)
try:
econ = int(econ)
except Exception:
econ = 0
return econ >= cost
@staticmethod
def _clamp(value, minimum, maximum):
return max(minimum, min(maximum, int(value)))
@classmethod
def _clamp_base_hp(cls, hp):
hp = cls._clamp(hp, 0, cls.BASE_HP_MAX)
return int(round(hp / cls.BASE_HP_STEP) * cls.BASE_HP_STEP)
@staticmethod
def _normalize_team(team):
if isinstance(team, str):
value = team.strip().lower()
if value in ("blue", "b", "2", "enemy"):
return "blue"
if team == 2:
return "blue"
return "red"
def _current_team_name(self):
try:
return "blue" if int(self.current_robot_id or 1) >= 100 else "red"
except Exception:
return "red"
def start(self):
self.running = True
self.log("System", "Simulation Started")
threading.Thread(target=self._update_loop, daemon=True).start()
def stop(self):
self.running = False
self.log("System", "Simulation Stopped")
def _update_loop(self):
while self.running:
time.sleep(1)
with self.lock:
now = time.time()
if self.game_status["is_paused"]:
self._last_respawn_tick = now # 暂停时不推进复活进度,重置基准时间
continue
stage = self.game_status["current_stage"]
# 一键赛事演示由单调时钟以 10 Hz 原子写入阶段,避免与这里的 1 Hz
# 传统倒计时重复推进;其余热量、复活等后台状态仍沿用本循环。
if (
not self._match_simulation_clock_active
and stage in [1, 2, 3, 4]
): # 有倒计时的阶段
self.game_status["stage_countdown_sec"] -= 1
self.game_status["stage_elapsed_sec"] += 1
# 阶段自动转换
if self.game_status["stage_countdown_sec"] <= 0:
if stage == 1: # 准备阶段结束 -> 自检阶段
self.game_status["current_stage"] = 2
self.game_status["stage_countdown_sec"] = 15
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "自动进入自检阶段 (Stage 2)")
elif stage == 2: # 自检阶段结束 -> 五秒倒计时
self.game_status["current_stage"] = 3
self.game_status["stage_countdown_sec"] = 5
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "自动进入五秒倒计时 (Stage 3)")
elif stage == 3: # 五秒倒计时结束 -> 比赛开始
self.game_status["current_stage"] = 4
self.game_status["stage_countdown_sec"] = 420
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "比赛开始! (Stage 4)")
elif stage == 4: # 比赛时间结束 -> 结算
self.game_status["current_stage"] = 5
self.game_status["stage_countdown_sec"] = 0
self.game_status["stage_elapsed_sec"] = 0
self.game_status["is_paused"] = False
self.log("Referee", "比赛时间结束,进入结算阶段 (Stage 5)")
self.pending_game_result_reason = "比赛时间结束"
self.pending_game_result_end_reason = 1
self._enqueue_game_result()
# 热量自动冷却:统一 30/s
try:
robot_heat = self.global_unit_status.get("robot_heat", [])
robot_fire_rate = self.global_unit_status.get("robot_fire_rate", [])
robot_speed_over_limit = self.global_unit_status.get("robot_speed_over_limit", [])
robot_power = self.global_unit_status.get("robot_power", [])
robot_power_over_limit = self.global_unit_status.get("robot_power_over_limit", [])
robot_heat_manual_hold = self.global_unit_status.get("robot_heat_manual_hold", [])
for i in range(len(robot_heat)):
h = int(robot_heat[i])
is_manual_hold = bool(robot_heat_manual_hold[i]) if i < len(robot_heat_manual_hold) else False
if h > 0 and not is_manual_hold:
robot_heat[i] = max(0, h - 30)
# 检查热量上限并发送判罚 (超限)
if robot_heat[i] > 240:
try:
rid = self.robot_ids[i]
self.warning_queue.append({
"type": "referee_warning",
"level": 5, # 5 对应 PenaltyInfo penalty_type=5
"offending_robot_id": rid,
"count": 1
})
self.log("Referee", f"Robot {rid} overheated! Heat: {robot_heat[i]} > 240. Issuing level 5 penalty.")
except Exception:
pass
# 检查射速上限并发送判罚(超限 -> penalty_type=6)
try:
current_fire_rate = float(robot_fire_rate[i]) if i < len(robot_fire_rate) else 0.0
rid = self.robot_ids[i]
fire_rate_limit = self._get_robot_fire_rate_limit(rid)
was_over_limit = bool(robot_speed_over_limit[i]) if i < len(robot_speed_over_limit) else False
is_over_limit = current_fire_rate > fire_rate_limit
if i < len(robot_speed_over_limit):
robot_speed_over_limit[i] = is_over_limit
if is_over_limit and not was_over_limit:
self.warning_queue.append({
"type": "referee_warning",
"level": 6,
"offending_robot_id": rid,
"count": 1
})
self.log(
"Referee",
f"Robot {rid} fire rate over limit! FireRate: {current_fire_rate} > {fire_rate_limit}. Issuing level 6 penalty."
)
except Exception:
pass
# 检查功率上限并发送判罚(超限 -> penalty_type=4)
try:
current_power = float(robot_power[i]) if i < len(robot_power) else 0.0
rid = self.robot_ids[i]
power_limit = self._get_robot_power_limit(rid)
was_power_over_limit = bool(robot_power_over_limit[i]) if i < len(robot_power_over_limit) else False
is_power_over_limit = current_power > power_limit
if i < len(robot_power_over_limit):
robot_power_over_limit[i] = is_power_over_limit
if is_power_over_limit and not was_power_over_limit:
self.warning_queue.append({
"type": "referee_warning",
"level": 4,
"offending_robot_id": rid,
"count": 1
})
self.log(
"Referee",
f"Robot {rid} power over limit! Power: {current_power} > {power_limit}. Issuing level 4 penalty."
)
except Exception:
pass
except Exception as e:
self.log("Referee", f"Heat cooldown error: {e}")
# --- 复活进度推进(按时间戳差值计算,每秒推进 1)---
delta_sec = int(now - self._last_respawn_tick)
if delta_sec > 0:
for rid, info in list(self.respawn_info.items()):
if info.get("is_pending"):
info["current_progress"] += delta_sec * 1
# 检查是否完成:不再自动复活,等待手动确认
if info["current_progress"] >= info.get("total_progress", 0):
info["current_progress"] = info.get("total_progress", info["current_progress"])
info["can_free"] = True # 读条完成后允许免费复活
# 仅首次读条完成时入队通知,保持 is_pending=True,is_dead=True 由确认指令处理
if not info.get("notified_complete", False):
robot_index = None
try:
robot_index = self.robot_ids.index(rid)
except ValueError:
robot_index = None
self.event_queue.append({
"id": 201,
"robot_id": rid,
"robot_index": robot_index,
"type": "robot_respawn_status",
"is_pending": True
})
info["notified_complete"] = True
# 更新基准时间,避免浮点累积
self._last_respawn_tick += delta_sec
# --- Dart 开闸推进 ---
for team_name, dart_status in self.dart_status_by_team.items():
if int(dart_status.get("open", 0)) != 1:
continue
started_ts = float(dart_status.get("opening_started_ts", 0.0))
opening_duration = float(dart_status.get("opening_duration_sec", 2.0))
if started_ts > 0.0 and (now - started_ts) >= opening_duration:
dart_status["open"] = 2
self.log("Referee", f"{team_name.upper()} dart gate state -> opened (2)")
self.dart_status = dict(
self.dart_status_by_team.get(
self.active_dart_team, self._create_dart_status()
)
)
active_team = str(self.air_support.get("active_team", "")).strip().lower()
if active_team in ("red", "blue"):
left_key = f"{active_team}_left_time"
status_key = f"{active_team}_status"
cost_key = f"{active_team}_cost_coins"
mode_key = f"{active_team}_mode"
remaining = max(0, int(self.air_support.get(left_key, 0)))
mode_name = str(self.air_support.get(mode_key, "free")).strip().lower()
if remaining > 0:
self.air_support[left_key] = remaining - 1
elif mode_name == "paid":
self.air_support[left_key] = 0
self.air_support[cost_key] = max(
0, int(self.air_support.get(cost_key, 0))
) + 1
else:
self.air_support[left_key] = 0
self.air_support[status_key] = 0
self.air_support["active_team"] = ""
self.log("Referee", f"Air support finished automatically for {active_team}")
# Buff 剩余时间倒计时
buff_status = self.last_buff_status
if int(buff_status.get("buff_left_time", 0)) > 0:
buff_status["buff_left_time"] = max(
0, int(buff_status.get("buff_left_time", 0)) - 1
)
if buff_status["buff_left_time"] == 0:
self.log(
"Referee",
f"Buff expired: robot_id={buff_status.get('robot_id', 0)} type={buff_status.get('buff_type', 0)}",
)
mechanism_time_sec = list(
self.global_special_mechanism.get("mechanism_time_sec", [0, 0])
)
mechanism_finished = []
for index, remaining in enumerate(mechanism_time_sec[:2]):
remaining_value = max(0, int(remaining or 0))
if remaining_value <= 0:
mechanism_time_sec[index] = 0
continue
next_value = remaining_value - 1
mechanism_time_sec[index] = next_value
if next_value == 0:
mechanism_finished.append("ally" if index == 0 else "enemy")
self.global_special_mechanism["mechanism_time_sec"] = mechanism_time_sec
for team_name in mechanism_finished:
self.log(
"Referee",
f"{team_name} fortress capture countdown finished",
)
# --- 裁判动作 ---
def start_match(self):
"""
开始比赛流程
按照官方协议阶段流转: 0(未开始) -> 1(准备阶段) -> 2(自检阶段) -> 3(五秒倒计时) -> 4(比赛中) -> 5(结算)
"""
with self.lock:
if self.game_status["current_stage"] == 0:
# 从未开始 -> 准备阶段
self.game_status["current_stage"] = 1 # 准备阶段
self.game_status["stage_countdown_sec"] = 180 # 准备阶段 3 分钟
self.game_status["stage_elapsed_sec"] = 0
self.game_status["is_paused"] = False
self.log("Referee", "进入准备阶段 (Stage 1)")
elif self.game_status["current_stage"] == 1:
# 准备阶段 -> 自检阶段
self.game_status["current_stage"] = 2 # 自检阶段
self.game_status["stage_countdown_sec"] = 15 # 15秒自检
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "进入自检阶段 (Stage 2)")
elif self.game_status["current_stage"] == 2:
# 自检阶段 -> 五秒倒计时
self.game_status["current_stage"] = 3 # 五秒倒计时
self.game_status["stage_countdown_sec"] = 5
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "进入五秒倒计时 (Stage 3)")
elif self.game_status["current_stage"] == 3:
# 五秒倒计时 -> 比赛中
self.game_status["current_stage"] = 4 # 比赛中
self.game_status["stage_countdown_sec"] = 420 # 7分钟比赛
self.game_status["stage_elapsed_sec"] = 0
self.log("Referee", "比赛开始! (Stage 4)")
elif self.game_status["current_stage"] == 5:
# 结算阶段:再次点击“开始比赛”进入下一轮(仅当未到最后一轮)
current_round = int(self.game_status.get("current_round", 1))
total_rounds = max(1, int(self.game_status.get("total_rounds", 1)))
if current_round < total_rounds:
self.game_status["current_round"] = current_round + 1
# 进入下一轮时保留当前大比分(red_score/blue_score)
self._reset_game_state(reset_series_score=False)
self.game_status["current_stage"] = 1 # 准备阶段
self.game_status["stage_countdown_sec"] = 180 # 准备阶段 3 分钟
self.log("Referee", f"进入第 {self.game_status['current_round']} 轮准备阶段 (Stage 1)")
else:
# 最后一轮结算完成后点击“开始比赛”回到未开始状态
self._reset_game_state()
self.game_status["current_stage"] = 0 # 回到未开始状态
self.game_status["stage_countdown_sec"] = self._stage_default_countdown(0)
self.game_status["stage_elapsed_sec"] = 0
self.game_status["is_paused"] = False
self.log("Referee", "已是最后一轮结算,点击开始比赛回到未开始状态")
'''
elif self.game_status["current_stage"] in [4, 5]:
# 如果在比赛中或结算阶段,重置为未开始状态,然后进入准备阶段
self._reset_game_state()
self.game_status["current_stage"] = 1 # 准备阶段
self.game_status["stage_countdown_sec"] = 180 # 准备阶段 3 分钟
self.log("Referee", "重置比赛,进入准备阶段 (Stage 1)")
'''
def skip_to_battle(self):
with self.lock:
previous_stage = int(self.game_status.get("current_stage", 0))
self.game_status["current_stage"] = 4
self.game_status["stage_countdown_sec"] = 420
self.game_status["stage_elapsed_sec"] = 0
self.game_status["is_paused"] = False
self.log("Referee", f"Skip to battle stage: {previous_stage} -> 4")
def _reset_game_state(self, reset_series_score=True):
"""重置比赛状态到初始值"""
if reset_series_score:
self.game_status["red_score"] = 0
self.game_status["blue_score"] = 0
self.global_logistics_status = self._create_global_logistics_status_state()
self.game_status["stage_countdown_sec"] = self._stage_default_countdown(
self.game_status.get("current_stage", 0)
)
self.game_status["stage_elapsed_sec"] = 0
self.game_status["is_paused"] = False
self._game_result_enqueued = False
self.penalty_counts = {}
self.event_queue.clear()
self.warning_queue.clear()
self.game_result_queue.clear()
self.last_yellow_ts = {rid: 0.0 for rid in self.robot_ids}
self.yellow_streak = {rid: 0 for rid in self.robot_ids}
self.yellow_count = {rid: 0 for rid in self.robot_ids}
self.double_yellow_count = 0
# 重置血量
self.global_unit_status["robot_max_hp"] = [self._default_robot_max_hp] * len(self.global_unit_status["robot_health"])
for i in range(len(self.global_unit_status["robot_health"])):
self.global_unit_status["robot_health"][i] = int(self.global_unit_status["robot_max_hp"][i])
self.global_unit_status["robot_bullets"][i] = 0
self.global_unit_status["robot_heat"][i] = 0
self.global_unit_status["robot_heat_manual_hold"][i] = False
self.global_unit_status["robot_fire_rate"][i] = 0
self.global_unit_status["robot_speed_over_limit"][i] = False
self.global_unit_status["robot_power_over_limit"][i] = False