Repository navigation
Expand file tree
/
Copy pathGameData.cpp
More file actions
5194 lines (4654 loc) · 188 KB
/
Copy pathGameData.cpp
File metadata and controls
5194 lines (4654 loc) · 188 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
// SPDX-License-Identifier: MIT
/**
* @file GameData.cpp
* @brief 比赛数据中心实现
* @details 实现了比赛数据的初始化、更新、查询和统计功能。
* @author Clear
* @date 2025-11-29
* @copyright Copyright (c) 2025 Fudan University EGA Team (复旦大学星云 EGA 机器人战队).
*/
#include "GameData.h"
#include "robomaster.pb.h"
#include "GameConstants.h"
#include <QColor>
#include <QDebug>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <algorithm>
#include <cmath>
#include "PopupStateMachine.h"
static QString getRobotName(int robotId);
static QString getRobotColor(int robotId);
namespace {
float sanitizeFiniteRuneAverage(float value) {
if (std::isfinite(static_cast<double>(value))) {
return value;
}
return 0.0f;
}
RobotType robotTypeFromProtocolId(quint32 robotId, quint32 fallbackType) {
const quint32 normalizedId = robotId % 100;
switch (normalizedId) {
case 1:
return RobotType::HERO;
case 2:
return RobotType::ENGINEER;
case 3:
return RobotType::INFANTRY_3;
case 4:
return RobotType::INFANTRY_4;
case 5:
return RobotType::INFANTRY_5;
case 6:
return RobotType::AERIAL;
case 7:
return RobotType::SENTRY;
default:
break;
}
switch (fallbackType) {
case 1:
return RobotType::HERO;
case 2:
return RobotType::ENGINEER;
case 3:
return RobotType::INFANTRY_3;
case 4:
return RobotType::INFANTRY_4;
case 5:
return RobotType::INFANTRY_5;
case 6:
return RobotType::AERIAL;
case 7:
return RobotType::SENTRY;
case 8:
return RobotType::DART;
case 9:
return RobotType::RADAR;
default:
return RobotType::INFANTRY_3;
}
}
QList<int> radarRobotOrderForPerspective(bool isBluePerspective) {
const QList<int> redOrder{1, 2, 3, 4, 6, 7};
const QList<int> blueOrder{101, 102, 103, 104, 106, 107};
return isBluePerspective ? (redOrder + blueOrder) : (blueOrder + redOrder);
}
QString dartTargetName(int targetId) {
switch (targetId) {
case 1:
return QStringLiteral("前哨站");
case 2:
return QStringLiteral("基地固定目标");
case 3:
return QStringLiteral("基地随机固定目标");
case 4:
return QStringLiteral("基地随机移动目标");
case 5:
return QStringLiteral("基地末端移动目标");
default:
return QStringLiteral("未知目标");
}
}
QString assemblyResultText(int resultCode) {
switch (resultCode) {
case 0:
return QStringLiteral("装配成功");
case 1:
return QStringLiteral("能量单元拔出,装配失败");
case 2:
return QStringLiteral("装配超时,装配失败");
case 3:
return QStringLiteral("离开装配区过久,装配失败");
case 4:
return QStringLiteral("工程战亡,装配失败");
case 5:
return QStringLiteral("四级难度未满足完成协作时限,装配失败");
case 6:
return QStringLiteral("主动退出装配,装配失败");
case 7:
return QStringLiteral("装配完成但未检测到能量单元");
case 8:
return QStringLiteral("缓冲期到期,装配流程强制结束");
default:
return QStringLiteral("装配结果未知");
}
}
QString airSupportCounteredText(const QString ¶m) {
bool ok = false;
const int remainingCounterCount = param.toInt(&ok);
if (ok) {
return QStringLiteral("对方空中支援被反制,己方剩余可反制次数 %1")
.arg(remainingCounterCount);
}
return QStringLiteral("对方空中支援被反制");
}
QString normalizedSystemMessageColor(const QString &color) {
static const QString kDefaultColor = QStringLiteral("#E5E5E5");
if (color.isEmpty()) {
return kDefaultColor;
}
const QColor parsedColor(color);
return parsedColor.isValid() ? color : kDefaultColor;
}
float robotShootSpeedLimit(RobotType type) {
switch (type) {
case RobotType::HERO:
return static_cast<float>(RM::RobotStats::HERO_BULLET_SPEED_LIMIT);
case RobotType::INFANTRY_3:
case RobotType::INFANTRY_4:
case RobotType::INFANTRY_5:
case RobotType::AERIAL:
case RobotType::SENTRY:
return static_cast<float>(RM::RobotStats::ROBOT_BULLET_SPEED_LIMIT);
case RobotType::ENGINEER:
case RobotType::DART:
case RobotType::RADAR:
default:
return 0.0f;
}
}
quint16 robotTabShootSpeedLimit(RobotType type) {
return static_cast<quint16>(robotShootSpeedLimit(type));
}
QString robotTabAvatarSource(const RobotData &robot) {
const QString teamPrefix =
robot.team == TeamColor::BLUE ? QStringLiteral("blue")
: QStringLiteral("red");
switch (robot.type) {
case RobotType::HERO:
return QStringLiteral("qrc:/images/top_robots/%1_teammate_avatar_hero.png")
.arg(teamPrefix);
case RobotType::ENGINEER:
return QStringLiteral(
"qrc:/images/top_robots/%1_teammate_avatar_engineer.png")
.arg(teamPrefix);
case RobotType::INFANTRY_3:
case RobotType::INFANTRY_4:
case RobotType::INFANTRY_5:
return QStringLiteral(
"qrc:/images/top_robots/%1_teammate_avatar_soldier.png")
.arg(teamPrefix);
case RobotType::AERIAL:
return QStringLiteral(
"qrc:/images/top_robots/%1_teammate_avatar_airplane.png")
.arg(teamPrefix);
case RobotType::SENTRY:
return QStringLiteral("qrc:/images/top_robots/%1_guard_avatar.png")
.arg(teamPrefix);
default:
return QStringLiteral("qrc:/images/robot_avatar.png");
}
}
quint16 robotTabDefaultMaxHp(RobotType type) {
switch (type) {
case RobotType::HERO:
return 200;
case RobotType::ENGINEER:
return 250;
case RobotType::INFANTRY_3:
case RobotType::INFANTRY_4:
case RobotType::INFANTRY_5:
return 200;
case RobotType::AERIAL:
return 250;
case RobotType::SENTRY:
return 600;
default:
return 0;
}
}
bool robotConnectedForTab(const RobotData &robot) {
const bool hasStaticConnection = robot.tabStaticConnected;
const bool hasGlobalHealth =
robot.hasTabGlobalSnapshot && robot.tabGlobalCurrentHP > 0;
return hasStaticConnection || hasGlobalHealth;
}
quint16 robotDisplayHpForPanels(const RobotData &robot) {
if (robot.hasTabGlobalSnapshot && robot.tabGlobalCurrentHP > 0) {
return robot.tabGlobalCurrentHP;
}
return robotConnectedForTab(robot) ? robot.currentHP : 0;
}
quint16 robotDisplayMaxHpForPanels(const RobotData &robot) {
if (!robotConnectedForTab(robot)) {
return 0;
}
return robot.maxHP > 0 ? robot.maxHP : robotTabDefaultMaxHp(robot.type);
}
quint8 robotDisplayLevelForPanels(const RobotData &robot) {
return robotConnectedForTab(robot)
? static_cast<quint8>(std::max(1, static_cast<int>(robot.level)))
: 0;
}
//根据bufftype获取buff指针
const RobotData::BuffTimedData *timedBuffByType(const RobotData *robot, quint8 buffType) {
return robot ? robot->buffs.byType(buffType) : nullptr;
}
RobotData::BuffTimedData *timedBuffByType(RobotData *robot, quint8 buffType) {
return robot ? robot->buffs.byType(buffType) : nullptr;
}
//打包buff信息
QVariantMap toBuffTimedVariant(quint8 buffType,
const RobotData::BuffTimedData *state) {
QVariantMap map;
map["type"] = static_cast<int>(buffType);
map["level"] = state ? static_cast<int>(state->level) : 0;
map["maxTime"] = state ? static_cast<int>(state->maxTime) : 0;
map["leftTime"] = state ? static_cast<int>(state->leftTimeAtSync) : 0;
return map;
}
QVariantMap toBuffTimedVariant(quint8 buffType, int level, int maxTime, int leftTime) {
QVariantMap map;
map["type"] = static_cast<int>(buffType);
map["level"] = level;
map["maxTime"] = qMax(0, maxTime);
map["leftTime"] = qMax(0, leftTime);
return map;
}
//机器人基础id
constexpr quint8 kRadarRobotBaseIds[] = {1, 2, 3, 4, 6, 7};
//根据红蓝方和机器人基础id获取机器人id
quint8 teamRobotId(quint8 baseId, TeamColor team) {
return (team == TeamColor::RED) ? baseId : static_cast<quint8>(baseId + 100);
}
//当前是否是正式比赛阶段
bool isBattleStage(GameStage stage) {
return stage != GameStage::NOT_STARTED &&
stage != GameStage::PREPARATION &&
stage != GameStage::SELF_CHECK &&
stage != GameStage::COUNTDOWN &&
stage != GameStage::SETTLEMENT;
}
QString officialEventPopupMessageForEvent(const robomaster::Event &data,
const RobotData *currentRobot,
int currentRuneType) {
const int eventId = data.event_id();
const QString param = QString::fromStdString(data.param()).trimmed();
const TeamColor currentTeam = currentRobot ? currentRobot->team : TeamColor::RED;
auto teamText = [](TeamColor team) {
return team == TeamColor::RED ? QStringLiteral("红") : QStringLiteral("蓝");
};
switch (eventId) {
case 1: {
const QStringList parts = param.split(",");
if (parts.size() == 2) {
bool okVictim = false;
bool okKiller = false;
const quint8 victimId = static_cast<quint8>(parts[0].toUInt(&okVictim));
const quint8 killerId = static_cast<quint8>(parts[1].toUInt(&okKiller));
if (okVictim && okKiller) {
if (killerId % 100 == 10 || killerId == victimId) {
const TeamColor victimTeam = victimId >= 100 ? TeamColor::BLUE : TeamColor::RED;
return QStringLiteral("%1方%2机器人阵亡")
.arg(teamText(victimTeam), getRobotName(victimId));
}
const TeamColor killerTeam = killerId >= 100 ? TeamColor::BLUE : TeamColor::RED;
const TeamColor victimTeam = victimId >= 100 ? TeamColor::BLUE : TeamColor::RED;
return QStringLiteral("%1方%2机器人击毁了%3方%4机器人")
.arg(teamText(killerTeam), getRobotName(killerId),
teamText(victimTeam), getRobotName(victimId));
}
}
return QStringLiteral("机器人击毁事件");
}
case 2: {
bool ok = false;
const uint targetId = param.toUInt(&ok);
if (ok) {
if (targetId == 11) {
return QStringLiteral("红方前哨站被摧毁");
}
if (targetId == 111) {
return QStringLiteral("蓝方前哨站被摧毁");
}
}
return QStringLiteral("前哨站被摧毁");
}
case 3: {
const QStringList parts = param.split(",");
if (parts.size() >= 2) {
bool okArms = false;
const int activatedArms = parts[0].trimmed().toInt(&okArms);
bool okAvg = false;
const float averageRings = parts[1].trimmed().toFloat(&okAvg);
if (okArms && okAvg) {
QString msg =
QStringLiteral("能量机关状态更新:已激活%1个灯臂,平均环数%2")
.arg(activatedArms)
.arg(QString::number(averageRings, 'f', 1));
// 附加各组环数/增量对
QStringList groupParts;
for (int i = 2; i + 1 < parts.size(); i += 2) {
bool okGAvg = false;
const float gAvg = parts[i].trimmed().toFloat(&okGAvg);
bool okDelta = false;
const int gDelta = parts[i + 1].trimmed().toInt(&okDelta);
if (okGAvg) {
groupParts.append(QStringLiteral("%1/Δ%2").arg(
QString::number(gAvg, 'f', 1)).arg(gDelta));
}
}
if (!groupParts.isEmpty()) {
msg += QStringLiteral(",各组 ") + groupParts.join(QStringLiteral(", "));
}
return msg;
}
}
if (!parts.isEmpty()) {
bool ok = false;
const int activatedArms = parts[0].trimmed().toInt(&ok);
if (ok) {
return QStringLiteral("能量机关状态更新:已激活%1个灯臂").arg(activatedArms);
}
}
return QStringLiteral("能量机关状态更新");
}
case 4: {
bool ok = false;
const int protocolRuneType = param.toInt(&ok);
const int resolvedRuneType = ok ? ((protocolRuneType == 2) ? 1 : 0) : currentRuneType;
return QStringLiteral("%1方激活了%2能量机关")
.arg(teamText(currentTeam), resolvedRuneType == 0 ? QStringLiteral("小")
: QStringLiteral("大"));
}
case 5:
return QStringLiteral("己方英雄累计造成狙击伤害 %1").arg(param);
case 6:
return QStringLiteral("对方英雄累计造成狙击伤害 %1").arg(param);
case 7: {
if (param.compare("RED", Qt::CaseInsensitive) == 0) {
return QStringLiteral("红方呼叫了空中支援");
}
if (param.compare("BLUE", Qt::CaseInsensitive) == 0) {
return QStringLiteral("蓝方呼叫了空中支援");
}
if (param.isEmpty()) {
return QStringLiteral("对方呼叫了空中支援");
}
return QStringLiteral("空中支援事件");
}
case 8:
return airSupportCounteredText(param);
case 9: {
QString normalizedParam = param;
normalizedParam.replace(QStringLiteral(","), QStringLiteral(","));
const QStringList parts = normalizedParam.split(",");
bool okTeam = false;
bool okTarget = false;
const int hitTeam = parts.value(0).trimmed().toInt(&okTeam);
const int targetId = parts.value(1).trimmed().toInt(&okTarget);
if (okTeam && okTarget) {
return QStringLiteral("%1方飞镖命中%2")
.arg(hitTeam == 1 ? QStringLiteral("红") : QStringLiteral("蓝"),
dartTargetName(targetId));
}
return QStringLiteral("飞镖命中事件");
}
case 10:
return QStringLiteral("对方飞镖闸门开启");
case 11:
return QStringLiteral("基地遭受攻击");
case 12:
return QStringLiteral("对方前哨站停转");
case 13:
return QStringLiteral("对方基地护甲展开");
case 14:
return QStringLiteral("对方请求四级装配,进入强制退出缓冲期");
case 15: {
bool ok = false;
const int result = param.toInt(&ok);
if (ok) {
return QStringLiteral("装配结果:%1").arg(assemblyResultText(result));
}
return QStringLiteral("装配流程状态更新");
}
case 100:
return param.isEmpty() ? QStringLiteral("自定义事件通知") : param;
case 2000:
return QStringLiteral("比赛结果已更新");
case 3001:
return QStringLiteral("全员踢出状态已开启");
case 3002:
return QStringLiteral("全员踢出状态已解除");
default:
return QString();
}
}
} // namespace
/**
* @brief 构造函数
* @details 初始化比赛数据,包括机器人、基地、增益点等,并启动定时器。
*
* @param parent 父对象
*/
GameData::GameData(QObject *parent)
: QObject(parent), m_currentRobotId(1), m_gameTimer(new QTimer(this)) {
initializeRobots();
// 初始化基地数据
m_redBase.team = TeamColor::RED;
m_redBase.currentHP = 5000;
m_redBase.maxHP = 5000;
m_blueBase.team = TeamColor::BLUE;
m_blueBase.currentHP = 5000;
m_blueBase.maxHP = 5000;
m_totalKills = 0;
// 初始化前哨站数据
m_redOutpostData.team = TeamColor::RED;
m_redOutpostData.currentHP = 1500;
m_redOutpostData.maxHP = 1500;
m_redOutpostData.isDestroyed = false;
m_blueOutpostData.team = TeamColor::BLUE;
m_blueOutpostData.currentHP = 1500;
m_blueOutpostData.maxHP = 1500;
m_blueOutpostData.isDestroyed = false;
// 初始化比赛状态
m_gameState.gameTime = 420; // 7分钟
m_gameState.currentRound = 1;
m_gameState.gameProgress = GameStage::NOT_STARTED;
m_gameState.gameStarted = false;
m_gameState.gameEnded = false;
// 初始化增益点
m_buffPoints.clear();
for (int i = 0; i < 3; ++i) { // 通常有3个增益点
BuffPointData buffPoint;
buffPoint.pointId = i + 1;
buffPoint.energyValue = 0;
buffPoint.maxEnergyValue = 1000;
buffPoint.isActivated = false;
buffPoint.controllingTeam = TeamColor::RED;
m_buffPoints.append(buffPoint);
}
// 初始化哨兵状态
m_redSentry.isAlive = true;
m_redSentry.currentHP = 600;
m_redSentry.maxHP = 600;
m_redSentry.isInvincible = false;
m_blueSentry.isAlive = true;
m_blueSentry.currentHP = 600;
m_blueSentry.maxHP = 600;
m_blueSentry.isInvincible = false;
// 设置定时器
connect(m_gameTimer, &QTimer::timeout, this, &GameData::onUpdateTimer);
m_gameTimer->start(100); // 100ms更新一次
// 连接信号以触发无参数的 QML 代理信号
connect(this, &GameData::baseHealthUpdated, this,
[this](TeamColor) { emit baseHealthUpdatedProxy(); });
connect(this, &GameData::outpostHealthUpdated, this,
[this](TeamColor) { emit outpostHealthUpdatedProxy(); });
connect(this, &GameData::outpostRebuildCountChanged, this,
[this]() { emit outpostRebuildCountProxy(); });
connect(this, &GameData::gameStateUpdated, this, [this]() {
emit baseHealthUpdatedProxy();
}); // GameState更新也可能影响基地无敌状态
// 初始化弹窗状态机,用于集中管理弹窗展现逻辑
m_popupStateMachine = new PopupStateMachine(this);
connect(m_popupStateMachine, &PopupStateMachine::activePopupsChanged, this,
&GameData::onPopupStateMachineUpdated);
connect(m_popupStateMachine, &PopupStateMachine::popupPayloadChanged, this,
&GameData::onPopupPayloadFromStateMachine);
// 初始化 UI 刷新定时器,用于驱动脱战倒计时等随时间变化的状态
m_uiRefreshTimer = new QTimer(this);
connect(m_uiRefreshTimer, &QTimer::timeout, this, [this]() {
// 检查当前机器人是否处于非脱战状态,如果是,则每秒通知 UI 重新读取倒计时
const RobotData *robot = getCurrentRobot();
emit myRobotUpdated();
});
m_uiRefreshTimer->start(1000); // 1秒一次
}
QImage GameData::heroFrame() const {
QMutexLocker locker(&m_mutex);
return m_heroFrame;
}
bool GameData::hasHeroFrame() const {
QMutexLocker locker(&m_mutex);
return !m_heroFrame.isNull();
}
void GameData::onVideoFrameReceived(const QImage &frame) {
{
QMutexLocker locker(&m_mutex);
m_heroFrame = frame;
++m_heroFrameRevision;
m_heroFrameDataUrl.clear();
}
emit heroFrameUpdated();
}
void GameData::clearHeroFrame() {
{
QMutexLocker locker(&m_mutex);
m_heroFrame = QImage();
++m_heroFrameRevision;
m_heroFrameDataUrl.clear();
}
qDebug() << "[herovideo] GameData: Cleared hero frame";
emit heroFrameUpdated();
}
quint64 GameData::heroFrameRevision() const {
QMutexLocker locker(&m_mutex);
return m_heroFrameRevision;
}
QString GameData::heroFrameSource() const {
QMutexLocker locker(&m_mutex);
if (m_heroFrame.isNull()) {
return QString();
}
return QStringLiteral("image://herovideo/frame?rev=%1").arg(m_heroFrameRevision);
}
QString GameData::heroFrameDataUrl() const {
QMutexLocker locker(&m_mutex);
return m_heroFrameDataUrl;
}
/**
* @brief 初始化机器人数据
* @details 创建红蓝双方共14个机器人的初始数据,设定ID、类型、血量上限等。
*/
void GameData::initializeRobots() {
m_robots.clear();
// 红方机器人
for (int i = 1; i <= 7; ++i) {
if(i ==5){
continue;
}
RobotData robot;
robot.robotId = i;
robot.team = TeamColor::RED;
switch (i) {
case 1:
robot.type = RobotType::HERO;
robot.maxHP = 200;
robot.heroRigMode = 0;
break;
case 2:
robot.type = RobotType::ENGINEER;
robot.maxHP = 250;
break;
case 3:
robot.type = RobotType::INFANTRY_3;
robot.maxHP = 200;
robot.infantry17mmMode = 0;
break;
case 4:
robot.type = RobotType::INFANTRY_4;
robot.maxHP = 200;
robot.infantry17mmMode = 0;
break;
case 6:
robot.type = RobotType::AERIAL;
robot.maxHP = 250;
break;
case 7:
robot.type = RobotType::SENTRY;
robot.maxHP = 200;
break;
}
// 未收到真实静态状态前,默认按"未知且离线"处理,避免顶部列表预亮。
robot.maxHP = 0;
robot.currentHP = 0;
robot.status = RobotStatus::OFFLINE;
robot.level = 1;
robot.experience = 0;
robot.maxExperience = 100;
robot.maxPower = 0;
robot.power = 0;
robot.heatLimit = 0;
robot.currentHeat = 0;
robot.isClientConnected = false;
robot.isControllerConnected = false;
robot.allowedAmmo17mm = 0;
robot.allowedAmmo42mm = 0;
robot.fortressBonusAmmo = 0;
robot.shootSpeedLimit = 0.0f;
robot.tabShootSpeedLimit = 0;
robot.lastUpdateTime = QDateTime::currentDateTime();
robot.q2HeatThreshold = robot.heatLimit + 100;
m_robots.append(robot);
}
// 蓝方机器人
for (int i = 101; i <= 107; ++i) {
if(i ==105){
continue;
}
RobotData robot;
robot.robotId = i;
robot.team = TeamColor::BLUE;
switch (i) {
case 101:
robot.type = RobotType::HERO;
robot.maxHP = 200;
robot.heroRigMode = 0;
break;
case 102:
robot.type = RobotType::ENGINEER;
robot.maxHP = 250;
break;
case 103:
robot.type = RobotType::INFANTRY_3;
robot.maxHP = 200;
robot.infantry17mmMode = 0;
break;
case 104:
robot.type = RobotType::INFANTRY_4;
robot.maxHP = 200;
robot.infantry17mmMode = 0;
break;
case 105:
robot.type = RobotType::INFANTRY_5;
robot.maxHP = 200;
robot.infantry17mmMode = 0;
break;
case 106:
robot.type = RobotType::AERIAL;
robot.maxHP = 250;
break;
case 107:
robot.type = RobotType::SENTRY;
robot.maxHP = 600;
break;
}
// 未收到真实静态状态前,默认按"未知且离线"处理,避免顶部列表预亮。
robot.maxHP = 0;
robot.currentHP = 0;
robot.status = RobotStatus::OFFLINE;
robot.level = 1;
robot.experience = 0;
robot.maxExperience = 100;
robot.maxPower = 0;
robot.power = 0;
robot.heatLimit = 0;
robot.currentHeat = 0;
robot.isClientConnected = false;
robot.isControllerConnected = false;
robot.allowedAmmo17mm = 0;
robot.allowedAmmo42mm = 0;
robot.fortressBonusAmmo = 0;
robot.shootSpeedLimit = 0.0f;
robot.tabShootSpeedLimit = 0;
robot.lastUpdateTime = QDateTime::currentDateTime();
robot.q2HeatThreshold = robot.heatLimit + 100;
m_robots.append(robot);
}
}
/**
* @brief 根据机器人ID获取其机器人类型
* @param robotId 机器人ID (1-7: 红方, 101-107: 蓝方)
* @return RobotType 对应的机器人类型
*/
RobotType GameData::getRobotTypeById(quint8 robotId) {
// 按照 RoboMaster 规则:蓝方 ID = 红方 ID + 100
// 取模 100 可以统一红蓝两方的基础 ID (1-7/9)
int baseId = robotId % 100;
switch(baseId){
case 1:
return RobotType::HERO;
case 2:
return RobotType::ENGINEER;
case 3:
return RobotType::INFANTRY_3;
case 4:
return RobotType::INFANTRY_4;
case 6:
return RobotType::AERIAL;
case 7:
return RobotType::SENTRY;
}
return RobotType::INFANTRY_3;
}
/**
* @brief 根据ID获取机器人数据
* @param robotId 机器人ID
* @return const RobotData* 机器人数据指针,如果未找到则返回 nullptr
*/
const RobotData *GameData::getRobotById(quint8 robotId) const {
for (const auto &robot : m_robots) {
if (robot.robotId == robotId) {
return &robot;
}
}
return nullptr;
}
GameData::~GameData() {
// 析构函数实现
}
//封装了 HP/Level 等全量状态更新,以及 击杀、复活、伤害检测 逻辑
void GameData::emitDataChanged() {
const qint64 now = QDateTime::currentMSecsSinceEpoch();
if (now - m_lastDataChangedMs < kDataChangedMinIntervalMs) {
return; // 节流:不到 50ms 跳过本次发射
}
m_lastDataChangedMs = now;
emit dataChanged();
}
void GameData::updateStandardStatus(RobotData *robot, const robomaster::RobotStatus &data) {
if (!robot) return;
// 保存旧状态用于比较(击杀逻辑)
bool wasAlive = (robot->status != RobotStatus::DESTROYED) && (robot->currentHP > 0);
quint16 prevHP = robot->currentHP;
// 更新机器人id
robot->robotId = data.id();
robot->isClientConnected = true;
robot->isControllerConnected = true;
robot->type = static_cast<RobotType>(data.type());
robot->shootSpeedLimit = robotShootSpeedLimit(robot->type);
robot->tabShootSpeedLimit = robotTabShootSpeedLimit(robot->type);
robot->level = data.level();
robot->currentHP = data.hp();
robot->maxHP = data.max_hp();
robot->currentRoundMaxHP =
qMax(robot->currentRoundMaxHP, qMax(robot->currentHP, robot->maxHP));
if (data.heat() > 0) {
robot->currentHeat = static_cast<quint16>(data.heat());
}
//热量上限
if (data.heat_limit() > 0)
robot->heatLimit = data.heat_limit();
//热量冷却值/s
if (data.cooling_value() > 0)
robot->coolingValue = static_cast<quint16>(data.cooling_value());
//底盘功率上限
if (data.power_limit() > 0) {
robot->maxPower = data.power_limit();
robot->maxChassisEnergy = robot->maxPower; // 同步给UI
}
// 更新底盘使能状态 (用于推断超速/超功率惩罚)
robot->chassisEnabled = data.chassis_enabled();
// 更新枪口使能状态 (0=锁定, 1=使能)
robot->shooterLocked = !data.shooter_enabled();
if (data.buff_mask() > 0)
robot->buffMask = data.buff_mask();
robot->lastUpdateTime = QDateTime::currentDateTime();
// 全量状态更新后,立即检查热量超限状态
checkHeatLimit(robot);
// 收到标准状态包说明该机器人已在协议侧出现;从 OFFLINE/DESTROYED 恢复到在线状态。
robot->status = robot->currentHP > 0 ? RobotStatus::NORMAL
: RobotStatus::DESTROYED;
// 伤害检测:如果血量减少且非死亡重置
if (robot->currentHP < prevHP && prevHP > 0) {
robot->isOutOfCombat = false;
robot->lastDamageTime = QDateTime::currentDateTime();
}
// 复活检测:若之前HP为0且当前HP>0,视为"复活",重置 ~ 面板伤害统计
if (prevHP == 0 && robot->currentHP > 0) {
resetInjuryStatsOnRespawn();
}
}
//封装了射速上限计算和超速判定逻辑
void GameData::checkSpeedLimit(RobotData *robot, bool isPenaltyTriggered) {
if (!robot) return;
// --- 射速上限计算 ---
// 计算当前模式下的射速上限
float limit = 30.0f; // 默认上限(如工程机器人)
if (robot->type == RobotType::INFANTRY_3 ||
robot->type == RobotType::INFANTRY_4 ||
robot->type == RobotType::INFANTRY_5 ||
robot->type == RobotType::AERIAL ||
robot->type == RobotType::SENTRY) {
limit = 25.0f;
} else if (robot->type == RobotType::HERO) {
// 英雄机器人特殊逻辑:
// 默认 12m/s
// 远程优先 (heroRigMode==0) + 部署模式 (chassisEnabled==false) -> 16.5m/s
bool isRangePriority = (robot->heroRigMode == 0);
bool isDeploymentMode = !robot->chassisEnabled; // 底盘断电视为进入部署模式
if (isRangePriority && isDeploymentMode) {
limit = 16.5f;
} else {
limit = 12.0f;
}
}
robot->shootSpeedLimit = limit;
if(robot->speedLockState!=SpeedLockState::PermanentLocked){
// 仅当收到 PenaltyInfo 且射速确实超限时,才判定锁定状态
// 如果没有 PenaltyInfo,即使超速也不触发锁定逻辑 (等待服务器判罚)
if (isPenaltyTriggered && robot->muzzleVelocity > limit && robot->currentHP > 0 && robot->status != RobotStatus::DESTROYED) {
// 根据射击初速度超限惩罚机制计算锁定时间
float v1 = robot->muzzleVelocity;
float v0 = limit;
int lockTime = 0;
SpeedLockState newState = SpeedLockState::Normal;
if (robot->type == RobotType::HERO) {
// 英雄机器人 (42mm 弹丸)
bool isDeployment = (v0 > 13.0f);
if (isDeployment) {
// 部署模式 (Table Col 3)
if (v1 <= 18.0f) {
lockTime = 15;
newState = SpeedLockState::Locked15s;
} else {
lockTime = 999;
newState = SpeedLockState::PermanentLocked;
}
} else {
// 非部署模式 (Table Col 2)
if (v1 <= 1.1f * v0) {
lockTime = 15;
newState = SpeedLockState::Locked15s;
} else if (v1 <= 1.2f * v0) {
lockTime = 20;
newState = SpeedLockState::Locked20s;
} else {
lockTime = 999;
newState = SpeedLockState::PermanentLocked;
}
}
} else {
// 17mm 弹丸 (步兵、空中、哨兵) (Table Col 1)
float diff = v1 - v0;
if (diff < 5.0f) {
lockTime = 15;
newState = SpeedLockState::Locked15s;
} else if (diff < 10.0f) {
lockTime = 20;
newState = SpeedLockState::Locked20s;
} else {
lockTime = 999;
newState = SpeedLockState::PermanentLocked;
}
}
robot->speedLockSeconds = lockTime;
robot->speedLockState = newState;
} else {
robot->speedLockState=SpeedLockState::Normal;
robot->speedLockSeconds = 0;
}
}
}
void GameData::checkHeatLimit(RobotData *robot, bool isPenaltyConfirmed) {
if (!robot) return;
// 基础参数校验
if (robot->heatLimit == 0) return; // 尚未获取到上限,不进行判断
// 计算 Q2 (二级超限阈值/永久封锁阈值)
// 步兵/空中/哨兵 (17mm): Q2 = Limit + 100
// 英雄 (42mm): Q2 = Limit + 200
int q2Threshold = robot->heatLimit + 100;
if (robot->type == RobotType::HERO) {
q2Threshold = robot->heatLimit + 200;
}
if(!robot->shooterPermanentLocked){
// 判定热量超限状态
if (robot->currentHeat > robot->heatLimit) {
robot->isHeatOverLimit = true; // 标记为过热
// 判断是否达到严重超限(Q2) - 仅作为严重程度标记,不用于推断锁定
// 引入 PenaltyInfo 判断:只有当收到判罚确认且热量超过 Q2 时,才标记为永久锁定
if (isPenaltyConfirmed && robot->currentHeat > q2Threshold) {
robot->shooterPermanentLocked = true;
}
// 计算冷却到 Limit 以下所需的时间
int diff = robot->currentHeat - robot->heatLimit;
double coolingRate = qMax(1.0, static_cast<double>(robot->coolingValue));
double secs = std::ceil(static_cast<double>(diff) / coolingRate);
robot->heatLockSeconds = static_cast<quint16>(secs);
}else if(robot->isHeatOverLimit && robot->currentHeat==0){
robot->isHeatOverLimit = false;
}else {
// 热量正常
robot->isHeatOverLimit = false; // 重置过热标记
robot->heatLockSeconds = 0;
// 如果热量恢复正常,重置严重超限标记(具体是否解锁由协议 shooter_enabled 决定)
robot->shooterPermanentLocked = false;
}
}
}
/**
* @brief 更新比赛时间
* @details 增加比赛时间计数并发出信号。
*/
void GameData::updateGameTime() {
// 兼容旧模拟器和测试的自增入口;正式比赛时间仍以服务端状态为准。
m_gameState.gameTime++;
emit gameTimeUpdated(m_gameState.gameTime);
emitDataChanged();