Repository navigation
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
3881 lines (3504 loc) · 124 KB
/
Copy pathmainwindow.cpp
File metadata and controls
3881 lines (3504 loc) · 124 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
#include "mainwindow.h"
#include <QCoreApplication>
#include <QDir>
#include <QFile>
#include <QFileInfo>
#include <QHash>
#include <QHostAddress>
#include <QJsonArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QKeyEvent>
#include <QAudioOutput>
#include <QMessageBox>
#include <QMouseEvent>
#include <QPainter>
#include <QPixmap>
#include <QPolygonF>
#include <QPushButton>
#include <QQueue>
#include <QRandomGenerator>
#include <QFont>
#include <QRegularExpression>
#include <QRegularExpressionMatch>
#include <QTcpServer>
#include <QTcpSocket>
#include <QUrl>
#include <algorithm>
#include <cmath>
#include <limits>
namespace {
constexpr int ShopPanelX = 16;
constexpr int ShopPanelWidth = 355;
constexpr int SidePanelWidth = 320;
constexpr int BoardTop = 64;
constexpr int BoardBenchGap = 48;
constexpr int ShopButtonY = 86;
constexpr int ShopCardOffsetX = 48;
constexpr int ShopCardOffsetY = 0;
constexpr int ShopSlotHeight = 106;
constexpr int ShopSlotGap = 14;
constexpr int ShopPanelLeftPadding = 16;
constexpr int ShopPanelRightPadding = 120;
constexpr int ShopPanelTop = 88;
constexpr int ShopPanelHeight = 750;
constexpr int ShopActionButtonGap = 10;
constexpr int LocalBoardRows = 8;
constexpr int LocalBoardCols = 8;
constexpr int MenuButtonWidth = 510;
constexpr int MenuButtonHeight = 132;
constexpr int MenuButtonGap = 130;
constexpr quint16 LanPort = 45454;
constexpr quint16 RemoteRelayPort = 45455;
const QString RemoteRelayHost = "67.216.192.97";
const QString UiFontFamily = QStringLiteral("Microsoft YaHei UI");
QFont uiFont(int pointSize, int weight = QFont::Normal)
{
return QFont(UiFontFamily, pointSize, weight);
}
QColor uiTextColor(int alpha = 255)
{
return QColor(255, 255, 255, alpha);
}
QPolygonF starPolygon(const QPointF& center, qreal radius)
{
QPolygonF points;
const qreal innerRadius = radius * 0.48;
constexpr qreal Pi = 3.14159265358979323846;
for (int i = 0; i < 10; ++i) {
const qreal angle = -Pi / 2 + i * Pi / 5;
const qreal currentRadius = (i % 2 == 0) ? radius : innerRadius;
points << QPointF(center.x() + std::cos(angle) * currentRadius,
center.y() + std::sin(angle) * currentRadius);
}
return points;
}
void drawStarLevel(QPainter& painter, const QRect& rect, int star)
{
const int count = std::clamp(star, 1, 3);
const qreal radius = std::max<qreal>(4.0, std::min<qreal>(6.0, rect.width() / 15.0));
const qreal gap = 2.0;
const qreal totalWidth = count * radius * 2 + (count - 1) * gap;
const qreal startX = rect.left() + (rect.width() - totalWidth) / 2 + radius;
const qreal centerY = rect.top() + 7.0;
painter.setPen(QPen(QColor(115, 86, 24), 1));
painter.setBrush(QColor(250, 210, 78));
for (int i = 0; i < count; ++i) {
painter.drawPolygon(starPolygon(QPointF(startX + i * (radius * 2 + gap), centerY), radius));
}
}
QString assetPath(const QString& relativePath)
{
const QStringList roots = {
QDir::currentPath(),
QCoreApplication::applicationDirPath()
};
for (const QString& root : roots) {
QDir dir(root);
for (int i = 0; i < 6; ++i) {
const QString candidate = dir.filePath(relativePath);
if (QFileInfo::exists(candidate)) {
return candidate;
}
if (!dir.cdUp()) {
break;
}
}
}
return relativePath;
}
QString heroImageFile(const QString& id)
{
if (id == "sentinel") {
return QStringLiteral("image/哨卫 Sentinel.png");
}
if (id == "arcanist") {
return QStringLiteral("image/秘术师 Arcanist.png");
}
if (id == "druid") {
return QStringLiteral("image/德鲁伊 Druid.png");
}
if (id == "ranger") {
return QStringLiteral("image/游侠 Ranger.png");
}
if (id == "assassin") {
return QStringLiteral("image/刺客 Assassin.png");
}
if (id == "star_knight") {
return QStringLiteral("image/星铠骑士 Star Knight.png");
}
if (id == "dawn_lancer") {
return QStringLiteral("image/破晓枪卫 Dawn Lancer.png");
}
if (id == "spark_gunner") {
return QStringLiteral("image/星火炮手 Spark Gunner.png");
}
if (id == "moonblade") {
return QStringLiteral("image/月影行者 Moonblade.png");
}
if (id == "light_priest") {
return QStringLiteral("image/光纹祭司 Light Priest.png");
}
return QString();
}
const QPixmap* heroImage(const QString& id)
{
static QHash<QString, QPixmap> cache;
if (!cache.contains(id)) {
const QString fileName = heroImageFile(id);
QPixmap pixmap;
if (!fileName.isEmpty()) {
pixmap.load(assetPath(fileName));
}
cache.insert(id, pixmap);
}
const auto it = cache.constFind(id);
return it == cache.constEnd() || it.value().isNull() ? nullptr : &it.value();
}
QString equipmentImageFile(EquipmentType type)
{
switch (type) {
case EquipmentType::Sword:
return QStringLiteral("image/铁剑.png");
case EquipmentType::Armor:
return QStringLiteral("image/锁子甲.png");
case EquipmentType::Gloves:
return QStringLiteral("image/迅捷手套.png");
case EquipmentType::Crystal:
return QStringLiteral("image/蓝水晶.png");
}
return QString();
}
const QPixmap* equipmentImage(EquipmentType type)
{
static QHash<int, QPixmap> cache;
const int key = static_cast<int>(type);
if (!cache.contains(key)) {
QPixmap pixmap;
pixmap.load(assetPath(equipmentImageFile(type)));
cache.insert(key, pixmap);
}
const auto it = cache.constFind(key);
return it == cache.constEnd() || it.value().isNull() ? nullptr : &it.value();
}
const QPixmap* startPageImage()
{
static QPixmap pixmap;
static bool loaded = false;
if (!loaded) {
pixmap.load(assetPath(QStringLiteral("image/Start_page.png")));
loaded = true;
}
return pixmap.isNull() ? nullptr : &pixmap;
}
const QPixmap* menuAsset(const QString& fileName)
{
static QHash<QString, QPixmap> cache;
if (!cache.contains(fileName)) {
QPixmap pixmap;
pixmap.load(assetPath(QStringLiteral("image/") + fileName));
cache.insert(fileName, pixmap);
}
const auto it = cache.constFind(fileName);
return it == cache.constEnd() || it.value().isNull() ? nullptr : &it.value();
}
QRect alphaBounds(const QPixmap& pixmap)
{
const QImage image = pixmap.toImage();
QRect bounds;
for (int y = 0; y < image.height(); ++y) {
for (int x = 0; x < image.width(); ++x) {
if (qAlpha(image.pixel(x, y)) > 8) {
const QRect pixelRect(x, y, 1, 1);
bounds = bounds.isNull() ? pixelRect : bounds.united(pixelRect);
}
}
}
return bounds.isNull() ? pixmap.rect() : bounds.adjusted(-4, -4, 4, 4).intersected(pixmap.rect());
}
QRect pixmapSource(const QString& key, const QPixmap& pixmap)
{
static QHash<QString, QRect> cache;
if (!cache.contains(key)) {
cache.insert(key, alphaBounds(pixmap));
}
return cache.value(key);
}
bool isCheckerboardBackgroundPixel(QRgb pixel)
{
if (qAlpha(pixel) < 8) {
return true;
}
const int red = qRed(pixel);
const int green = qGreen(pixel);
const int blue = qBlue(pixel);
const int brightest = std::max({red, green, blue});
const int darkest = std::min({red, green, blue});
return brightest >= 236 && brightest - darkest <= 14;
}
const QPixmap* shopStorePixmap()
{
static QPixmap pixmap;
static bool loaded = false;
if (!loaded) {
QImage image(assetPath(QStringLiteral("image/back_of_store.png")));
if (!image.isNull()) {
image = image.convertToFormat(QImage::Format_ARGB32);
const int imageWidth = image.width();
const int imageHeight = image.height();
std::vector<unsigned char> visited(size_t(imageWidth) * size_t(imageHeight), 0);
QQueue<QPoint> queue;
auto enqueue = [&](int x, int y) {
if (x < 0 || y < 0 || x >= imageWidth || y >= imageHeight) {
return;
}
const size_t index = size_t(y) * size_t(imageWidth) + size_t(x);
if (visited[index] || !isCheckerboardBackgroundPixel(image.pixel(x, y))) {
return;
}
visited[index] = 1;
queue.enqueue(QPoint(x, y));
};
for (int x = 0; x < imageWidth; ++x) {
enqueue(x, 0);
enqueue(x, imageHeight - 1);
}
for (int y = 0; y < imageHeight; ++y) {
enqueue(0, y);
enqueue(imageWidth - 1, y);
}
while (!queue.isEmpty()) {
const QPoint point = queue.dequeue();
QColor color = image.pixelColor(point);
color.setAlpha(0);
image.setPixelColor(point, color);
enqueue(point.x() + 1, point.y());
enqueue(point.x() - 1, point.y());
enqueue(point.x(), point.y() + 1);
enqueue(point.x(), point.y() - 1);
}
pixmap = QPixmap::fromImage(image);
}
loaded = true;
}
return pixmap.isNull() ? nullptr : &pixmap;
}
QRect heroImageSource(const QString& id, const QPixmap& pixmap)
{
if (id == "sentinel") {
return QRect(120, 35, 1175, 940).intersected(pixmap.rect());
}
return pixmap.rect();
}
QRect fittedPixmapRect(const QRect& rect, const QSize& sourceSize)
{
if (sourceSize.isEmpty()) {
return rect;
}
const qreal scale = std::min(rect.width() / qreal(sourceSize.width()),
rect.height() / qreal(sourceSize.height()));
const int width = std::max(1, int(std::round(sourceSize.width() * scale)));
const int height = std::max(1, int(std::round(sourceSize.height() * scale)));
return QRect(rect.left() + (rect.width() - width) / 2,
rect.top() + (rect.height() - height) / 2,
width,
height);
}
void drawHeroImage(QPainter& painter, const QString& id, const QRect& rect, const QColor& fallback)
{
const QPixmap* pixmap = heroImage(id);
if (!pixmap) {
painter.fillRect(rect, fallback);
return;
}
const QRect source = heroImageSource(id, *pixmap);
const QRect target = fittedPixmapRect(rect, source.size());
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, false);
painter.drawPixmap(target, *pixmap, source);
painter.restore();
}
void drawCoverPixmap(QPainter& painter, const QPixmap& pixmap, const QRect& target)
{
if (target.isEmpty() || pixmap.isNull()) {
return;
}
const qreal scale = std::max(target.width() / qreal(pixmap.width()),
target.height() / qreal(pixmap.height()));
const int sourceWidth = std::max(1, int(std::round(target.width() / scale)));
const int sourceHeight = std::max(1, int(std::round(target.height() / scale)));
const QRect source((pixmap.width() - sourceWidth) / 2,
(pixmap.height() - sourceHeight) / 2,
sourceWidth,
sourceHeight);
painter.drawPixmap(target, pixmap, source);
}
bool drawMenuPixmap(QPainter& painter, const QString& fileName, const QRect& target)
{
const QPixmap* pixmap = menuAsset(fileName);
if (!pixmap) {
return false;
}
painter.drawPixmap(target, *pixmap, pixmapSource(fileName, *pixmap));
return true;
}
bool drawShopCardPixmap(QPainter& painter, const QRect& target)
{
const QPixmap* pixmap = menuAsset(QStringLiteral("back_of_card.png"));
if (!pixmap || target.isEmpty()) {
return false;
}
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, pixmapSource(QStringLiteral("back_of_card.png"), *pixmap));
painter.restore();
return true;
}
bool drawShopStorePixmap(QPainter& painter, const QRect& target)
{
const QPixmap* pixmap = shopStorePixmap();
if (!pixmap || target.isEmpty()) {
return false;
}
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, pixmapSource(QStringLiteral("back_of_store_clean"), *pixmap));
painter.restore();
return true;
}
bool drawResultPixmap(QPainter& painter, const QRect& target)
{
const QPixmap* pixmap = menuAsset(QStringLiteral("back_of_result.png"));
if (!pixmap || target.isEmpty()) {
return false;
}
const QRectF sourcePanel(38.0, 32.0, 1479.0, 919.0);
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, sourcePanel);
painter.restore();
return true;
}
bool drawTexturePixmap(QPainter& painter, const QString& fileName, const QRect& target)
{
const QPixmap* pixmap = menuAsset(fileName);
if (!pixmap || target.isEmpty()) {
return false;
}
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, pixmap->rect());
painter.restore();
return true;
}
bool drawBoardTexturePixmap(QPainter& painter, const QRect& gridTarget)
{
const QPixmap* pixmap = menuAsset(QStringLiteral("back_of_board.png"));
if (!pixmap || gridTarget.isEmpty()) {
return false;
}
const QRectF sourceGrid(21.0, 20.0, 1211.0, 1213.0);
const qreal scaleX = gridTarget.width() / sourceGrid.width();
const qreal scaleY = gridTarget.height() / sourceGrid.height();
const QRectF target(gridTarget.left() - sourceGrid.left() * scaleX,
gridTarget.top() - sourceGrid.top() * scaleY,
pixmap->width() * scaleX,
pixmap->height() * scaleY);
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, QRectF(pixmap->rect()));
painter.restore();
return true;
}
bool drawPrepareTexturePixmap(QPainter& painter, const QRect& slotsTarget)
{
const QPixmap* pixmap = menuAsset(QStringLiteral("back_of_prepare.png"));
if (!pixmap || slotsTarget.isEmpty()) {
return false;
}
const QRectF sourceSlots(43.0, 293.0, 1686.0, 300.0);
const QRectF sourcePanel(19.0, 265.0, 1735.0, 356.0);
const qreal scaleX = slotsTarget.width() / sourceSlots.width();
const qreal scaleY = slotsTarget.height() / sourceSlots.height();
const QRectF targetPanel(slotsTarget.left() + (sourcePanel.left() - sourceSlots.left()) * scaleX,
slotsTarget.top() + (sourcePanel.top() - sourceSlots.top()) * scaleY,
sourcePanel.width() * scaleX,
sourcePanel.height() * scaleY);
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(targetPanel, *pixmap, sourcePanel);
painter.restore();
return true;
}
bool drawEquipmentSitePixmap(QPainter& painter, const QRect& target)
{
const QPixmap* pixmap = menuAsset(QStringLiteral("back_of_equipment_site.png"));
if (!pixmap || target.isEmpty()) {
return false;
}
const QRectF sourcePanel(159.0, 0.0, 704.0, 761.0);
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.drawPixmap(target, *pixmap, sourcePanel);
painter.restore();
return true;
}
qreal fadeProgress(qint64 elapsedMs, qint64 startMs, qint64 durationMs)
{
const qreal value = (elapsedMs - startMs) / qreal(durationMs);
return std::clamp(value, 0.0, 1.0);
}
void drawImageMenuButton(QPainter& painter,
const QString& fileName,
const QRect& rect,
const QString& text,
bool enabled,
qreal opacity,
bool hovered)
{
const QRect imageRect = hovered && enabled ? rect.adjusted(-5, -3, 5, 3) : rect;
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, true);
painter.setRenderHint(QPainter::TextAntialiasing, true);
painter.setOpacity(opacity * (enabled ? 1.0 : 0.45));
drawMenuPixmap(painter, fileName, imageRect);
QFont font(UiFontFamily, 22, QFont::Black);
painter.setFont(font);
const QRect textRect = imageRect.adjusted(22, 4, -22, -6);
painter.setPen(uiTextColor(130));
painter.drawText(textRect.translated(0, 3), Qt::AlignCenter, text);
painter.setPen(uiTextColor(150));
painter.drawText(textRect.translated(0, -1), Qt::AlignCenter, text);
painter.setPen(enabled ? uiTextColor() : uiTextColor(150));
painter.drawText(textRect, Qt::AlignCenter, text);
painter.restore();
}
void drawEquipmentImage(QPainter& painter, const Equipment& equipment, const QRect& rect)
{
const QPixmap* pixmap = equipmentImage(equipment.type);
if (!pixmap) {
painter.setFont(uiFont(8, QFont::Bold));
painter.setPen(uiTextColor());
painter.drawText(rect, Qt::AlignCenter | Qt::TextWordWrap, equipment.name);
return;
}
const QRect target = fittedPixmapRect(rect, pixmap->size());
painter.save();
painter.setRenderHint(QPainter::SmoothPixmapTransform, false);
painter.drawPixmap(target, *pixmap, pixmap->rect());
painter.restore();
}
QString traitDisplayName(const QString& trait)
{
if (trait == "Warrior") {
return QStringLiteral("战士");
}
if (trait == "Guardian") {
return QStringLiteral("守护者");
}
if (trait == "Mage") {
return QStringLiteral("法师");
}
if (trait == "Mystic") {
return QStringLiteral("秘术");
}
if (trait == "Ranger") {
return QStringLiteral("游侠");
}
return trait;
}
QString traitDisplayList(const QStringList& traits)
{
QStringList localized;
for (const QString& trait : traits) {
localized << traitDisplayName(trait);
}
return localized.join(QStringLiteral("、"));
}
int indexOf(int row, int col)
{
return row * LocalBoardCols + col;
}
bool inBounds(int row, int col)
{
return row >= 0 && row < LocalBoardRows && col >= 0 && col < LocalBoardCols;
}
double gridDistance(const Unit* a, const Unit* b)
{
const int dr = a->row() - b->row();
const int dc = a->col() - b->col();
return std::sqrt(static_cast<double>(dr * dr + dc * dc));
}
QString equipmentName(const Unit* unit)
{
return unit->hasEquipment() ? unit->equipment().name : QStringLiteral("无");
}
QString cleanRemoteToken(QString value, int maxLength)
{
value = value.trimmed();
value.replace(QRegularExpression(QStringLiteral("[\\r\\n\\t]")), QStringLiteral(" "));
while (value.contains(QStringLiteral(" "))) {
value.replace(QStringLiteral(" "), QStringLiteral(" "));
}
if (value.size() > maxLength) {
value = value.left(maxLength);
}
return value;
}
}
MainWindow::MainWindow(QWidget* parent)
: QWidget(parent)
{
setWindowTitle(QStringLiteral("星尘骑士团"));
setMinimumSize(1440, 900);
setMouseTracking(true);
for (int row = 0; row < BoardRows; ++row) {
for (int col = 0; col < BoardCols; ++col) {
m_tiles[row][col] = Tile(row, col);
}
}
for (auto& row : m_board) {
row.fill(nullptr);
}
m_bench.fill(nullptr);
m_menuAudioOutput = new QAudioOutput(this);
m_menuAudioOutput->setVolume(float(m_menuVolume));
m_menuMusicPlayer.setAudioOutput(m_menuAudioOutput);
m_menuMusicPlayer.setSource(QUrl::fromLocalFile(assetPath(QStringLiteral("music/Beneath_the_Iron_Crown.mp3"))));
m_menuMusicPlayer.setLoops(QMediaPlayer::Infinite);
connect(&m_timer, &QTimer::timeout, this, &MainWindow::tickGame);
m_timer.start(250);
m_menuAnimationClock.start();
connect(&m_menuAnimationTimer, &QTimer::timeout, this, [this]() {
if (m_screen != Screen::Playing && m_menuAnimationClock.elapsed() < 1900) {
update();
} else {
m_menuAnimationTimer.stop();
}
});
m_menuAnimationTimer.start(16);
updateMenuMusic();
}
void MainWindow::initializeGame()
{
setScreen(Screen::Playing);
m_phase = Phase::Prep;
m_round = 1;
const QString nickname = m_localNickname;
const QString roomId = m_remoteRoomId;
m_player.setState(100, 30, 1, 3, 0, 0);
m_units.clear();
for (auto& row : m_board) {
row.fill(nullptr);
}
m_bench.fill(nullptr);
m_equipmentPool.clear();
m_activeTraits.clear();
m_log.clear();
m_finalMessage.clear();
m_menuMessage.clear();
m_localCombatReady = false;
m_remoteCombatReady = false;
m_hasServerBattleResult = false;
m_serverPlayerWon = false;
m_remoteOpponentHealth = 100;
m_localNickname = nickname;
m_remoteOpponentName.clear();
m_remoteRoomId = roomId;
m_remoteBoardSnapshot = QJsonArray();
Unit* first = addUnit(createHero("sentinel", Owner::PlayerCtrl));
Unit* second = addUnit(createHero("ranger", Owner::PlayerCtrl));
placeOnBench(first, 0);
placeOnBench(second, 1);
refreshShop(false);
updateActiveTraits();
pushLog(QStringLiteral("购买单位,拖到棋盘下半区,然后开始战斗。"));
update();
}
void MainWindow::tickGame()
{
if (m_screen != Screen::Playing) {
update();
return;
}
if (m_phase == Phase::Combat) {
QVector<Unit*> all = combatUnits();
for (Unit* unit : all) {
updateUnit(unit, all);
clearDeadOccupants();
}
const bool enemyAlive = hasAlive(Owner::EnemyCtrl);
const bool playerAlive = hasAlive(Owner::PlayerCtrl);
if (!enemyAlive || !playerAlive) {
bool playerWon = !enemyAlive;
if (m_networkRole == NetworkRole::Remote && m_hasServerBattleResult) {
if (playerWon != m_serverPlayerWon) {
pushLog(QStringLiteral("服务器结果覆盖本地战斗演出。"));
}
playerWon = m_serverPlayerWon;
}
finishCombat(playerWon);
}
update();
return;
}
if (m_phase == Phase::Resolve) {
--m_resolveTicks;
if (m_resolveTicks <= 0) {
enterPrepAfterResolve();
}
update();
}
}
void MainWindow::startCombat()
{
if (m_phase != Phase::Prep) {
return;
}
if (boardPlayerCount() == 0) {
pushLog(QStringLiteral("请至少放置一个单位到棋盘上。"));
update();
return;
}
if (m_networkRole != NetworkRole::Offline) {
sendLocalCombatReady();
return;
}
m_combatStart.clear();
for (Unit* unit : playerBoardUnits()) {
m_combatStart.push_back({unit, unit->row(), unit->col()});
}
spawnEnemies();
for (Unit* unit : combatUnits()) {
unit->resetForCombat();
}
const int enemyPower = std::max(0, m_round - 1);
for (Unit* unit : combatUnits()) {
if (unit->owner() == Owner::EnemyCtrl) {
unit->addMaxHp(enemyPower * 45);
unit->addAttack(enemyPower * 6);
}
}
applyTraitBonuses();
m_phase = Phase::Combat;
pushLog(QStringLiteral("第 %1 回合战斗开始。").arg(m_round));
update();
}
void MainWindow::finishCombat(bool playerWon)
{
if (m_phase != Phase::Combat) {
return;
}
if (m_networkRole == NetworkRole::Remote) {
m_remoteOpponentHealth = std::max(0, m_remoteOpponentHealth - (playerWon ? 12 + m_round * 3 : 0));
}
m_hasServerBattleResult = false;
m_serverPlayerWon = false;
m_lastRoundWon = playerWon;
resolveRewards(playerWon);
restorePlayerPositions();
clearEnemies();
if (!playerWon) {
if (m_player.health() <= 0) {
m_phase = Phase::Finished;
m_finalMessage = QStringLiteral("失败:第 %1 回合 HP 归零。").arg(m_round);
pushLog(QStringLiteral("失败:玩家 HP 已经归零。"));
update();
return;
}
const int finishedRound = m_round;
if (m_networkRole != NetworkRole::Offline) {
++m_round;
}
m_phase = Phase::Resolve;
m_resolveTicks = 8;
pushLog(m_networkRole == NetworkRole::Offline
? QStringLiteral("第 %1 回合失败,整备后再挑战本回合。").arg(finishedRound)
: QStringLiteral("第 %1 回合失败,进入下一回合。").arg(finishedRound));
update();
return;
}
if (m_networkRole == NetworkRole::Offline && m_round >= MaxRounds) {
m_phase = Phase::Finished;
m_finalMessage = QStringLiteral("胜利:已通关全部五个回合。");
pushLog(QStringLiteral("胜利:已通关全部五个回合。"));
update();
return;
}
if (m_networkRole == NetworkRole::Remote && m_remoteOpponentHealth <= 0) {
m_phase = Phase::Finished;
m_finalMessage = QStringLiteral("胜利:%1 HP 已归零。").arg(m_remoteOpponentName.isEmpty() ? QStringLiteral("对手") : m_remoteOpponentName);
pushLog(m_finalMessage);
update();
return;
}
++m_round;
m_phase = Phase::Resolve;
m_resolveTicks = 8;
update();
}
void MainWindow::enterPrepAfterResolve()
{
m_phase = Phase::Prep;
refreshShop(false);
updateActiveTraits();
pushLog(QStringLiteral("准备阶段。"));
}
void MainWindow::spawnEnemies()
{
clearEnemies();
QVector<QString> lineups;
if (m_round == 1) {
lineups = {"sentinel", "ranger"};
} else if (m_round == 2) {
lineups = {"sentinel", "druid", "spark_gunner"};
} else if (m_round == 3) {
lineups = {"star_knight", "ranger", "assassin", "arcanist"};
} else if (m_round == 4) {
lineups = {"sentinel", "light_priest", "spark_gunner", "moonblade", "arcanist"};
} else {
lineups = {"star_knight", "dawn_lancer", "light_priest", "ranger", "moonblade", "arcanist"};
}
const QVector<QPoint> spots = {
{1, 2}, {1, 5}, {0, 3}, {0, 4}, {2, 2}, {2, 5}
};
for (int i = 0; i < lineups.size(); ++i) {
Unit* enemy = addUnit(createHero(lineups[i], Owner::EnemyCtrl));
if (m_round >= 4 && (i % 2 == 0)) {
enemy->setStar(2);
}
placeOnBoard(enemy, spots[i].x(), spots[i].y());
}
}
void MainWindow::updateActiveTraits()
{
refreshActiveTraits(false);
}
void MainWindow::applyTraitBonuses()
{
refreshActiveTraits(true);
}
void MainWindow::refreshActiveTraits(bool applyBonuses)
{
m_activeTraits.clear();
QVector<Unit*> units = playerBoardUnits();
auto countTrait = [&units](const QString& trait) {
int count = 0;
for (Unit* unit : units) {
if (unit->hasTrait(trait)) {
++count;
}
}
return count;
};
const int warriors = countTrait("Warrior");
if (warriors > 0) {
const int bonus = warriors >= 4 ? 160 : 80;
if (warriors >= 2 && applyBonuses) {
for (Unit* unit : units) {
if (unit->hasTrait("Warrior")) {
unit->addMaxHp(bonus);
}
}
}
if (warriors >= 2) {
m_activeTraits << QStringLiteral("战士 %1:战士单位 +%2 HP").arg(warriors).arg(bonus);
} else {
m_activeTraits << QStringLiteral("战士 %1/2(未激活):战士单位 +80 HP").arg(warriors);
}
}
const int guardians = countTrait("Guardian");
if (guardians > 0) {
if (guardians >= 2 && applyBonuses) {
for (Unit* unit : units) {
unit->addMaxHp(60);
}
}
if (guardians >= 2) {
m_activeTraits << QStringLiteral("守护者 2:我方全体 +60 HP");
} else {
m_activeTraits << QStringLiteral("守护者 %1/2(未激活):我方全体 +60 HP").arg(guardians);
}
}
const int mages = countTrait("Mage");
if (mages > 0) {
const int bonus = mages >= 3 ? 100 : 50;
if (mages >= 2 && applyBonuses) {
for (Unit* unit : units) {
unit->addSkillDamagePercent(bonus);
}
}
if (mages >= 2) {
m_activeTraits << QStringLiteral("法师 %1:技能伤害 +%2%").arg(mages).arg(bonus);
} else {
m_activeTraits << QStringLiteral("法师 %1/2(未激活):技能伤害 +50%").arg(mages);
}
}
const int rangers = countTrait("Ranger");
if (rangers > 0) {
if (rangers >= 2 && applyBonuses) {
for (Unit* unit : units) {
if (unit->hasTrait("Ranger")) {
unit->setDoubleAttackChance(35);
}
}
}
if (rangers >= 2) {
m_activeTraits << QStringLiteral("游侠 2:游侠有概率连击");
} else {
m_activeTraits << QStringLiteral("游侠 %1/2(未激活):游侠有概率连击").arg(rangers);
}
}
const int mystics = countTrait("Mystic");
if (mystics > 0) {
if (mystics >= 2 && applyBonuses) {
for (Unit* unit : units) {
unit->addManaGain(5);
}
}
if (mystics >= 2) {
m_activeTraits << QStringLiteral("秘术 2:我方全体法力获取 +5");
} else {
m_activeTraits << QStringLiteral("秘术 %1/2(未激活):我方全体法力获取 +5").arg(mystics);
}
}
}
void MainWindow::resolveRewards(bool playerWon)
{
m_player.recordResult(playerWon);
if (!playerWon) {
m_player.takeDamage(12 + m_round * 3);
}
const int baseGold = playerWon ? 6 : 3;
m_lastInterest = std::min(5, m_player.gold() / 10);
const int streak = playerWon ? m_player.winStreak() : m_player.lossStreak();
m_lastStreakBonus = streak >= 2 ? std::min(3, streak - 1) : 0;
const int rewardMultiplier = m_networkRole == NetworkRole::Offline ? 1 : 2;
const int totalGold = (baseGold + m_lastInterest + m_lastStreakBonus) * rewardMultiplier;
m_player.addGold(totalGold);
if (playerWon && QRandomGenerator::global()->bounded(100) < 65) {
const QVector<Equipment> catalog = Equipment::catalog();
m_equipmentPool << catalog[QRandomGenerator::global()->bounded(catalog.size())];
pushLog(QStringLiteral("获得一件装备。"));
}
pushLog(QStringLiteral("%1:+%2 金币(基础 %3,利息 +%4,连胜/连败 +%5%6)。")
.arg(playerWon ? QStringLiteral("胜利") : QStringLiteral("失败"))
.arg(totalGold)
.arg(baseGold)
.arg(m_lastInterest)
.arg(m_lastStreakBonus)
.arg(rewardMultiplier > 1 ? QStringLiteral(",联机 x2") : QString()));
}
void MainWindow::clearEnemies()
{
for (auto& row : m_board) {