File: boardwidget.cpp

package info (click to toggle)
kmahjongg 4:4.14.0-1
  • links: PTS, VCS
  • area: main
  • in suites: jessie, jessie-kfreebsd
  • size: 1,968 kB
  • ctags: 427
  • sloc: cpp: 3,945; makefile: 9; sh: 2
file content (1270 lines) | stat: -rw-r--r-- 35,579 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
/* Copyright (C) 1997 Mathias Mueller   <in5y158@public.uni-hamburg.de>
 * Copyright (C) 2006 Mauricio Piacentini   <mauricio@tabuleiro.com>
 *
 * Kmahjongg 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 "boardwidget.h"
#include "prefs.h"

#include <QTimer>
#include <qpainter.h>
#include <qapplication.h>

#include <klocale.h>
#include <kstandarddirs.h>
#include <kmessagebox.h>
#include <krandom.h>
#include <kconfig.h>
#include <kglobal.h>
#include <KDebug>


BoardWidget::BoardWidget(QWidget *parent)
    : KGameCanvasWidget(parent),
    theTiles()
{
    QPalette palette;
    palette.setColor(backgroundRole(), Qt::black);
    setPalette(palette);

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(helpMoveTimeout()));

    TimerState = Stop;
    gamePaused = false;
    iTimerStep = 0;
    matchCount = 0;
    showMatch = false;
    showHelp = false;

    //memset( &Game->Mask, 0, sizeof( Game->Mask ) );
    gameGenerationNum = 0;
    m_angle = (TileViewAngle) Prefs::angle();

    // Load layout first
    loadBoardLayout(Prefs::layout());

    //Initialize our Game structure
    Game = new GameData(theBoardLayout.board());

    MouseClickPos1.e = Game->m_depth;     // mark tile position as invalid
    MouseClickPos2.e = Game->m_depth;

    //Animation timers
    animateForwardTimer = new QTimer(this);
    animateForwardTimer->setSingleShot(true);
    animateForwardTimer->setInterval(100);
    connect(animateForwardTimer, SIGNAL(timeout()), SLOT(animatingMoveListForward()));
    animateForwardTimer->stop();

    animateBackwardsTimer = new QTimer(this);
    animateBackwardsTimer->setSingleShot(true);
    animateBackwardsTimer->setInterval(100);
    connect(animateBackwardsTimer, SIGNAL(timeout()), SLOT(animatingMoveListBackwards()));
    animateBackwardsTimer->stop();

    loadSettings();
}

BoardWidget::~BoardWidget()
{
    delete Game;
}

void BoardWidget::loadSettings()
{
    // Load tileset. First try to load the last use tileset

    if (!loadTileset(Prefs::tileSet())) {
        kDebug() << "An error occurred when loading the tileset" << Prefs::tileSet() << "KMahjongg "
            "will continue with the default tileset.";
    }

    // Load background
    if (!loadBackground(Prefs::background(), false)) {
        kDebug() << "An error occurred when loading the background" << Prefs::background() << "KMah"
            "jongg will continue with the default background.";
    }

    setShowMatch(Prefs::showMatchingTiles());

    // If the random layout is activated, we won't load a boardlayout, as it will be created
    // randomly in calculateNewGame().
    if (!Prefs::randomLayout()) {
        if (QString::compare(Prefs::layout(), theBoardLayout.path(), Qt::CaseSensitive) !=0 ) {
            //TODO: WARN USER HERE ABOUT DESTRUCTIVE OPERATION!!!
            loadBoardLayout(Prefs::layout());
            calculateNewGame();
        }
    } else {
        calculateNewGame();
    }

    setDisplayedWidth();
    drawBoard(true);

    //Store our updated settings, some values might have been changed to defaults
    saveSettings();
}

void BoardWidget::resizeEvent(QResizeEvent *event)
{
    if (event->spontaneous()) {
        return;
    }

    resizeTileset(event->size());
    theBackground.sizeChanged(requiredWidth(), requiredHeight());
    drawBoard(true);
}

void BoardWidget::resizeTileset(const QSize &wsize)
{
    QSize newtiles = theTiles.preferredTileSize(wsize, requiredHorizontalCells(),
        requiredVerticalCells());

    theTiles.reloadTileset(newtiles);
    stopMatchAnimation();
}

void BoardWidget::saveSettings()
{
    Prefs::setTileSet(theTiles.path());
    Prefs::setLayout(theBoardLayout.path());
    Prefs::setBackground(theBackground.path());
    Prefs::setAngle(m_angle);
    Prefs::self()->writeConfig();
}

void BoardWidget::setDisplayedWidth()
{
    //TODO remove method and let the layout handle it
    //for now we just force our resizeEvent() to be called
    resize(width(), height());
}

void BoardWidget::populateSpriteMap()
{
    //Delete previous sprites (full update), synchronize state with GameData
    while (!items()->isEmpty()) {
        delete items()->first();
    }

    //Clear our spritemap as well
    spriteMap.clear();

    //Recreate our background
    QPalette palette;
    palette.setBrush(backgroundRole(), theBackground.getBackground());
    setPalette(palette);
    setAutoFillBackground(true);

    //create the sprites
    for (int z = 0; z < Game->m_depth; z++) {
        // we draw down the board so the tile below over rights our border
        for (int y = 0; y < Game->m_height; y++) {
            // drawing right to left to prevent border overwrite
            for (int x = Game->m_width - 1; x >= 0; x--) {

                // skip if no tile to display
                if (!Game->tilePresent(z, y, x)) {
                    continue;
                }

                QPixmap s;
                QPixmap us;
                QPixmap f;
                bool selected = false;
                s = theTiles.selectedTile(m_angle);
                us = theTiles.unselectedTile(m_angle);
                f = theTiles.tileface(Game->BoardData(z, y, x) - TILE_OFFSET);

                if (Game->HighlightData(z, y, x)) {
                    selected = true;
                }

                TileSprite *thissprite = new TileSprite(this, us, s, f, m_angle, selected);

                spriteMap.insert(TileCoord(x, y, z), thissprite);
            }
        }
    }

    updateSpriteMap();
}

void BoardWidget::updateSpriteMap()
{
    // initial offset on the screen of tile 0,0
    // think of it as what is left if you add all tilefaces (qwidth/heigh*2) plus one
    // (wholetile - shadow(3dindent) - tileface), and divide by 2
    int xOffset = (width() - (Game->m_width * (theTiles.qWidth())) - (theTiles.width()
        - (theTiles.qWidth() * 2))) / 2;
    int yOffset = (height() - (Game->m_height * (theTiles.qHeight())) - (theTiles.height()
        - (theTiles.qHeight() * 2))) / 2;

    // we iterate over the depth stacking order. Each successive level is
    // drawn one indent up and to the right. The indent is the width
    // of the 3d relief on the tile left (tile shadow width)
    switch (m_angle) {
    case NW:
        //remove shadow from margin calculation
        xOffset += theTiles.levelOffsetX() / 2;
            yOffset += theTiles.levelOffsetY() / 2;

        //Position
        for (int z = 0; z < Game->m_depth; z++) {
            // we draw down the board so the tile below over rights our border
            for (int y = 0; y < Game->m_height; y++) {
            // drawing right to left to prevent border overwrite
                for (int x=Game->m_width - 1; x >= 0; x--) {
                    int sx = x * (theTiles.qWidth()) + xOffset;
                    int sy = y * (theTiles.qHeight()) + yOffset;

                    // skip if no tile to display
                    if (!Game->tilePresent(z, y, x)) {
                        continue;
                    }

                    TileSprite *thissprite = spriteMap.value(TileCoord(x, y, z));

                    if (thissprite) {
                        thissprite->moveTo(sx, sy);
                    }

                    if (thissprite) {
                        thissprite->show();
                    }
                }
            }

            xOffset += theTiles.levelOffsetX();
            yOffset -= theTiles.levelOffsetY();
        }

        //Layer
        for (int z = 0; z < Game->m_depth; z++) {
            // start drawing in diagonal for correct layering. For this we double the board,
            //actually starting outside of it, in the bottom right corner, so our first diagonal ends
            // at the actual top right corner of the board
            for (int x = Game->m_width * 2; x >= 0; x--) {
                // reset the offset
                int offset = 0;

                for (int y = Game->m_height - 1; y >= 0; y--) {
                    if (Game->tilePresent(z, y, x - offset)) {
                        TileSprite *thissprite = spriteMap.value(TileCoord(x - offset, y, z));

                        if (thissprite) {
                            thissprite->raise();
                        }
                    }

                    //at each pass, move one place to the left
                    offset++;
                }
            }
        }

        break;

    case NE:
        xOffset -= theTiles.levelOffsetX() / 2;
        yOffset += theTiles.levelOffsetY() / 2;

        //Position
        for (int z = 0; z < Game->m_depth; z++) {
            // we draw down the board so the tile below over rights our border
            for (int y = 0; y < Game->m_height; y++) {
                // drawing right to left to prevent border overwrite
                for (int x = 0; x <= Game->m_width - 1; x++) {
                    int sx = x * (theTiles.qWidth()) + xOffset;
                    int sy = y * (theTiles.qHeight()) + yOffset;

                    // skip if no tile to display
                    if (!Game->tilePresent(z, y, x)) {
                        continue;
                    }

                    TileSprite *thissprite = spriteMap.value(TileCoord(x, y, z));

                    if (thissprite) {
                        thissprite->moveTo(sx, sy);
                    }

                    if (thissprite) {
                        thissprite->show();
                    }
                }
            }

            xOffset -= theTiles.levelOffsetX();
            yOffset -= theTiles.levelOffsetY();
        }

        //Layer
        for (int z = 0; z < Game->m_depth; z++) {
            // start drawing in diagonal for correct layering. For this we double the board,
            //actually starting outside of it, in the bottom right corner, so our first diagonal ends
            // at the actual top right corner of the board
            for (int x =- (Game->m_width); x <= Game->m_width - 1; x++) {
                // reset the offset
                int offset = 0;

                for (int y = Game->m_height - 1; y >= 0; y--) {
                    if (Game->tilePresent(z, y, x + offset)) {
                        TileSprite *thissprite = spriteMap.value(TileCoord(x + offset, y, z));

                        if (thissprite) {
                            thissprite->raise();
                        }
                    }

                    //at each pass, move one place to the right
                    offset++;
                }
            }
        }

        break;

    case SE:
        xOffset -= theTiles.levelOffsetX() / 2;
        yOffset -= theTiles.levelOffsetY() / 2;

        //Position
        for (int z = 0; z < Game->m_depth; z++) {
            for (int y = Game->m_height - 1; y >= 0; y--) {
                for (int x = 0; x <= Game->m_width - 1; x++) {
                    int sx = x * (theTiles.qWidth()) + xOffset;
                    int sy = y * (theTiles.qHeight()) + yOffset;

                    if (!Game->tilePresent(z, y, x)) {
                        continue;
                    }

                    TileSprite *thissprite = spriteMap.value(TileCoord(x, y, z));

                    if (thissprite) {
                        thissprite->moveTo(sx, sy);
                    }

                    if (thissprite) {
                        thissprite->show();
                    }
                }
            }

            xOffset -= theTiles.levelOffsetX();
            yOffset += theTiles.levelOffsetY();
        }

        //Layer
        for (int z = 0; z < Game->m_depth; z++) {
            for (int x =- (Game->m_width); x <= Game->m_width - 1; x++) {
                int offset = 0;

                for (int y = 0; y < Game->m_height; y++) {
                    if (Game->tilePresent(z, y, x + offset)) {
                        TileSprite *thissprite = spriteMap.value(TileCoord(x + offset, y, z));
                        if (thissprite) {
                            thissprite->raise();
                        }
                    }

                    offset++;
                }
            }
        }

        break;

    case SW:
        xOffset += theTiles.levelOffsetX() / 2;
        yOffset -= theTiles.levelOffsetY() / 2;

        //Position
        for (int z = 0; z < Game->m_depth; z++) {
            for (int y = Game->m_height - 1; y >= 0; y--) {
                for (int x = Game->m_width - 1; x >= 0; x--) {
                    int sx = x * (theTiles.qWidth()) + xOffset;
                    int sy = y * (theTiles.qHeight()) + yOffset;

                    if (!Game->tilePresent(z, y, x)) {
                        continue;
                    }

                    TileSprite *thissprite = spriteMap.value(TileCoord(x, y, z));

                    if (thissprite) {
                        thissprite->moveTo(sx, sy);
                    }

                    if (thissprite) {
                        thissprite->show();
                    }
                }
            }

            xOffset += theTiles.levelOffsetX();
            yOffset += theTiles.levelOffsetY();
        }

        //Layer
        for (int z = 0; z < Game->m_depth; z++) {
            for (int x = Game->m_width * 2; x >= 0; x--) {
                int offset = 0;

                for (int y = 0; y < Game->m_height; y++) {
                    if (Game->tilePresent(z, y, x - offset)) {
                        TileSprite *thissprite = spriteMap.value(TileCoord(x - offset, y, z));

                        if (thissprite) {
                            thissprite->raise();
                        }
                    }

                    offset++;
                }
            }
        }

        break;
    }
}

void BoardWidget::pause()
{
    gamePaused = !gamePaused;
    drawBoard(!gamePaused);
}

void BoardWidget::gameLoaded()
{
    int i;
    Game->initialiseRemovedTiles();
    i = Game->TileNum;

    // use the history of moves to put in the removed tiles area the correct tiles
    while (i < Game->MaxTileNum) {
        Game->setRemovedTilePair(Game->MoveListData(i), Game->MoveListData(i + 1));
        i += 2;
    }

    populateSpriteMap();
    drawBoard(true);
}

int BoardWidget::undoMove()
{
    cancelUserSelectedTiles();

    if (Game->TileNum < Game->MaxTileNum)
    {
        Game->clearRemovedTilePair(Game->MoveListData(Game->TileNum), Game->MoveListData(
            Game->TileNum + 1));
        putTileInBoard(Game->MoveListData(Game->TileNum), false);
        Game->TileNum++;
        putTileInBoard(Game->MoveListData(Game->TileNum));
        Game->TileNum++;
        drawTileNumber();
        setStatusText(i18n("Undo operation done successfully."));

        return 1;
    } else {
        setStatusText(i18n("What do you want to undo? You have done nothing!"));

        return 0;
    }
}

void BoardWidget::helpMove()
{
    cancelUserSelectedTiles();
    if (showHelp) helpMoveStop();

    if (Game->findMove(TimerPos1, TimerPos2)) {
        cheatsUsed++;
        iTimerStep = 1;
        showHelp = true;
        helpMoveTimeout();
    } else {
        setStatusText(i18n("Sorry, you have lost the game."));
    }
}

void BoardWidget::helpMoveTimeout()
{
    if (iTimerStep & 1) {
        hilightTile(TimerPos1, true, false);
        hilightTile(TimerPos2, true);
    } else {
        hilightTile(TimerPos1, false, false);
        hilightTile(TimerPos2, false);
    }

    // restart timer
    if (iTimerStep++ < 8) {
        timer->setSingleShot(true);
        timer->start(ANIMSPEED);
    } else {
        showHelp = false;
    }
}

void BoardWidget::helpMoveStop()
{
    timer->stop();
    iTimerStep = 8;
    hilightTile(TimerPos1, false, false);
    hilightTile(TimerPos2, false);
    showHelp = false;
}

void BoardWidget::startDemoMode()
{
    calculateNewGame();

    if (TimerState == Stop) {
        TimerState = Demo;
        iTimerStep = 0;
        emit demoModeChanged(true);
        setStatusText(i18n("Demo mode. Click mousebutton to stop."));
        demoMoveTimeout();
    }
}

void BoardWidget::stopDemoMode()
{
    TimerState = Stop;    // stop demo
    calculateNewGame();
    setStatusText(i18n("Now it is you again."));

    emit demoModeChanged(false);
    emit gameCalculated();
}

void BoardWidget::demoMoveTimeout()
{
    if (TimerState == Demo) {
        switch (iTimerStep++ % 6) {
        case 0:
            if (!Game->findMove(TimerPos1, TimerPos2)) {
                // if computer has won
                if (Game->TileNum == 0) {
                    animateMoveList();
                } else {
                    setStatusText(i18n("Your computer has lost the game."));

                    while (Game->TileNum < Game->MaxTileNum) {
                        putTileInBoard(Game->MoveListData(Game->TileNum), false);
                        Game->TileNum++;
                        putTileInBoard(Game->MoveListData(Game->TileNum));
                        Game->TileNum++;
                        drawTileNumber();
                    }
                }

                TimerState = Stop;
                //startDemoMode();
                //do not loop demo
                stopDemoMode();

                return;
            }

            break;

        case 1:
        case 3:
            hilightTile(TimerPos1, true, false);
            hilightTile(TimerPos2, true);

            break;

        case 2:
        case 4:
            hilightTile(TimerPos1, false, false);
            hilightTile(TimerPos2, false);

            break;

        case 5:
            Game->setRemovedTilePair(TimerPos1, TimerPos2);
            removeTile(TimerPos1, false);
            removeTile(TimerPos2);
            drawTileNumber();

            break;
        }

        // restart timer
        QTimer::singleShot(ANIMSPEED, this, SLOT(demoMoveTimeout()));
    }
}

void BoardWidget::setShowMatch(bool show)
{
    if (showMatch) {
        stopMatchAnimation();
    }

    showMatch = show;
}

void BoardWidget::matchAnimationTimeout()
{
    if (matchCount == 0) {
        return;
    }

    if (iTimerStep++ & 1) {
        for (short Pos = 0; Pos < matchCount; Pos++) {
          hilightTile(Game->getFromPosTable(Pos), true);
        }
    } else {
        for (short Pos = 0; Pos < matchCount; Pos++) {
          hilightTile(Game->getFromPosTable(Pos), false);
        }
    }

    if (TimerState == Match) {
        QTimer::singleShot(ANIMSPEED, this, SLOT(matchAnimationTimeout()));
    }
}

void BoardWidget::stopMatchAnimation()
{
    for (short Pos = 0; Pos < matchCount; Pos++) {
      hilightTile(Game->getFromPosTable(Pos), false);
    }

    TimerState = Stop;
    matchCount = 0;
}

void BoardWidget::redoMove()
{
    Game->setRemovedTilePair(Game->MoveListData(Game->TileNum - 1), Game->MoveListData(Game->TileNum
        - 2));
    removeTile(Game->MoveListData(Game->TileNum - 1), false);
    removeTile(Game->MoveListData(Game->TileNum - 1));
    drawTileNumber();
}

void BoardWidget::animateMoveList()
{
    setStatusText(i18n("Congratulations. You have won!"));
    animatingMoveListForward();
}

void BoardWidget::animatingMoveListForward()
{
    if (Game->TileNum < Game->MaxTileNum) {
        // put back all tiles
        putTileInBoard(Game->MoveListData(Game->TileNum));
        Game->TileNum++;
        putTileInBoard(Game->MoveListData(Game->TileNum), false);
        Game->TileNum++;
        drawTileNumber();
        animateForwardTimer->start(); //it is a single shot timer
    } else {
        //start removal
      animateBackwardsTimer->start(); //it is a single shot timer
    }
}

void BoardWidget::animatingMoveListBackwards()
{
    if (Game->TileNum > 0) {
        // remove all tiles
        removeTile(Game->MoveListData(Game->TileNum - 1), false);
        removeTile(Game->MoveListData(Game->TileNum - 1));
        drawTileNumber();
        animateBackwardsTimer->start(); //it is a single shot timer
    } else {
        //end of animation
        stopEndAnimation();
    }
}

void BoardWidget::stopEndAnimation()
{
    animateForwardTimer->stop();
    animateBackwardsTimer->stop();
}

QString BoardWidget::getRandomLayoutName() const
{
    QStringList tilesAvailable = KGlobal::dirs()->findAllResources("kmahjongglayout",
        QString("*.desktop"), KStandardDirs::Recursive);

    return tilesAvailable.at(qrand() % tilesAvailable.size());
}

void BoardWidget::calculateNewGame(int gNumber)
{
    cancelUserSelectedTiles();
    stopMatchAnimation();
    stopEndAnimation();
    Game->initialiseRemovedTiles();

    // If random layout is true, we will create a new random layout from the existing layouts.
    if (Prefs::randomLayout()) {
        QString layoutName = getRandomLayoutName();
        loadBoardLayout(layoutName);
    }

    setStatusText(i18n("Calculating new game..."));

    if (!loadBoard()) {
        setStatusText(i18n("Error converting board information!"));

        return;
    }

    if (gNumber == -1) {
        gameGenerationNum = KRandom::random();
    } else {
        gameGenerationNum = gNumber;
    }

    Game->random.setSeed(gameGenerationNum);

    // Translate Game->Map to an array of POSITION data.  We only need to
    // do this once for each new game.
    Game->generateTilePositions();

    // Now use the tile position data to generate tile dependency data.
    // We only need to do this once for each new game.
    Game->generatePositionDepends();

    // Now try to position tiles on the board, 64 tries max.
    for (short nr = 0; nr < 64; nr++) {
        if (Game->generateStartPosition2()) {
            drawBoard(true);
            setStatusText(i18n("Ready. Now it is your turn."));
            cheatsUsed = 0;
            emit gameCalculated();

            return;
        }
    }

    drawBoard(false);
    setStatusText(i18n("Error generating new game!"));
}

void BoardWidget::hilightTile(POSITION& Pos, bool on, bool doRepaint)
{
    TileSprite *atile = 0;
    TileCoord coord = TileCoord(Pos.x, Pos.y, Pos.e);

    if (spriteMap.contains(coord)) {
        atile = spriteMap.value(coord);
    }

    if (on) {
        Game->setHighlightData(Pos.e, Pos.y, Pos.x, 1);
        if (atile) {
            atile->setSelected(true);
        }
    } else {
        Game->setHighlightData(Pos.e, Pos.y, Pos.x, 0);
        if (atile) {
            atile->setSelected(false);
        }
    }
}

void BoardWidget::drawBoard(bool showTiles)
{
    if (gamePaused) {
        showTiles = false;
    }

    if (showTiles) {
        populateSpriteMap();
        drawTileNumber();
    } else {
        //Delete previous sprites
        while (!items()->isEmpty()) {
            delete items()->first();
        }

        //Clear our spritemap as well
        spriteMap.clear();

        //Recreate our background
        QPalette palette;
        palette.setBrush(backgroundRole(), theBackground.getBackground());
        setPalette(palette);
        setAutoFillBackground(true);
    }
}

void BoardWidget::putTileInBoard(POSITION& Pos, bool doRepaint)
{
    short E = Pos.e;
    short Y = Pos.y;
    short X = Pos.x;

    // we ensure that any tile we put on has highlighting off
    Game->putTile(E, Y, X, Pos.f);
    Game->setHighlightData(E, Y, X, 0);

    QPixmap s;
    QPixmap us;
    QPixmap f;
    s = theTiles.selectedTile(m_angle);
    us = theTiles.unselectedTile(m_angle);
    f = theTiles.tileface(Game->BoardData(E, Y, X) - TILE_OFFSET);
    TileSprite *thissprite = new TileSprite(this, us, s, f, m_angle, false);
    thissprite->show();
    spriteMap.insert(TileCoord(X, Y, E), thissprite);

    updateSpriteMap();
}

void BoardWidget::removeTile(POSITION& Pos, bool doRepaint)
{
    short E = Pos.e;
    short Y = Pos.y;
    short X = Pos.x;

    Game->TileNum--;                    // Eine Figur weniger
    Game->setMoveListData(Game->TileNum,Pos); // Position ins Protokoll eintragen

    delete spriteMap.take(TileCoord(X,Y,E));

    // remove tile from game board
    Game->putTile(E, Y, X, 0);
}

void BoardWidget::mousePressEvent(QMouseEvent *event)
{
    if (gamePaused) {
        return;
    }

    if (event->button() == Qt::LeftButton) {
        if (TimerState == Demo) {
            stopDemoMode();
        } else if (showMatch) {
            stopMatchAnimation();
        }

        if (showHelp) { // stop hilighting tiles
            helpMoveStop();
        }

        if (MouseClickPos1.e == Game->m_depth) {      // first tile
            transformPointToPosition(event->pos(), MouseClickPos1);

            if (MouseClickPos1.e != Game->m_depth && showMatch) {
                matchCount = Game->findAllMatchingTiles(MouseClickPos1);
                TimerState = Match;
                iTimerStep = 1;
                matchAnimationTimeout();
                cheatsUsed++;
            }
        } else {                             // second tile
            transformPointToPosition(event->pos(), MouseClickPos2);
            if (MouseClickPos2.e == Game->m_depth) {
                cancelUserSelectedTiles();
            } else {
                if (Game->isMatchingTile(MouseClickPos1, MouseClickPos2)) {
                    // update the removed tiles (we do this before the remove below
                    // so that we only require 1 screen paint for both actions)
                    Game->setRemovedTilePair(MouseClickPos1, MouseClickPos2);

                    // now we remove the tiles from the board*t,
                    removeTile(MouseClickPos1, false);
                    removeTile(MouseClickPos2);

                    // removing a tile means redo is impossible without
                    // a further undo.
                    Game->allow_redo = false;
                    demoModeChanged(false);
                    drawTileNumber();

                    // if no tiles are left, the player has `won`, so celebrate
                    if (Game->TileNum == 0) {
                        gameOver(Game->MaxTileNum,cheatsUsed);
                    } else {
                    // else if no more moves are possible, display the sour grapes dialog
                        validMovesAvailable();
                    }
                } else {
                    // redraw tiles in normal state
                    hilightTile(MouseClickPos1, false, false);
                    hilightTile(MouseClickPos2, false);
                }

                MouseClickPos1.e = Game->m_depth;     // mark tile position as invalid
                MouseClickPos2.e = Game->m_depth;
            }
        }
    }
}

KGameCanvasItem* BoardWidget::itemAt(const QPoint& point) const
{
    // Get the shadows...
    // theTiles.width() == The whole tile width including offset and shadow.
    // theTiles.qWidth() == Half of the width of the tile face (without the offset and the shadow).
    // theTiles.levelOffsetX() == The level of the tile (the perspective height of the tile)
    int shadowWidth = theTiles.width() - (theTiles.qWidth() * 2 + theTiles.levelOffsetX());
    int shadowHeight = theTiles.height() - (theTiles.qHeight() * 2 + theTiles.levelOffsetY());

    for (int i = m_items.size() - 1; i >= 0; i--) {
        KGameCanvasItem *canvasItem = m_items[i];

        // Cause of the shadow, that is not really a part of a tile. Correct the rect positions
        // related to the angle. Actually we just correct the rect of the canvas item cause of the
        // shadow, that is not part of the clickable tile.
        QRect oldRect = canvasItem->rect();
        QRect rectCorrection = oldRect;

        // Correct the positions related to the angle we had set.
        switch (m_angle) {
        case NW:
            rectCorrection.setRect(oldRect.x() + shadowWidth, oldRect.y(),
                oldRect.width() - shadowWidth, oldRect.height() - shadowHeight);
            break;
        case NE:
            rectCorrection.setRect(oldRect.x(), oldRect.y(), oldRect.width() - shadowWidth,
                oldRect.height() - shadowHeight);
            break;
        case SW:
            rectCorrection.setRect(oldRect.x() + shadowWidth, oldRect.y() + shadowHeight,
                oldRect.width() - shadowWidth, oldRect.height() - shadowHeight);
            break;
        case SE:
            rectCorrection.setRect(oldRect.x(), oldRect.y() + shadowHeight,
                oldRect.width() - shadowWidth, oldRect.height() - shadowHeight);
            break;
        }

        // if the canvas is visible and we click inside the corrected rect of the canvas item, we
        // can return the actual canvas item.
        if (canvasItem->visible() && rectCorrection.contains(point)) {
            return canvasItem;
        }
    }

    return NULL;
}

void BoardWidget::transformPointToPosition(const QPoint &point, POSITION &MouseClickPos)
{
    int E;
    int X;
    int Y;

    TileSprite *clickedItem = NULL;
    clickedItem = (TileSprite *) itemAt(point);

    if (!clickedItem) {
        //no item under mouse
        qDebug() << "no tile registered";

        return;
    }

    TileCoord coord = spriteMap.key(clickedItem);
    E = coord.z();
    X = coord.x();
    Y = coord.y();

    //sanity checking
    if (X < 0 || X >= Game->m_width || Y < 0 || Y >= Game->m_height) {
        return;
    }

    // if gameboard is empty, skip
    //sanity checking
    if (!Game->BoardData(E, Y, X)) {
        qDebug() << "Tile not in BoardData. Fading out?";

        return;
    }

    // tile must be 'free' (nothing left, right or above it)
    //Optimization, skip "over" test for the top layer
    if (E < Game->m_depth - 1) {
        if (Game->BoardData(E + 1, Y, X)
            || (Y < Game->m_height - 1 && Game->BoardData(E + 1, Y + 1, X))
            || (X < Game->m_width - 1 && Game->BoardData(E + 1, Y, X + 1))
            || (X < Game->m_width - 1 && Y < Game->m_height - 1
            && Game->BoardData(E + 1, Y + 1, X + 1))) {
            return;
        }
    }

    // No left test on left edge
    if (( X > 0) && (Game->BoardData(E, Y, X - 1) || Game->BoardData(E, Y + 1, X - 1))) {
        if ((X < Game->m_width - 2)
            && (Game->BoardData(E, Y, X + 2) || Game->BoardData(E, Y + 1, X + 2))) {
                return;
        }
    }

    // if we reach here, position is legal
    MouseClickPos.e = E;
    MouseClickPos.y = Y;
    MouseClickPos.x = X;
    MouseClickPos.f = Game->BoardData(E, Y, X);

    // give visible feedback
    hilightTile( MouseClickPos );
}

bool BoardWidget::loadBoard( )
{
    delete Game;
    Game = new GameData(theBoardLayout.board());

    return true;
}

void BoardWidget::setStatusText(const QString &pszText)
{
    emit statusTextChanged(pszText, gameGenerationNum);
}

bool BoardWidget::loadBackground(const QString &pszFileName, bool bShowError)
{
    if (theBackground.load(pszFileName, requiredWidth(), requiredHeight())) {
        if (theBackground.loadGraphics()) {
            return true;
        }
    }

    //Try default
    if (theBackground.loadDefault()) {
        if (theBackground.loadGraphics()) {
        }
    }

    return false;
}

void BoardWidget::drawTileNumber()
{
    emit tileNumberChanged(Game->MaxTileNum, Game->TileNum, Game->moveCount());
}

void BoardWidget::cancelUserSelectedTiles()
{
    if (MouseClickPos1.e != Game->m_depth) {
        hilightTile(MouseClickPos1, false); // redraw tile
        MouseClickPos1.e = Game->m_depth;    // mark tile invalid
    }
}

bool BoardWidget::loadTileset(const QString &path)
{
    if (theTiles.loadTileset(path)) {
        if (theTiles.loadGraphics()) {
            resizeTileset(size());

            return true;
        }
    }

    //Tileset or graphics could not be loaded, try default
    if (theTiles.loadDefault()) {
        if (theTiles.loadGraphics()) {
            resizeTileset(size());
        }
    }

    return false;
}

bool BoardWidget::loadBoardLayout(const QString &file)
{
    if (theBoardLayout.load(file)) {
        return true;
    } else {
        if (theBoardLayout.loadDefault()) {
            return false;
        } else {
            return false;
        }
    }
}

int BoardWidget::requiredHorizontalCells()
{
    int res = (Game->m_width / 2);
    /*if (Prefs::showRemoved())
        res = res + 3; //space for removed tiles*/

    return res;
}

