-
Notifications
You must be signed in to change notification settings - Fork 2
/
ground.cpp
executable file
·1261 lines (1186 loc) · 39.5 KB
/
ground.cpp
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
/*
* Copyright (C) Kreogist Dev Team
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include <QPainter>
#include <QMessageBox>
#include <QFileDialog>
#include <QColorDialog>
#include <QFileInfo>
#include <QTimer>
#include <QFile>
#include <QJsonObject>
#include <QJsonArray>
#include <QTextStream>
#include <QJsonDocument>
#include <QApplication>
#include "robot.h"
#include "enemy.h"
#include "menubar.h"
#include "generategroundbase.h"
#include "groundglobal.h"
#include "languagemanager.h"
#include "ground.h"
#include <QDebug>
Ground::Ground(QWidget *parent) :
GroundBase(parent),
m_border(QPolygonF()),
m_barracks(QPolygonF()),
m_reachBorderCount(0),
m_showDirection(true),
m_showDetectRadius(true),
m_filePath(QString()),
m_fileName(QString()),
m_changed(false),
m_timeline(new QTimer(this)),
m_generator(nullptr),
m_groundGlobal(GroundGlobal::instance()),
m_lastOpenFolder(QApplication::applicationDirPath()),
m_lastSaveFolder(QApplication::applicationDirPath())
{
//Set parameters.
setContentsMargins(0,0,0,0);
//Initial robots.
Robot::initialRobotPatameters();
//Configure the timer.
setSpeed(16); //This will update the image for 60fps.
connect(m_timeline, &QTimer::timeout,
this, &Ground::onActionUpdateRobot);
//Initial the actions.
for(int i=0; i<GroundActionsCount; i++)
{
m_actions[i]=new QAction(this);
}
m_actions[ShowDetectRange]->setCheckable(true);
m_actions[ShowDetectRange]->setChecked(true);
m_actions[ShowDirection]->setCheckable(true);
m_actions[ShowDirection]->setChecked(true);
m_actions[ShowCoordinate]->setCheckable(true);
m_actions[ShowCoordinate]->setChecked(false);
//Set the key sequence.
m_actions[New]->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_N));
m_actions[Open]->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_O));
m_actions[Save]->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_S));
m_actions[SaveAs]->setShortcut(QKeySequence(Qt::CTRL+Qt::SHIFT+Qt::Key_S));
m_actions[Close]->setShortcut(QKeySequence(Qt::CTRL+Qt::Key_W));
//Disable the save, save as and close as default.
m_actions[Save]->setEnabled(false);
m_actions[SaveAs]->setEnabled(false);
m_actions[Close]->setEnabled(false);
connect(m_actions[New],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionNew();});
connect(m_actions[Open],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionOpen();});
connect(m_actions[Save],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionSave();});
connect(m_actions[SaveAs],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionSaveAs();});
connect(m_actions[Close],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionClose();});
connect(m_actions[BorderColor],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionChangeBorderColor();});
connect(m_actions[BarracksColor],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionChangeBarracksColor();});
connect(m_actions[RobotColor],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionChangeRobotColor();});
connect(m_actions[RobotDirectionLineColor],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionChangeDirectionLineColor();});
connect(m_actions[RobotDetectRangeColor],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{onActionChangeDetectRangeLineColor();});
connect(m_actions[ShowDetectRange],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{update();});
connect(m_actions[ShowDirection],
static_cast<void (QAction::*)(bool)>(&QAction::triggered),
[=]{update();});
connect(LanguageManager::instance(), SIGNAL(languageChanged()),
this, SLOT(retranslate()));
retranslate();
}
Ground::~Ground()
{
//Recover all the memory of the robot.
qDeleteAll(m_robotList);
}
QPolygonF Ground::border() const
{
return m_border;
}
void Ground::setBorder(const QPolygonF &border)
{
//The border should be at least a triangle, if it's only a line or nothing,
//ignore the request.
if(border.size()<3)
{
return;
}
//Save the border, and clear the barracks.
m_border = border;
m_barracks = QPolygonF();
//Set the changed flag.
m_changed=true;
//Update the border lines.
m_borderLines.clear();
for(int i=0; i<m_border.size()-1; i++)
{
m_borderLines.append(QLineF(m_border.at(i), m_border.at(i+1)));
}
m_borderLines.append(QLineF(m_border.at(m_border.size()-1),
m_border.at(0)));
//Get the bounding rect of the border.
QRect borderBoundingRect=m_border.toPolygon().boundingRect();
QSize groundSize=QSize(borderBoundingRect.right(),
borderBoundingRect.bottom());
//Bounding revise.
groundSize+=QSize(2+(Robot::detectRadius()<<1),
2+(Robot::detectRadius()<<1));
//Resize the ground.
setFixedSize(groundSize);
emit groundSizeChanged(groundSize);
//Update the widget.
update();
//Emit changed signal.
emit borderChanged();
emit barracksChanged();
}
void Ground::paintEvent(QPaintEvent *event)
{
Q_UNUSED(event)
QPainter painter(this);
//Configure the painter.
painter.setRenderHints(QPainter::Antialiasing |
QPainter::TextAntialiasing |
QPainter::SmoothPixmapTransform, true);
//Set translation.
painter.translate(Robot::detectRadius(), Robot::detectRadius());
//Draw the ground.
//Paint the ground base.
painter.setPen(Qt::NoPen);
QBrush borderBrush(Qt::SolidPattern);
borderBrush.setColor(m_groundGlobal->groundColor());
painter.setBrush(borderBrush);
painter.drawPolygon(m_border);
//Paint the ground border.
painter.setPen(m_groundGlobal->borderColor());
borderBrush.setStyle(Qt::FDiagPattern);
borderBrush.setColor(m_groundGlobal->borderColor());
painter.setBrush(borderBrush);
painter.drawPolygon(m_border);
//Draw the barracks.
painter.setPen(m_groundGlobal->barracksColor());
borderBrush.setColor(m_groundGlobal->barracksColor());
borderBrush.setStyle(Qt::DiagCrossPattern);
painter.setOpacity(0.5);
painter.setBrush(borderBrush);
painter.drawPolygon(m_barracks);
painter.setOpacity(1.0);
//Draw all the robot.
if(!m_robotList.isEmpty())
{
//First, draw the detect area.
if(m_actions[ShowDetectRange]->isChecked())
{
painter.setPen(Qt::NoPen);
for(Robot *robot : m_robotList)
{
robot->paintRobotDetectArea(&painter);
}
}
//Then, draw the parameter.
if(m_actions[ShowDirection]->isChecked())
{
painter.setPen(Robot::directionLineColor());
painter.setBrush(Qt::NoBrush);
for(Robot *robot : m_robotList)
{
robot->paintRobotParameter(&painter);
}
}
//Finally, draw the robot.
QPen robotPen(Robot::robotBorder());
robotPen.setWidth(2);
painter.setPen(robotPen);
painter.setBrush(Robot::robotColor());
for(Robot *robot : m_robotList)
{
robot->paintRobot(&painter);
}
}
//Draw all the enemy.
if(!m_enemyList.isEmpty())
{
//First, draw the detect area.
if(m_actions[ShowDetectRange]->isChecked())
{
painter.setPen(Qt::NoPen);
for(Enemy *enemy : m_enemyList)
{
if(!enemy->destory())
{
enemy->paintEnemyDetectArea(&painter);
}
}
}
// //Then, draw the parameter.
// if(m_actions[ShowDirection]->isChecked())
// {
// painter.setPen(Robot::enemyRadiusColor());
// painter.setBrush(Qt::NoBrush);
// for(Enemy *enemy : m_enemyList)
// {
// if(!enemy->destory())
// {
// enemy->paintRobotParameter(&painter);
// }
// }
// }
//Finally, draw the robot.
QPen robotPen(Robot::robotBorder());
robotPen.setWidth(2);
painter.setPen(robotPen);
painter.setBrush(Robot::robotColor());
for(Enemy *enemy : m_enemyList)
{
if(!enemy->destory())
{
enemy->paintRobot(&painter);
}
}
}
}
void Ground::retranslate()
{
m_actions[New]->setText(tr("New"));
m_actions[Open]->setText(tr("Open"));
m_actions[Save]->setText(tr("Save"));
m_actions[SaveAs]->setText(tr("Save As"));
m_actions[Close]->setText(tr("Close"));
m_actions[BorderColor]->setText(tr("Set border color"));
m_actions[BarracksColor]->setText(tr("Set barracks color"));
m_actions[RobotColor]->setText(tr("Set robot color"));
m_actions[RobotDirectionLineColor]->setText(tr("Set robot direction line color"));
m_actions[RobotDetectRangeColor]->setText(tr("Set robot detect range color"));
m_actions[ShowDirection]->setText(tr("Show Robot Direction"));
m_actions[ShowDetectRange]->setText(tr("Show Detect Range"));
m_actions[ShowCoordinate]->setText(tr("Show Coordinate"));
}
void Ground::onActionUpdateRobot()
{
//If there're more than 1 robots, we will going to detect the robot.
if(m_robotList.size()>1)
{
QList<Robot *>::iterator beforeLastRobot=m_robotList.end()-1;
//Give all the robot the detect information.
for(QList<Robot *>::iterator robot=m_robotList.begin();
robot!=beforeLastRobot;
++robot)
{
for(QList<Robot *>::iterator target=robot+1;
target!=m_robotList.end();
++target)
{
//Ignore the current robot.
if(robot==target)
{
continue;
}
//If we have detected one of another robot, add them into the both
//detect list.
if(inDetectRange(*robot, *target))
{
(*robot)->addToDetectList(*target);
(*target)->addToDetectList(*robot);
}
else
{
//Or else remove them from each other's detect list.
(*robot)->removeFromDetectList(*target);
(*target)->removeFromDetectList(*robot);
}
}
}
}
//Move un-destoied unit enemy if 80% of the robots reach the border.
if(m_reachBorderCount>m_minimumMoveEnemyCount)
{
//Get the next position of the enemies.
for(Enemy *enemy : m_enemyList)
{
if(!enemy->destory())
{
bool reachTarget=false;
QPointF nextStep=enemy->nextStep(reachTarget);
if(reachTarget)
{
if(Enemy::missionComplete())
{
continue;
}
//Set mission complete flag.
Enemy::setMissionComplete(true);
//Generate the four target point.
QList<QPointF> targetPoints;
targetPoints << QPointF(0, 0)
<< QPointF(width(), 0)
<< QPointF(0, height())
<< QPointF(width(), height());
//Set the new target.
for(QPointF point : targetPoints)
{
if(!m_border.containsPoint(point,
Qt::WindingFill))
{
Enemy::setTarget(point);
break;
}
}
//Get the new next step.
nextStep=enemy->nextStep(reachTarget);
//Add next step to steps list.
enemy->setPos(nextStep);
}
enemy->setPos(nextStep);
}
}
}
//If there'r more than 1 enemies, we will going to detect the enemy.
if(!m_enemyList.isEmpty() && !m_robotList.isEmpty())
{
for(Enemy *enemy : m_enemyList)
{
//If current enemy is not destoried.
if(!enemy->destory())
{
//Check the distance to all the robot.
for(Robot *robot : m_robotList)
{
if(pointDistance(enemy->pos(), robot->pos())
< Robot::detectRadius())
{
enemy->setDestory(true);
break;
}
}
}
}
}
//Update all the robot.
for(Robot *robot : m_robotList)
{
//If the robot is still don't have a line to guard,
if(!robot->hasGuardianLine())
{
//Detect if the robot is in the border, if the robot is out of the
//border.
if(!m_border.containsPoint(robot->nextStep(),
Qt::WindingFill))
{
//Find the line of the robot should guard, the robot should
//guard the most recent line.
//Appoint the robot to guard that line.
appointGuardianLine(robot);
//Add the counter.
m_reachBorderCount++;
}
}
//Update the direction of the robot.
robot->updateDirection();
}
//Ask all the robot to move one step.
for(Robot *robot : m_robotList)
{
//Move the robot.
robot->moveOneStep();
}
//Update the image.
update();
}
void Ground::onActionNew()
{
//Stop the time line.
pause();
//Close the current file.
if(!onActionClose())
{
return;
}
//Should call generate ground widget here, and then judge it's success or
//failed. If success, set the ground information, or else abandon.
if(m_generator)
{
//Clear the previous data.
m_generator->setBorder(QPolygonF());
m_generator->setBarracks(QPolygonF());
//Get the new data.
if(QDialog::Accepted==m_generator->exec())
{
//Set the border and barracks.
setBorder(m_generator->border());
setBarracks(m_generator->barracks());
//Set changed flag.
m_changed=true;
//Update the image.
update();
//Enabled save and save as actions.
m_actions[Save]->setEnabled(true);
m_actions[SaveAs]->setEnabled(true);
m_actions[Close]->setEnabled(true);
}
}
}
bool Ground::onActionOpen()
{
//Stop the time line.
pause();
//Close the current file.
if(!onActionClose())
{
return false;
}
//Get the session file path.
QString sessionFilePath=QFileDialog::getOpenFileName(this,
tr("Open session"),
m_lastOpenFolder,
tr("Robot Emulator Session") + "(*.sss)");
if(sessionFilePath.isEmpty())
{
return false;
}
//Read the session file.
return readGroundData(sessionFilePath);
}
bool Ground::onActionSave()
{
//If the file don't need to save, then return false.
if(!m_changed)
{
return false;
}
//Check the file path is empty or not, if it's empty, call the save as.
if(m_filePath.isEmpty())
{
return onActionSaveAs();
}
//Or else, just write the data to the file.
m_changed=!writeGroundData();
return !m_changed;
}
bool Ground::onActionSaveAs()
{
//Get the new file path.
QString preferFilePath=QFileDialog::getSaveFileName(this,
tr("Save session"),
m_lastSaveFolder,
tr("Robot Emulator Session") + "(*.sss)");
if(preferFilePath.isEmpty())
{
return false;
}
//Set session file information.
m_filePath=preferFilePath;
QFileInfo sessionFileInfo(m_filePath);
m_fileName=sessionFileInfo.fileName();
//Save the data to session file.
m_changed=!writeGroundData();
return !m_changed;
}
bool Ground::onActionClose()
{
//Stop the timeline.
pause();
//Check if the current state is already close.
if(m_filePath.isEmpty() && !m_changed)
{
//Treat this as close successful.
return true;
}
//Check the current session has been saved or not.
const int buttonSave=0, buttonCancel=1, buttonAbandon=2;
if(m_changed)
{
//There's a session which is modified but not save.
int result=QMessageBox::question(this,
tr("Close unsaved session"),
tr("Do you want to save the changes you made in the document \"%1\"?").arg(
m_fileName.isEmpty()?tr("Untitled"):m_fileName),
tr("Save"),
tr("Cancel"),
tr("Don't Save"),
buttonSave,
buttonCancel);
switch(result)
{
case buttonSave:
//If we saved fail, then we can't close the document.
if(!onActionSave())
{
return false;
}
case buttonCancel:
//If user cancel close, then stop to close.
return false;
case buttonAbandon:
//Continue close the file.
break;
default:
//You must kidding me if goes here.
return false;
}
}
//Clear the ground data.
clearGroundData();
//Reset the file status data.
m_filePath=QString();
m_fileName=QString();
m_changed=false;
//Disable save and save as.
m_actions[Save]->setEnabled(false);
m_actions[SaveAs]->setEnabled(false);
m_actions[Close]->setEnabled(false);
//Update the panel.
update();
return true;
}
void Ground::onActionChangeBorderColor()
{
//Get the prefer color.
QColor preferBorderColor=
QColorDialog::getColor(m_groundGlobal->borderColor(),
this,
tr("Get border color"),
QColorDialog::ShowAlphaChannel |
QColorDialog::DontUseNativeDialog);
if(!preferBorderColor.isValid())
{
return;
}
//Set the color.
m_groundGlobal->setBorderColor(preferBorderColor);
//Update the panel.
update();
}
void Ground::onActionChangeBarracksColor()
{
//Get the prefer color.
QColor preferBarracksColor=
QColorDialog::getColor(m_groundGlobal->barracksColor(),
this,
tr("Get barracks color"),
QColorDialog::ShowAlphaChannel |
QColorDialog::DontUseNativeDialog);
if(!preferBarracksColor.isValid())
{
return;
}
//Set the color.
m_groundGlobal->setBarracksColor(preferBarracksColor);
//Update the panel.
update();
}
void Ground::onActionChangeRobotColor()
{
//Get the prefer color.
QColor preferRobotColor=
QColorDialog::getColor(Robot::robotColor(),
this,
tr("Get border color"),
QColorDialog::ShowAlphaChannel |
QColorDialog::DontUseNativeDialog);
if(!preferRobotColor.isValid())
{
return;
}
//Set the color.
Robot::setRobotColor(preferRobotColor);
//Update the panel.
update();
}
void Ground::onActionChangeDirectionLineColor()
{
//Get the prefer color.
QColor preferDirectionLineColor=
QColorDialog::getColor(Robot::directionLineColor(),
this,
tr("Get border color"),
QColorDialog::ShowAlphaChannel |
QColorDialog::DontUseNativeDialog);
if(!preferDirectionLineColor.isValid())
{
return;
}
//Set the color.
Robot::setDirectionLineColor(preferDirectionLineColor);
//Update the panel.
update();
}
void Ground::onActionChangeDetectRangeLineColor()
{
//Get the prefer color.
QColor preferDetectRadiusColor=
QColorDialog::getColor(Robot::detectRadiusColor(),
this,
tr("Get border color"),
QColorDialog::ShowAlphaChannel |
QColorDialog::DontUseNativeDialog);
if(!preferDetectRadiusColor.isValid())
{
return;
}
//Set the color.
Robot::setDetectRadiusColor(preferDetectRadiusColor);
//Update the panel.
update();
}
void Ground::clearGroundData()
{
//Clear the border, border information, and barracks.
m_border=QPolygon();
m_borderLines.clear();
m_barracks=QPolygon();
//Remove all the robot datas.
qDeleteAll(m_robotList);
m_robotList.clear();
m_robotInitialAngle.clear();
m_robotInitialPosition.clear();
//Remove all the enemy datas.
qDeleteAll(m_enemyList);
m_enemyList.clear();
m_enemyInitialPosition.clear();
Enemy::setMissionComplete(false);
Enemy::setTarget(QPointF(0,0));
//Reset the counters.
m_reachBorderCount=0;
m_minimumMoveEnemyCount=0;
//Hack way to repaint all the things. WTF!
hide();
show();
//Resize ground.
setFixedSize(0,0);
emit groundSizeChanged(QSize(0,0));
}
bool Ground::readGroundData(const QString &filePath)
{
//Try to open the file.
QFile sessionFile(filePath);
if(sessionFile.open(QIODevice::ReadOnly))
{
//Read the data from the file.
QTextStream sessionStream(&sessionFile);
sessionStream.setCodec("UTF-8");
//Read and parse the json.
QJsonObject sessionObject=
QJsonDocument::fromJson(sessionStream.readAll().toUtf8()).object();
sessionFile.close();
//Generate the border.
QJsonArray borderData=sessionObject.value("Border").toArray();
//Check if the border is vaild or not.
if(borderData.size()<3) //Simplified than a triangle.
{
return false;
}
QPolygonF border;
for(QJsonArray::iterator i=borderData.begin();
i!=borderData.end();
++i)
{
QJsonArray pointData=(*i).toArray();
//The array must contains only x() and y() data of the point.
if(pointData.size()!=2)
{
return false;
}
border.append(QPointF(pointData.at(0).toDouble(),
pointData.at(1).toDouble()));
}
//Generate the barracks.
QJsonArray barracksData=sessionObject.value("Barracks").toArray();
//Check if the barracks is vaild or not.
if(barracksData.size()<3) //Simlified than a triangle.
{
return false;
}
QPolygonF barracks;
for(QJsonArray::iterator i=barracksData.begin();
i!=barracksData.end();
++i)
{
QJsonArray pointData=(*i).toArray();
//The array must contains only x() and y() data of the point.
if(pointData.size()!=2)
{
return false;
}
//Check the point is vaild or not.
QPointF barracksPoint=QPointF(pointData.at(0).toDouble(),
pointData.at(1).toDouble());
if(!border.containsPoint(barracksPoint, Qt::WindingFill))
{
return false;
}
barracks.append(barracksPoint);
}
//Generate the robot list.
QList<Robot *> robotList;
QJsonArray robotsData=sessionObject.value("Robots").toArray();
for(QJsonArray::iterator i=robotsData.begin();
i!=robotsData.end();
++i)
{
//Generate the robot.
QJsonObject robotData=(*i).toObject();
QJsonArray robotPosition=robotData.value("Position").toArray();
if(robotPosition.size()!=2)
{
//Clear the robots that has been genereated.
qDeleteAll(robotList);
return false;
}
Robot *robot=new Robot(robotPosition.at(0).toDouble(),
robotPosition.at(1).toDouble());
robot->setAngle(robotData.value("Angle").toDouble());
robotList.append(robot);
}
//Generate the enemy list.
QList<Enemy *> enemyList;
QJsonArray enemiesData=sessionObject.value("Enemies").toArray();
for(QJsonArray::iterator i=enemiesData.begin();
i!=enemiesData.end();
++i)
{
//Generate enemy.
QJsonObject enemyData=(*i).toObject();
QJsonArray enemyPosition=enemyData.value("Position").toArray();
if(enemyPosition.size()!=2)
{
//Clear the enemies that has been generated.
qDeleteAll(enemyList);
//Clear the robots that has been generated.
qDeleteAll(robotList);
return false;
}
Enemy *enemy=new Enemy(enemyPosition.at(0).toDouble(),
enemyPosition.at(1).toDouble());
enemyList.append(enemy);
}
//If we can go here, then all the data should be ok.
//Set the border, barracks and robots.
setBorder(border);
setBarracks(barracks);
addRobots(robotList);
addEnemies(enemyList);
//Change the file information and flags.
QFileInfo sessionFileInfo(sessionFile);
m_lastOpenFolder=sessionFileInfo.absoluteDir().absolutePath();
m_filePath=sessionFileInfo.absoluteFilePath();
m_fileName=sessionFileInfo.fileName();
m_changed=false;
//Update the image.
update();
//Enabled save and save as actions.
m_actions[Save]->setEnabled(true);
m_actions[SaveAs]->setEnabled(true);
m_actions[Close]->setEnabled(true);
return true;
}
return false;
}
bool Ground::writeGroundData()
{
QFile sessionFile(m_filePath);
if(sessionFile.open(QIODevice::WriteOnly))
{
//Generate the json object.
QJsonObject sessionObject;
QJsonArray border, barracks, robots, enemies;
//Write the border data to session object.
for(QPointF borderPoint : m_border)
{
QJsonArray point;
point.append(borderPoint.x());
point.append(borderPoint.y());
border.append(point);
}
sessionObject.insert("Border", border);
//Write barracks data to session object.
for(QPointF barracksPoint : m_barracks)
{
QJsonArray point;
point.append(barracksPoint.x());
point.append(barracksPoint.y());
barracks.append(point);
}
sessionObject.insert("Barracks", barracks);
//Write robot initial data to session object.
for(int i=0; i<m_robotList.size(); i++)
{
QJsonObject robot;
//Insert the initial position.
QJsonArray position;
const QPointF &robotInitialPos=m_robotInitialPosition.at(i);
position.append(robotInitialPos.x());
position.append(robotInitialPos.y());
robot.insert("Position", position);
//Insert the initial angle.
robot.insert("Angle", m_robotInitialAngle.at(i));
//Add robot to robot list.
robots.append(robot);
}
sessionObject.insert("Robots", robots);
//Write enemy initial data to session object.
for(int i=0; i<m_enemyList.size(); i++)
{
QJsonObject enemy;
//Insert the initial position.
QJsonArray position;
const QPointF &enemyInitialPos=m_enemyInitialPosition.at(i);
position.append(enemyInitialPos.x());
position.append(enemyInitialPos.y());
enemy.insert("Position", position);
//Add enemy to enemy list.
enemies.append(enemy);
}
sessionObject.insert("Enemies", enemies);
//Write the object to file using UTF-8 encoding.
QTextStream sessionStream(&sessionFile);
sessionStream.setCodec("UTF-8");
sessionStream << QJsonDocument(sessionObject).toJson() << flush;
//Close the file.
sessionFile.close();
//Get the file info.
QFileInfo sessionFileInfo(sessionFile);
m_lastSaveFolder=sessionFileInfo.absoluteDir().absolutePath();
return true;
}
return false;
}
inline bool Ground::inDetectRange(Robot *from, Robot *to)
{
return QLineF(from->pos(), to->pos()).length()<Robot::detectRadius();
}
inline void Ground::appointGuardianLine(Robot *robot)
{
qreal minimalDistance=-1.0;
QLineF guardianLine;
QPointF footPoint;
//Get the distance of the robot to all the border line.
for(QLineF line : m_borderLines)
{
QPointF currentFoot;
//Calculate the distance.
qreal currentDistance=getDistance(robot->pos(), line, currentFoot);
//Check the distance.
if(minimalDistance<0.0 || currentDistance<minimalDistance)
{
//Save the minimum distance, and the line's information.
minimalDistance=currentDistance;
guardianLine=line;
footPoint=currentFoot;
}
}
//Set the robot to guard that line.
robot->setGuardianLine(guardianLine, footPoint);
}
inline qreal Ground::pointDistance(const QPointF &a, const QPointF &b)
{
return QLineF(a, b).length();
}
inline qreal Ground::getDistance(const QPointF &point,
const QLineF &line,
QPointF &footPoint)
{
//The line whose angle is 90.0 or 270.0 has no gradient.
//The distance will be the absolute of the difference of x.
if(line.angle()==90.0 || line.angle()==270.0)
{
footPoint=QPointF(line.p1().x(), point.y());
return qAbs(line.p1().x()-point.x());
}
//Calculate the gradient.
qreal k=(line.p2().y()-line.p1().y())/(line.p2().x()-line.p1().x());
//Get the foot point.
qreal footX=(k*k*line.p1().x()+k*(point.y()-line.p1().y())+point.x())/
(k*k+1);
footPoint=QPointF(footX, k*(footX-line.p1().x())+line.p1().y());
//Get the distance.
return QLineF(point, footPoint).length();
}
QPolygonF Ground::barracks() const
{
return m_barracks;
}
bool Ground::addRobot(Robot *robot)
{
//Check the robot.
//If the position of the robot is outside barracks, or there's already have
//a robot, you can't add this robot.
if(!m_barracks.containsPoint(robot->pos(), Qt::WindingFill) ||
m_robotInitialPosition.contains(robot->pos()))
{
//Delete the robot.
delete robot;
return false;
}
//Add the available robot to list.