-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1358 lines (1328 loc) · 40.7 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1358 lines (1328 loc) · 40.7 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"
MainWindow::MainWindow(QWidget *parent) {
table = NULL;
deck = NULL;
fairyPiece = NULL;
dragonPiece = NULL;
drawn = -1;
turn = -1;
active = false;
gameOver = false;
builderRedraw = false;
builderPlaced = false;
innsAndCathedrals = false;
tradersAndBuilders = false;
princessAndDragon = false;
volcanoPlayed = false;
portalActive = false;
placeFairy = false;
baseDir = new QString(qApp->applicationDirPath()); // Deleted in destructor
occupationMapper = new OccupationMapper(baseDir); // Deleted in destructor
QRect rec = QApplication::desktop()->screenGeometry();
zoom = 4;
if (rec.height() < 500) {
zoom = 2;
}
else if (rec.height() < 1200) {
zoom = 3;
}
screenSize = zoom;
}
MainWindow::~MainWindow() {
delete table;
table = NULL;
delete deck;
deck = NULL;
delete occupationMapper;
occupationMapper = NULL;
delete baseDir;
baseDir = NULL;
for (int i = 0; i < merchandiseLabels.size(); ++i) {
delete merchandiseLabels.at(i);
}
delete backDrawPile;
backDrawPile = NULL;
delete backTable;
backTable = NULL;
delete barrelImg;
barrelImg = NULL;
delete barleyImg;
barleyImg = NULL;
delete clothImg;
clothImg = NULL;
delete fairyPiece;
fairyPiece = NULL;
delete dragonPiece;
dragonPiece = NULL;
delete window;
window = NULL;
}
void MainWindow::start(int x, int y, int p, int r, QStringList *decks, QStringList *rulesList) {
QString tempStr;
// Set up rules
innsAndCathedrals = rulesList->contains(tr("inns_and_cathedrals.xml"));
tradersAndBuilders = rulesList->contains(tr("traders_and_builders.xml"));
princessAndDragon = rulesList->contains(tr("the_princess_and_the_dragon.xml"));
if (princessAndDragon) {
tempStr = *baseDir;
tempStr.append("/graphics/dragon_piece.svg");
dragonPiece = new Piece(tempStr, 50, 50, 0.8); // Deleted in destructor
tempStr = *baseDir;
tempStr.append("/graphics/fairy.svg");
fairyPiece = new Piece(tempStr, 150, 150, 0.2); // Deleted in destructor
}
delete rulesList;
// Qt's radiobutton index starts from -2 and decreases (WTF?)
// This way 1st ed rules -> 1, 2nd ed rules -> 2, et.c.
rules = -1 * r - 1;
window = new QWidget(); // Deleted in destructor
// Set up players
QStringList colors;
colors << tr("Red") << tr("Blue") << tr("Green") << tr("Yellow") << tr("Black") << tr("Grey");
for (int i = 0; i < p; ++i) {
QString text = "Pick a color for player ";
text.append(QString::number(i + 1));
bool ok;
QString color;
do {
color = QInputDialog::getItem(this, tr("Choose color"), text, colors, 0, false, &ok);
} while (!ok || color.isEmpty());
for (int j = 0; j < colors.size(); ++j) {
if (color == colors.at(j)) {
colors.removeAt(j);
break;
}
}
players.push_back(new Player(i, color.toLower().toStdString()));
players.at(i)->addFollower(normal, occupationMapper, 7);
if (innsAndCathedrals) {
players.at(i)->addFollower(big, occupationMapper, 1);
}
if (tradersAndBuilders) {
players.at(i)->addFollower(builder, occupationMapper, 1);
players.at(i)->addFollower(pig, occupationMapper, 1);
}
scoreWidgets.push_back(new QWidget(window));
scoreLayouts.push_back(new QVBoxLayout(window));
merchandiseLayouts.push_back(new QHBoxLayout(window));
merchandiseLayouts.at(i)->setAlignment(Qt::AlignLeft);
scoreLabels.push_back(new QLabel(window));
merchandiseLabels.push_back(new vector<QLabel*>()); // Deleted in destructor
scoreWidgets.at(i)->setLayout(scoreLayouts.at(i));
scoreLayouts.at(i)->addWidget(scoreLabels.at(i));
scoreLayouts.at(i)->addLayout(merchandiseLayouts.at(i));
QString score = tr("Player ");
score.append(QString::number(i + 1));
score.append(tr(" score: 0"));
scoreLabels.at(i)->setText(score);
scoreLabels.at(i)->setAlignment(Qt::AlignTop);
}
// Set up deck
table = new Table(x, y); // Deleted in destructor
table->setExpansions(innsAndCathedrals, princessAndDragon);
deck = new Deck(baseDir); // Deleted in destructor
bool core = decks->contains("core.xml");
bool river = decks->contains("river.xml");
bool river2 = decks->contains("river_II.xml");
int mem = 0;
// Load order matters when the river expansions are involved. We want to end
// up with the spring tile first, the appropriate amount of lake tiles last,
// and the tiles in between mixed - but only amongst themselves.
if (river2) {
if (river) {
tempStr = *baseDir;
tempStr.append("/decks/river.xml");
deck->loadTiles(tempStr);
// Erase last (==lake) tile of river expansion when using both.
mem = deck->getSize();
deck->eraseTile(mem - 1);
}
tempStr = *baseDir;
tempStr.append("/decks/river_II.xml");
deck->loadTiles(tempStr);
// If loading both, we then need to erase the first (==spring) tile of
// the river II deck, which is now where the lake tile was before deletion.
// Then we swap the second tile with the river fork tile.
if (river) {
deck->eraseTile(mem - 1);
deck->swapTiles(1, mem - 1);
}
// Leave the two first (spring/fork) and two last tiles (lakes) in place. Shuffle the rest.
deck->shuffleDeck(2, deck->getSize() - 3);
mem = deck->getSize();
}
else if (river) {
tempStr = *baseDir;
tempStr.append("/decks/river.xml");
deck->loadTiles(tempStr);
// When using river only, shuffle all between 1st and last.
deck->shuffleDeck(1, deck->getSize() - 2);
mem = deck->getSize();
}
// If neither expansion is loaded we load core first because of starting tile.
else if (core) {
tempStr = *baseDir;
tempStr.append("/decks/core.xml");
deck->loadTiles(tempStr);
}
for (int i = 0; i < decks->size(); ++i) {
// These are always handled above.
if (decks->at(i) == "river.xml" || decks->at(i) == "river_II.xml") {
continue;
}
// Core is handled iff neither river expansion is loaded
if (decks->at(i) == "core.xml" && !river && !river2) {
continue;
}
tempStr = *baseDir;
tempStr.append("/decks/");
deck->loadTiles(tempStr.append(decks->at(i)));
}
// Shuffle non-river pieces among themselves
if (river || river2) {
deck->shuffleDeck(mem, deck->getSize() - 1);
}
// Shuffle all but first tile
else {
deck->shuffleDeck(1);
}
for (int i = 0; i < deck->getSize(); ++i) {
deck->getTile(i)->launchSetup();
}
delete decks;
decks = NULL;
rotateButtons = new QWidget(window);
zoomButtons = new QWidget(window);
mainLayout = new QHBoxLayout(window);
rotateLayout = new QHBoxLayout(window);
zoomLayout = new QHBoxLayout(window);
tableLayout = new QGridLayout(window);
tableLayout->setHorizontalSpacing(0);
tableLayout->setVerticalSpacing(0);
controlLayout = new QVBoxLayout(window);
currentDraw = new QLabel(window);
tileCounter = new QLabel(window);
// Tile backs image
tempStr = *baseDir;
tempStr.append("/graphics/tile_back.svg");
QSvgRenderer renderer(tempStr);
QImage img(tileSizes[zoom], tileSizes[zoom], IMG_FORMAT);
QPainter painter(&img);
renderer.render(&painter);
backTable = new QPixmap(QPixmap::fromImage(img)); // Deleted in destructor
backDrawPile = new QPixmap(QPixmap::fromImage(img)); // Deleted in destructor
currentDraw->setPixmap(*backDrawPile);
currentDraw->setAlignment(Qt::AlignTop);
// Merchandise images
tempStr = *baseDir;
tempStr.append("/graphics/barrel.svg");
QSvgRenderer renderer1(tempStr);
QImage img1(20, 20, IMG_FORMAT);
QPainter painter1(&img1);
renderer1.render(&painter1);
barrelImg = new QPixmap(QPixmap::fromImage(img1)); // Deleted in destructor
tempStr = *baseDir;
tempStr.append("/graphics/barley.svg");
QSvgRenderer renderer2(tempStr);
QImage img2(20, 20, IMG_FORMAT);
QPainter painter2(&img2);
renderer2.render(&painter2);
barleyImg = new QPixmap(QPixmap::fromImage(img2)); // Deleted in destructor
tempStr = *baseDir;
tempStr.append("/graphics/cloth.svg");
QSvgRenderer renderer3(tempStr);
QImage img3(20, 20, IMG_FORMAT);
QPainter painter3(&img3);
renderer3.render(&painter3);
clothImg = new QPixmap(QPixmap::fromImage(img3)); // Deleted in destructor
// UI setup
controlLayout->addWidget(currentDraw);
tileCounter->setAlignment(Qt::AlignTop);
tileCounter->setAlignment(Qt::AlignHCenter);
tileCounter->setText(QString::number(deck->getSize()));
controlLayout->addWidget(tileCounter);
for (int i = 0; i < scoreWidgets.size(); ++i) {
controlLayout->addWidget(scoreWidgets.at(i));
}
tableArea = new QWidget(window);
tableArea->setLayout(tableLayout);
scroll = new QScrollArea(window);
scroll->setVerticalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAsNeeded);
scroll->setWidgetResizable(true);
for (int i = 0; i < y; ++i) {
for (int j = 0; j < x; ++j) {
tableLayout->addWidget(table->getLabel(j, i), i, j);
table->setPixmap(j, i, backTable);
connect(table->getLabel(j, i), SIGNAL(clicked(QPoint)), this, SLOT(selectedTableLabel()));
}
}
tableLayout->setAlignment(Qt::AlignLeft|Qt::AlignTop);
draw = new QPushButton(tr("Draw tile"), window);
connect(draw, SIGNAL(clicked()), this, SLOT(drawTile()));
rotateCW = new QPushButton(window);
tempStr = *baseDir;
tempStr.append("/graphics/rotate_cw.svg");
QPixmap rotateCWPxm(tempStr);
QIcon rotateCWIcon(rotateCWPxm);
rotateCW->setIcon(rotateCWIcon);
rotateCW->setEnabled(false);
connect(rotateCW, SIGNAL(clicked()), this, SLOT(rotateClockwise()));
rotateCCW = new QPushButton(window);
tempStr = *baseDir;
tempStr.append("/graphics/rotate_ccw.svg");
QPixmap rotateCCWPxm(tempStr);
QIcon rotateCCWIcon(rotateCCWPxm);
rotateCCW->setIcon(rotateCCWIcon);
rotateCCW->setEnabled(false);
connect(rotateCCW, SIGNAL(clicked()), this, SLOT(rotateCounterClockwise()));
zoomInButton = new QPushButton(window);
tempStr = *baseDir;
tempStr.append("/graphics/zoom_in.svg");
QPixmap zoomInPxm(tempStr);
QIcon zoomInIcon(zoomInPxm);
zoomInButton->setIcon(zoomInIcon);
connect(zoomInButton, SIGNAL(clicked()), this, SLOT(zoomIn()));
zoomOutButton = new QPushButton(window);
tempStr = *baseDir;
tempStr.append("/graphics/zoom_out.svg");
QPixmap zoomOutPxm(tempStr);
QIcon zoomOutIcon(zoomOutPxm);
zoomOutButton->setIcon(zoomOutIcon);
connect(zoomOutButton, SIGNAL(clicked()), this, SLOT(zoomOut()));
controlLayout->addStretch();
controlLayout->addWidget(draw);
rotateButtons->setLayout(rotateLayout);
rotateLayout->addWidget(rotateCCW);
rotateLayout->addWidget(rotateCW);
controlLayout->addWidget(rotateButtons);
zoomButtons->setLayout(zoomLayout);
zoomLayout->addWidget(zoomOutButton);
zoomLayout->addWidget(zoomInButton);
controlLayout->addWidget(zoomButtons);
window->setLayout(mainLayout);
scroll->setWidget(tableArea);
mainLayout->addWidget(scroll);
mainLayout->addLayout(controlLayout);
setCentralWidget(window);
advanceTurn();
this->show();
}
void MainWindow::drawTile() {
draw->setEnabled(false);
rotateCW->setEnabled(true);
rotateCCW->setEnabled(true);
++drawn;
if (drawn == deck->getSize() - 1) {
gameOver = true;
}
QPixmap *pxm = deck->getTile(drawn)->getPixmap(tileSizes[screenSize]);
currentDraw->setPixmap(*pxm);
delete pxm;
tileCounter->setText(QString::number(deck->getSize() - drawn - 1));
while (princessAndDragon && !volcanoPlayed && deck->getTile(drawn)->hasTerrainAddon(dragon)) {
QMessageBox::warning(this, "Dragon not in play", "The dragon is not yet in play.\nThe tile will be shuffled into the deck, and a new one drawn.", QMessageBox::Ok);
deck->mixIntoDeck(drawn);
pxm = deck->getTile(drawn)->getPixmap(tileSizes[screenSize]);
currentDraw->setPixmap(*pxm);
delete pxm;
}
if (drawn > 0 && !legalMovesExist(deck->getTile(drawn))) {
QMessageBox::warning(this, "No legal moves", "This tile can not be placed anywhere.\nIt will be discarded, and a new one drawn.", QMessageBox::Ok);
drawTile();
}
else {
active = true;
}
}
bool MainWindow::legalMovesExist(Tile *t) {
int h = table->getHeight();
int w = table->getWidth();
int mask = 255;
int x, y, bothXY;
bool legal = false;
set<int>::iterator b = validPlacePositions.begin();
set<int>::iterator e = validPlacePositions.end();
if (deck->getTile(drawn)->hasTerrain(river)) {
b = validRiverPositions.begin();
e = validRiverPositions.end();
}
for (set<int>::iterator it = b; it != e; ++it) {
bothXY = *it;
x = bothXY >> 8;
y = bothXY & mask;
for (int i = 0; i < 4; ++i) {
if (table->tileFits(t, x, y)) {
legal = true;
}
t->rotateClockwise();
}
if (legal) {
return true;
}
}
return false;
}
void MainWindow::selectedTableLabel() {
currentLabel = (TableLabel*)QObject::sender();
int x, y;
currentLabel->getPosition(&x, &y);
QPixmap *pxm;
vector<Follower*> evict;
QMessageBox::StandardButton reply = QMessageBox::No;
// First check if a portal is letting the user choose where to add a follower
if (portalActive) {
Tile *t = table->getTile(x, y);
if (t == NULL) {
QMessageBox::critical(this, "Illegal move", "Can not place follower on empty tile.", QMessageBox::Ok);
return;
}
if (t->hasDragon()) {
QMessageBox::critical(this, "Illegal move", "DO NOT FEED THE DRAGON!", QMessageBox::Ok);
return;
}
placingTile = t;
goto portalTileSelected;
}
// Then check if we're actually placing the fairy
if (placeFairy) {
Tile *t = table->getTile(x, y);
if (t == NULL) {
QMessageBox::critical(this, "Illegal move", "Can not place fairy on empty tile.", QMessageBox::Ok);
return;
}
Follower *f;
vector<Follower*> fs;
for (int i = 0; i < 16; ++i) {
f = t->getSubtile(i)->getFollower();
if (f != NULL && f->getParent() == players.at(turn)) {
fs.push_back(f);
}
}
if (fs.size() == 0) {
QMessageBox::critical(this, "Illegal move", "You can only place fairy where you already have a follower.", QMessageBox::Ok);
return;
}
if (fs.size() == 1) {
f = fs.at(0);
}
else {
f = haveUserPickFollower(fs, false);
}
for (int i = 0; i < players.size(); ++i) {
vector<Follower*> playerFollowers = players.at(i)->getAllFollowers();
for (int j = 0; j < playerFollowers.size(); ++j) {
playerFollowers.at(j)->setFairy(false);
}
}
f->setFairy(true);
int faX, faY;
table->getFairy(&faX, &faY);
table->setFairy(x, y);
vector<Subtile*> sTiles = f->getPlacement()->getConnections();
Subtile *s = f->getPlacement();
if (!sTiles.empty() && sTiles.at(0)->getParent() == t) {
s = sTiles.at(0);
}
int tileX, tileY;
f->translateSubtileToCoordinates(t->getFairyPosition(s->getPosition()), &tileX, &tileY);
fairyPiece->setPosition(tileX, tileY);
fairyPiece->setSubtile(s);
t->getImageContainer()->setPiece(fairyPiece);
pxm = t->getPixmap(tileSizes[zoom]);
currentLabel->setPixmap(*pxm);
delete pxm;
if (faX >= 0) {
pxm = table->getTile(faX, faY)->getPixmap(tileSizes[zoom]);
table->getLabel(faX, faY)->setPixmap(*pxm);
delete pxm;
}
placeFairy = false;
checkFeatureCompletion();
return;
}
// If we're not in the mode of placing a tile, do nothing.
if (!active) {
return;
}
if (drawn == 0) {
updateValidPositions(x, y, true);
}
// Only the first tile may be placed in a space with no neighboring tiles.
else if (!table->hasNeighbors(x, y)) {
return;
}
// Only legal placements are allowed.
else if (!isValidPosition(x, y)) {
return;
}
// Tile must fit
else if (!table->tileFits(deck->getTile(drawn), x, y)) {
return;
}
// River U-turns not allowed
else if (riverDoesUTurn(x, y)) {
QMessageBox::critical(this, "Illegal move", "River U-turns are not allowed.", QMessageBox::Ok);
return;
}
else {
updateValidPositions(x, y);
}
active = false;
rotateCW->setEnabled(false);
rotateCCW->setEnabled(false);
table->addTile(deck->getTile(drawn), x, y);
deck->getTile(drawn)->setPosition(x, y);
pxm = deck->getTile(drawn)->getPixmap(tileSizes[zoom]);
currentLabel->setPixmap(*pxm);
delete pxm;
currentDraw->setPixmap(*backDrawPile);
// Check if we need to remove a follower
evict = followersToEvict();
if (princessAndDragon && !evict.empty()) {
Follower *evictee;
if (evict.size() == 1) {
evictee = *(evict.begin());
}
else {
evictee = haveUserPickFollower(evict, true);
}
restoreFollowerToPlayer(evictee);
checkFeatureCompletion();
return;
}
// We don't get to place a follower if we drew a volcano tile while
// playing the princess & the dragon expansion
else if (princessAndDragon && deck->getTile(drawn)->hasTerrainAddon(volcano)) {
int drX, drY;
table->getDragon(&drX, &drY);
volcanoPlayed = true;
table->setDragon(x, y);
deck->getTile(drawn)->getImageContainer()->setPiece(dragonPiece);
pxm = deck->getTile(drawn)->getPixmap(tileSizes[zoom]);
currentLabel->setPixmap(*pxm);
delete pxm;
if (drX >= 0) {
pxm = table->getTile(drX, drY)->getPixmap(tileSizes[zoom]);
table->getLabel(drX, drY)->setPixmap(*pxm);
delete pxm;
}
}
// If princess and dragon rules we also want to ask about the fairy
else if (princessAndDragon && canPlaceFairy()) {
QMessageBox msgBox;
QAbstractButton *followerBtn;
msgBox.setWindowTitle(tr("Placing"));
if (players.at(turn)->hasPlayableFollowers()) {
msgBox.setText(tr("Do you wish to place a follower, place the fairy or do nothing?"));
followerBtn = msgBox.addButton(tr("Place follower"), QMessageBox::YesRole);
}
else {
msgBox.setText(tr("Do you wish to place the fairy or do nothing?"));
}
QAbstractButton *fairyBtn = msgBox.addButton(tr("Place fairy"), QMessageBox::NoRole);
QAbstractButton *rejectBtn = msgBox.addButton(tr("Do nothing"), QMessageBox::AcceptRole);
msgBox.exec();
if (msgBox.clickedButton() == fairyBtn) {
placeFairy = true;
QMessageBox::information(this, "Fairy", "Please select tile to place fairy on.", QMessageBox::Ok);
return;
}
else if (msgBox.clickedButton() == followerBtn) {
reply = QMessageBox::Yes;
}
}
// Ask about follower placing
else if (players.at(turn)->hasPlayableFollowers()) {
reply = QMessageBox::question(this, "Placing", "Do you wish to place a follower?", QMessageBox::Yes|QMessageBox::No);
}
if (reply == QMessageBox::Yes) {
if (princessAndDragon && deck->getTile(drawn)->hasTerrainAddon(portal)) {
portalActive = true;
QMessageBox::information(this, "Portal", "Portal allows you to select another tile where to place your follower.", QMessageBox::Ok);
}
placer = new FollowerPlacer(this, portalActive); // Deleted in placeFollower
connect(placer, SIGNAL(followerTypeSelected(FollowerType)), this, SLOT(setFollowerType(FollowerType)));
connect(placer, SIGNAL(keepPortalActive()), this, SLOT(keepPortalActive()));
connect(placer->getLabel(), SIGNAL(clicked(QPoint)), this, SLOT(placeFollower(QPoint)));
placer->setFollowers(players.at(turn)->getAllFollowers());
if (portalActive) {
return;
}
else {
placingTile = deck->getTile(drawn);
}
portalTileSelected:
portalActive = false;
pxm = placingTile->getPixmap();
placer->setImage(pxm);
delete pxm;
placer->exec();
if (portalActive) {
return;
}
}
checkFeatureCompletion();
}
void MainWindow::checkFeatureCompletion() {
// The dragon moves (if applicable) before feature completion check
if (princessAndDragon && volcanoPlayed && deck->getTile(drawn)->hasTerrainAddon(dragon)) {
DragonMover dragonMover(this, table, dragonPiece, scroll, players.size(), turn + 1, tileSizes[zoom]);
dragonMover.exec();
}
// Check monastery completion
vector<Tile*> neighbors = table->getMonasteryNeighbors(deck->getTile(drawn));
for (int i = 0; i < neighbors.size(); ++i) {
if (neighbors.at(i) != NULL && neighbors.at(i)->hasTerrainAddon(monastery) && table->isMonasteryComplete(neighbors.at(i))) {
Follower *temp = neighbors.at(i)->getMonk();
if (temp == NULL) {
continue;
}
if (temp->hasFairy()) {
addScore(3, temp->getParent());
}
restoreFollowerToPlayer(temp);
addScore(9, temp->getParent());
}
}
vector<Subtile*> subs = deck->getTile(drawn)->getDistinctFeatures();
set<Follower*> followers;
// Check if we need to do one more turn
if (!builderRedraw && !builderPlaced && !gameOver) {
for (int i = 0; i < subs.size(); ++i) {
if (subs.at(i)->getTerrain() == city || subs.at(i)->getTerrain() == road) {
followers= table->getAllFollowersInFeature(subs.at(i));
for (set<Follower*>::iterator it=followers.begin(); it!=followers.end(); ++it) {
Follower *temp = *it;
if (temp->getType() == builder && temp->getParent()->getPlayerNumber() == turn) {
builderRedraw = true;
break;
}
}
}
}
}
else {
builderRedraw = false;
}
// Check road & city completion
for (int i = 0; i < subs.size(); ++i) {
// Monasteries are checked elsewhere.
if (subs.at(i)->getTerrainAddon() == monastery) {
continue;
}
if ((subs.at(i)->getTerrain() == road && table->isRoadComplete(subs.at(i))) || (subs.at(i)->getTerrain() == city && table->isCityComplete(subs.at(i)))) {
followers = table->getAllFollowersInFeature(subs.at(i));
vector<int> playerWeight;
vector<bool> playerHasFairy;
playerWeight.assign(players.size(), 0);
playerHasFairy.assign(players.size(), false);
for (set<Follower*>::iterator it=followers.begin(); it!=followers.end(); ++it) {
Follower *temp = *it;
switch(temp->getType()) {
case big:
++playerWeight.at(temp->getParent()->getPlayerNumber());
case normal:
++playerWeight.at(temp->getParent()->getPlayerNumber());
if (temp->hasFairy()) {
playerHasFairy.at(temp->getParent()->getPlayerNumber()) = true;
}
break;
default:
break;
}
restoreFollowerToPlayer(temp);
}
int max = getMaxValue(playerWeight);
int score = table->getFeatureScore(subs.at(i), rules);
if (tradersAndBuilders) {
int barrels, barley, spools;
table->getMerchandise(&barrels, &barley, &spools);
addMerchandise(barrels, barley, spools);
}
if (max > 0) {
for (int j = 0; j < playerWeight.size(); ++j) {
if (playerWeight.at(j) == max) {
addScore(score, j);
if (playerHasFairy.at(j)) {
addScore(3, j);
}
}
}
}
}
}
if (!builderRedraw) {
advanceTurn();
}
else {
draw->setEnabled(true);
}
}
void MainWindow::keepPortalActive() {
portalActive = true;
}
int MainWindow::getMaxValue(vector<int> v) {
int max = 0;
for (int i = 0; i < v.size(); ++i) {
if (v.at(i) > max) {
max = v.at(i);
}
}
return max;
}
void MainWindow::rotateClockwise() {
deck->getTile(drawn)->rotateClockwise();
QPixmap *pxm = deck->getTile(drawn)->getPixmap(tileSizes[screenSize]);
currentDraw->setPixmap(*pxm);
delete pxm;
}
void MainWindow::rotateCounterClockwise() {
deck->getTile(drawn)->rotateCounterClockwise();
QPixmap *pxm = deck->getTile(drawn)->getPixmap(tileSizes[screenSize]);
currentDraw->setPixmap(*pxm);
delete pxm;
}
void MainWindow::zoomIn() {
if (zoom < 5) {
int visible = 0;
vector<TableLabel*> labels = table->getLabels();
vector<Tile*> tiles = table->getTiles();
for (int i = 0; i < labels.size() ; ++i) {
if (tiles.at(i) != NULL) {
// First we get the first tile that's not empty...
if (visible == 0) {
visible = i;
}
// ...but what we really want is the first *visible* tile that's not empty - if it exists.
if (!labels.at(i)->visibleRegion().isEmpty()) {
visible = i;
break;
}
}
}
++zoom;
redrawTable();
// redrawTable() already does the qApp->processEvents(), but for reasons known by Cthulhu,
// Sauron and maybe some other entities of ancient evil, it won't actually work unless done
// again here... so we do it again here. :-P
qApp->processEvents();
scroll->ensureWidgetVisible(labels.at(visible), tileSizes[zoom], tileSizes[zoom]);
}
}
void MainWindow::zoomOut() {
if (zoom > 0) {
int visible = 0;
vector<TableLabel*> labels = table->getLabels();
vector<Tile*> tiles = table->getTiles();
for (int i = 0; i < labels.size() ; ++i) {
if (tiles.at(i) != NULL) {
if (visible == 0) {
visible = i;
}
if (!labels.at(i)->visibleRegion().isEmpty()) {
visible = i;
break;
}
}
}
--zoom;
redrawTable();
qApp->processEvents();
scroll->ensureWidgetVisible(labels.at(visible), tileSizes[zoom], tileSizes[zoom]);
}
}
void MainWindow::restoreFollowerToPlayer(Follower *f) {
if (f == NULL) {
return;
}
Tile *t = f->getPlacement()->getParent();
t->getImageContainer()->removeFollower(f);
f->getPlacement()->setFollower(NULL);
QPixmap *pxm = t->getPixmap(tileSizes[zoom]);
TableLabel *tl = table->getLabel(t->getX(), t->getY());
tl->setPixmap(*pxm);
delete pxm;
f->setPlacement(NULL);
}
void MainWindow::redrawTable() {
QString tempStr(*baseDir);
tempStr.append("/graphics/tile_back.svg");
QSvgRenderer renderer(tempStr);
QImage img(tileSizes[zoom], tileSizes[zoom], IMG_FORMAT);
QPainter painter(&img);
renderer.render(&painter);
delete backTable;
backTable = new QPixmap(QPixmap::fromImage(img));
vector<Tile*> tiles = table->getTiles();
vector<TableLabel*> labels = table->getLabels();
for (int i = 0; i < tiles.size(); ++i) {
if (tiles.at(i) == NULL) {
labels.at(i)->setPixmap(*backTable);
}
else {
QPixmap *pxm = tiles.at(i)->getPixmap(tileSizes[zoom]);
labels.at(i)->setPixmap(*pxm);
delete pxm;
}
}
qApp->processEvents();
}
void MainWindow::advanceTurn() {
builderPlaced = false;
++turn;
if (turn == players.size()) {
turn = 0;
}
for (int i = 0; i < scoreLabels.size(); ++i) {
QString style = "color: ";
style.append(htmlColorMap()[players.at(i)->getColor()].c_str());
style.append("; border: 0px");
if (i == turn) {
scoreWidgets.at(i)->setStyleSheet(tr("border: 5px solid black"));
for (int j = 0; j < merchandiseLabels.at(i)->size(); ++j) {
merchandiseLabels.at(i)->at(j)->setStyleSheet(tr("border: 0px"));
}
}
else {
scoreWidgets.at(i)->setStyleSheet(tr("border: 0px"));
}
scoreLabels.at(i)->setStyleSheet(style);
}
if (gameOver) {
countFinalScore();
}
else {
// Award a point to a player who starts with the fairy.
if (princessAndDragon) {
vector<Follower*> followers = players.at(turn)->getAllFollowers();
for (int i = 0; i < followers.size(); ++i) {
if (followers.at(i)->hasFairy()) {
addScore(1, turn);
break;
}
}
}
draw->setEnabled(true);
}
}
void MainWindow::placeFollower(const QPoint p) {
int subnum = translatePointToSubtile(p.x(), p.y(), IMG_DEFAULT_SIZE);
Subtile *subtile = placingTile->getSubtile(subnum);
bool found = false;
set<Follower*> followers;
switch(followerType) {
case normal:
case big:
if (table->doesFeatureContainFollowers(subtile, true)) {
QMessageBox::critical(this, "Illegal move", "Illegal move. That feature already has a follower.", QMessageBox::Ok);
placer->raise();
return;
}
break;
case builder:
if (subtile->getTerrain() != city && subtile->getTerrain() != road) {
QMessageBox::critical(this, "Illegal move", "Illegal move. Builders may only be added to cities and roads.", QMessageBox::Ok);
placer->raise();
return;
}
followers = table->getAllFollowersInFeature(subtile);
for (set<Follower*>::iterator it = followers.begin(); it != followers.end(); ++it) {
Follower *f = *it;
if (f->getParent()->getPlayerNumber() == turn) {
found = true;
break;
}
}
if (!found) {
QMessageBox::critical(this, "Illegal move", "Illegal move. Builders may only be added where you already have a follower.", QMessageBox::Ok);
placer->raise();
return;
}
break;
case pig:
if (subtile->getTerrain() != field) {
QMessageBox::critical(this, "Illegal move", "Illegal move. Pigs may only be added to fields.", QMessageBox::Ok);
placer->raise();
return;
}
followers = table->getAllFollowersInFeature(subtile);
for (set<Follower*>::iterator it = followers.begin(); it != followers.end(); ++it) {
Follower *f = *it;
if (f->getParent()->getPlayerNumber() == turn) {
found = true;
break;
}
}
if (!found) {
QMessageBox::critical(this, "Illegal move", "Pigs may only be added where you already have a follower.", QMessageBox::Ok);
placer->raise();
return;
}
break;
}
// If the placing is done via portal on some other tile than the one just
// drawn, we need to check for some further possible illegal moves
if (placingTile != deck->getTile(drawn)) {
if (subtile->getTerrainAddon() == monastery) {
if (table->isMonasteryComplete(placingTile)) {
QMessageBox::critical(this, "Illegal move", "You can not add a follower to a feature that has already been completed.", QMessageBox::Ok);
placer->raise();
return;
}
}
else if ((subtile->getTerrain() == city && table->isCityComplete(subtile)) ||
(subtile->getTerrain() == road && table->isRoadComplete(subtile))) {
QMessageBox::critical(this, "Illegal move", "You can not add a follower to a feature that has already been completed.", QMessageBox::Ok);
placer->raise();
return;
}
}
QString message = tr("Confirm that you want to add ");
if (subtile->getTerrainAddon() == monastery) {
message.append("a monk to the monastery.");
}
else {
switch (subtile->getTerrain()) {
case road:
if (followerType == builder) {
message.append("a builder to the road.");
}
else {
message.append("a bandit to the road.");
}
break;
case city:
if (followerType == builder) {
message.append("a builder to the city.");
}
else {
message.append("a knight to the city.");
}
break;
case field:
if (followerType == pig) {
message.append("a pig to the field.");
}
else {
message.append("a farmer to the field.");
}
break;
default:
QMessageBox::warning(this, tr("Invalid terrain"), tr("You can not place a follower there."), QMessageBox::Ok);
placer->raise();
return;
}
}
QMessageBox::StandardButton reply;
reply = QMessageBox::question(this, tr("Confirmation request"), message, QMessageBox::Ok|QMessageBox::Cancel);
if (reply == QMessageBox::Cancel) {
placer->raise();
return;
}
placer->close();
delete placer;
placer = NULL;
if (followerType == builder) {
builderPlaced = true;
}
Follower *f = players.at(turn)->getFollower(followerType);
subtile->setFollower(f);
f->setPlacement(subtile);
// Are we adding the follower to a tile/feature where the fairy already is?
if (princessAndDragon && subtile->isOnSameFeatureAndTile(fairyPiece->getSubtile())) {
f->setFairy(true);
}
placingTile->getImageContainer()->addFollower(f);
QPixmap *pxm = placingTile->getPixmap(tileSizes[zoom]);
currentLabel->setPixmap(*pxm);
delete pxm;
}
// If this makes no sense, stare at the ascii diagram in tile.h
// until it does (or your eyes start to bleed, whichever comes first)
int MainWindow::translatePointToSubtile(int x, int y, int size) {
int third = size / 3;
int twoThirds = 2 * size / 3;
if (x < third) { // Leftmost third
if (y < third) { // Upper left corner
if (x > y) { // Upper right triangle
return 0;
}
else { // Lower left triangle
return 11;
}
}
else if (y < twoThirds) { // Middle left
return 10;
}
else { // Lower left corner
if (x + y - twoThirds > third) { // Right lower triangle
return 8;
}
else {
return 9;
}
}
}
else if (x < twoThirds) { // Middle column
if (y < third) { // Upper area
return 1;
}
else if (y > twoThirds) { // Lower area
return 7;
}
else { // Absolute center
if (x > y) { // Upper right
if (x + y > size) { // Right
return 13;
}
else {
return 12; // Upper
}
}