int BoardWidget::requiredVerticalCells()
{
    int res = (Game->m_height / 2);

    return res;
}

int BoardWidget::requiredWidth()
{
    //int res = ((BoardLayout::width+12)* theTiles.qWidth());
    int res = width();

    return res;
}

int BoardWidget::requiredHeight()
{
    //int res = ((BoardLayout::height+3)* theTiles.qHeight());
    int res = height();

    return res;
}

void BoardWidget::angleSwitchCCW()
{
    switch (m_angle) {
    case NW :
        m_angle = NE;

        break;

    case NE :
        m_angle = SE;

        break;

    case SE :
        m_angle = SW;

        break;

    case SW :
        m_angle = NW;

        break;
    }

    QHashIterator<TileCoord, TileSprite*> i(spriteMap);
    while (i.hasNext()) {
        i.next();
        QPixmap u = theTiles.unselectedTile(m_angle);
        QPixmap s = theTiles.selectedTile(m_angle);
        i.value()->setAngle(m_angle, u, s);
    }

    //re-position and re-layer
    updateSpriteMap();

    //save angle
    saveSettings();
}

void BoardWidget::angleSwitchCW()
{
    switch (m_angle) {
    case NW :
        m_angle = SW;

        break;

    case NE :
        m_angle = NW;

        break;

    case SE :
        m_angle = NE;

        break;

    case SW :
        m_angle = SE;

        break;
    }

    QHashIterator<TileCoord, TileSprite *> i(spriteMap);
    while (i.hasNext()) {
        i.next();
        QPixmap u = theTiles.unselectedTile(m_angle);
        QPixmap s = theTiles.selectedTile(m_angle);
        i.value()->setAngle(m_angle, u, s);
    }

    //re-position and re-layer
    updateSpriteMap();

    //save settings
    saveSettings();
}

void BoardWidget::shuffle()
{
    cancelUserSelectedTiles();
    Game->shuffle();

    // force a full redraw
    populateSpriteMap();

    // I consider this s very bad cheat so, I punish the user
    // 300 points per use
    cheatsUsed += 15;
    drawTileNumber();

    // Test if any moves are available
    validMovesAvailable();
}

bool BoardWidget::validMovesAvailable()
{
    if (!Game->findMove(TimerPos1, TimerPos2)) {
        KMessageBox::information(this, i18n("Game over: You have no moves left."));

        return false;
    }

    return true;
}

QString  BoardWidget::getLayoutName()
{
    QString key("Name");

    return theBoardLayout.authorProperty(key);
}

void BoardWidget::wheelEvent(QWheelEvent *event)
{
    if (event->orientation() == Qt::Vertical) {
        if (event->delta() > 0) {
            angleSwitchCCW();
        } else {
            angleSwitchCW();
        }
    }

    event->accept();
}


#include "boardwidget.moc"