File: kmahjongg.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 (600 lines) | stat: -rw-r--r-- 16,478 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
/* kmahjongg, the classic mahjongg game for KDE project
 *
 * Copyright (C) 1997 Mathias Mueller   <in5y158@public.uni-hamburg.de>
 * Copyright (C) 2006-2007 Mauricio Piacentini   <mauricio@tabuleiro.com>
 *
 * 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 "kmahjongg.h"

#include "prefs.h"
#include "kmahjongglayoutselector.h"
#include "ui_settings.h"
#include "Editor.h"

#include <kmahjonggconfigdialog.h>

#include <limits.h>

#include <QPixmapCache>
#include <QLabel>
#include <QDesktopWidget>

#include <KAboutData>
#include <KAction>
#include <KConfigDialog>
#include <KInputDialog>
#include <KMenuBar>
#include <KMessageBox>
#include <KStandardGameAction>
#include <KStandardAction>
#include <KIcon>
#include <KScoreDialog>
#include <KGameClock>

#include <kio/netaccess.h>
#include <klocale.h>
#include <ktoggleaction.h>
#include <kactioncollection.h>


#define ID_STATUS_TILENUMBER 1
#define ID_STATUS_MESSAGE    2
#define ID_STATUS_GAME       3


static const char *gameMagic = "kmahjongg-gamedata";
static int gameDataVersion = 1;

int is_paused = 0;

/**
 * This class implements
 *
 * longer description
 *
 * @author Mauricio Piacentini  <mauricio@tabuleiro.com> */
class Settings : public QWidget, public Ui::Settings
{
public:
    /**
     * Constructor */
    Settings(QWidget *parent)
        : QWidget(parent)
    {
        setupUi(this);
    }
};

KMahjongg::KMahjongg(QWidget *parent)
    : KXmlGuiWindow(parent)
{
    //Use up to 3MB for global application pixmap cache
    QPixmapCache::setCacheLimit(3 * 1024);

    // minimum area required to display the field
    setMinimumSize(320, 320);

    // init board widget
    bw = new BoardWidget(this);
    setCentralWidget(bw);

    // Initialize boardEditor
    boardEditor = new Editor();
    boardEditor->setModal(false);

    // Set the tileset setted in the the settings.
    boardEditor->setTilesetFromSettings();

    setupStatusBar();
    setupKAction();

    gameTimer = new KGameClock(this);

    connect(gameTimer, SIGNAL(timeChanged(QString)), this, SLOT(displayTime(QString)));

    mFinished = false;
    bDemoModeActive = false;

    connect(bw, SIGNAL(statusTextChanged(QString,long)), SLOT(showStatusText(QString,long)));
    connect(bw, SIGNAL(tileNumberChanged(int,int,int)), SLOT(showTileNumber(int,int,int)));
    connect(bw, SIGNAL(demoModeChanged(bool)), SLOT(demoModeChanged(bool)));
    connect(bw, SIGNAL(gameOver(unsigned short,unsigned short)), this,
        SLOT(gameOver(unsigned short,unsigned short)));
    connect(bw, SIGNAL(gameCalculated()), this, SLOT(timerReset()));

    startNewGame();
}

KMahjongg::~KMahjongg()
{
    delete bw;
    delete boardEditor;
}

void KMahjongg::setupKAction()
{
    KStandardGameAction::gameNew(this, SLOT(newGame()), actionCollection());
    KStandardGameAction::load(this, SLOT(loadGame()), actionCollection());
    KStandardGameAction::save(this, SLOT(saveGame()), actionCollection());
    KStandardGameAction::quit(this, SLOT(close()), actionCollection());
    KStandardGameAction::restart(this, SLOT(restartGame()), actionCollection());

    QAction *newNumGame = actionCollection()->addAction(QLatin1String("game_new_numeric"));
    newNumGame->setText(i18n("New Numbered Game..."));
    connect(newNumGame, SIGNAL(triggered(bool)), SLOT(startNewNumeric()));

    QAction *action = KStandardGameAction::hint(bw, SLOT(helpMove()), this);
    actionCollection()->addAction(action->objectName(), action);

    QAction *shuffle = actionCollection()->addAction(QLatin1String("move_shuffle"));
    shuffle->setText(i18n("Shu&ffle"));
    shuffle->setIcon(KIcon(QLatin1String("view-refresh")));
    connect(shuffle, SIGNAL(triggered(bool)), bw, SLOT(shuffle()));

    KAction *angleccw = actionCollection()->addAction(QLatin1String("view_angleccw"));
    angleccw->setText(i18n("Rotate View Counterclockwise"));
    angleccw->setIcon(KIcon(QLatin1String("object-rotate-left")));
    angleccw->setShortcuts(KShortcut("f"));
    connect(angleccw, SIGNAL(triggered(bool)), bw, SLOT(angleSwitchCCW()));

    KAction *anglecw = actionCollection()->addAction(QLatin1String("view_anglecw"));
    anglecw->setText(i18n("Rotate View Clockwise"));
    anglecw->setIcon(KIcon(QLatin1String("object-rotate-right")));
    anglecw->setShortcuts(KShortcut("g"));
    connect(anglecw, SIGNAL(triggered(bool)), bw, SLOT(angleSwitchCW()));

    demoAction = KStandardGameAction::demo(this, SLOT(demoMode()), actionCollection());

    KStandardGameAction::highscores(this, SLOT(showHighscores()), actionCollection());
    pauseAction = KStandardGameAction::pause(this, SLOT(pause()), actionCollection());

    // move
    undoAction = KStandardGameAction::undo(this, SLOT(undo()), actionCollection());
    redoAction = KStandardGameAction::redo(this, SLOT(redo()), actionCollection());

    // edit
    QAction *boardEdit = actionCollection()->addAction(QLatin1String("game_board_editor"));
    boardEdit->setText(i18n("&Board Editor"));
    connect(boardEdit, SIGNAL(triggered(bool)), SLOT(slotBoardEditor()));

    // settings
    KStandardAction::preferences(this, SLOT(showSettings()), actionCollection());

    setupGUI(qApp->desktop()->availableGeometry().size() * 0.7);
}

void KMahjongg::setupStatusBar()
{
    gameTimerLabel = new QLabel(i18n("Time: 0:00:00"), statusBar());
    statusBar()->addWidget(gameTimerLabel);

    QFrame *timerDivider = new QFrame(statusBar());
    timerDivider->setFrameStyle(QFrame::VLine);
    statusBar()->addWidget(timerDivider);

    tilesLeftLabel = new QLabel(i18n("Removed: 0000/0000"), statusBar());
    statusBar()->addWidget(tilesLeftLabel, 1);

    QFrame *tileDivider = new QFrame(statusBar());
    tileDivider->setFrameStyle(QFrame::VLine);
    statusBar()->addWidget(tileDivider);

    gameNumLabel = new QLabel(i18n("Game: 000000000000000000000"), statusBar());
    statusBar()->addWidget(gameNumLabel);

    QFrame *gameNumDivider = new QFrame(statusBar());
    gameNumDivider->setFrameStyle(QFrame::VLine);
    statusBar()->addWidget(gameNumDivider);

    statusLabel = new QLabel("Kmahjongg", statusBar());
    statusBar()->addWidget(statusLabel);
}

void KMahjongg::displayTime(const QString& timestring)
{
    gameTimerLabel->setText(i18n("Time: ") + timestring);
}

void KMahjongg::setDisplayedWidth()
{
    bw->setDisplayedWidth();
    bw->drawBoard();
}

void KMahjongg::startNewNumeric()
{
    bool ok;
    int s = KInputDialog::getInteger(i18n("New Game"), i18n("Enter game number:"), 0, 0, INT_MAX, 1,
        &ok, this);

    if (ok) {
        startNewGame(s);
    }
}

void KMahjongg::undo()
{
    bw->Game->allow_redo += bw->undoMove();
    demoModeChanged(false);
}

void KMahjongg::redo()
{
    if (bw->Game->allow_redo > 0) {
        bw->Game->allow_redo--;
        bw->redoMove();
        demoModeChanged(false);
    }
}

void KMahjongg::showSettings()
{
    if (KConfigDialog::showDialog("settings")) {
        return;
    }

    //Use the classes exposed by LibKmahjongg for our configuration dialog
    KMahjonggConfigDialog *dialog = new KMahjonggConfigDialog(this, "settings", Prefs::self());

    //The Settings class is ours
    dialog->addPage(new Settings(0), i18n("General"), "games-config-options");
    dialog->addPage(new KMahjonggLayoutSelector(0, Prefs::self()), i18n("Board Layout"), "games-con"
        "fig-board");
    dialog->addTilesetPage();
    dialog->addBackgroundPage();
    dialog->setHelp(QString(),"kmahjongg");

    connect(dialog, SIGNAL(settingsChanged(QString)), bw, SLOT(loadSettings()));
    connect(dialog, SIGNAL(settingsChanged(QString)), boardEditor, SLOT(setTilesetFromSettings()));
    connect(dialog, SIGNAL(settingsChanged(QString)), this, SLOT(setDisplayedWidth()));

    dialog->show();
}

void KMahjongg::demoMode()
{
    if (bDemoModeActive) {
        bw->stopDemoMode();
    } else {
        // we assume demo mode removes tiles so we can
        // disable redo here.
        bw->Game->allow_redo = false;
        bw->startDemoMode();
    }

}

void KMahjongg::pause()
{
    if (is_paused) {
        gameTimer->resume();
    } else {
        gameTimer->pause();
    }

    is_paused = !is_paused;
    demoModeChanged(false);
    bw->pause();
}

void KMahjongg::showHighscores()
{
    KScoreDialog ksdialog(KScoreDialog::Name | KScoreDialog::Time, this);
    ksdialog.setConfigGroup(bw->getLayoutName());
    ksdialog.exec();
}

void KMahjongg::slotBoardEditor()
{
    boardEditor->setVisible(true);

    // Set the default size.
    boardEditor->setGeometry(Prefs::editorGeometry());
}

void KMahjongg::newGame()
{
    startNewGame();
}

void KMahjongg::startNewGame(int item)
{
    if (!bDemoModeActive) {
        bw->calculateNewGame(item);

        // initialise button states
        bw->Game->allow_redo = bw->Game->allow_undo = 0;

        timerReset();

        // update the initial enabled/disabled state for
        // the menu and the tool bar.
        mFinished = false;
        demoModeChanged(false);
    }
}

void KMahjongg::timerReset()
{
    // initialise the scoring system
    gameElapsedTime = 0;

    // start the game timer
    gameTimer->restart();
}

void KMahjongg::changeEvent(QEvent *event)
{
    if (event->type() == QEvent::WindowStateChange) {
        QWindowStateChangeEvent *stateEvent = (QWindowStateChangeEvent *) event;

        if ((isMinimized() && stateEvent->oldState() != Qt::WindowMinimized)
            || (!isMinimized() && stateEvent->oldState() == Qt::WindowMinimized)) {
            pause();
        }
    }
}

void KMahjongg::gameOver(unsigned short numRemoved,	unsigned short cheats)
{
    int time;
    int score;

    gameTimer->pause();
    long gameNum = bw->getGameNum();

    KMessageBox::information(this, i18n("You have won!"));

    mFinished = true;
    demoModeChanged(false);

    int elapsed = gameTimer->seconds();

    time = score = 0;

    // get the time in milli secs
    // subtract from 20 minutes to get bonus. if longer than 20 then ignore
    time = (60 * 20) - gameTimer->seconds();
    if (time < 0) {
        time =0;
    }
    // conv back to  secs (max bonus = 60*20 = 1200

    // points per removed tile bonus (for deragon max = 144*10 = 1440
    score += (numRemoved * 20);
    // time bonus one point per second under one hour
    score += time;
    // points per cheat penalty (max penalty = 1440 for dragon)
    score -= (cheats * 20);
    if (score < 0) {
        score = 0;
    }

    //TODO: add gameNum as a Custom KScoreDialog field?
//     theHighScores->checkHighScore(score, elapsed, gameNum, bw->getBoardName());
    KScoreDialog ksdialog(KScoreDialog::Name | KScoreDialog::Time, this);
    ksdialog.setConfigGroup(bw->getLayoutName());
    KScoreDialog::FieldInfo scoreInfo;
    scoreInfo[KScoreDialog::Score].setNum(score);
    scoreInfo[KScoreDialog::Time] = gameTimer->timeString();
    if(ksdialog.addScore(scoreInfo, KScoreDialog::AskName)) {
        ksdialog.exec();
    }

    bw->animateMoveList();

    timerReset();
}


void KMahjongg::showStatusText(const QString &msg, long board)
{
    statusLabel->setText(msg);
    QString str = i18n("Game number: %1", board);
    gameNumLabel->setText(str);
}

void KMahjongg::showTileNumber(int iMaximum, int iCurrent, int iLeft)
{
    // Hmm... seems iCurrent is the number of remaining tiles, not removed ...
    //QString szBuffer = i18n("Removed: %1/%2").arg(iCurrent).arg(iMaximum);
    QString szBuffer = i18n("Removed: %1/%2  Combinations left: %3", iMaximum-iCurrent, iMaximum,
        iLeft);
    tilesLeftLabel->setText(szBuffer);

    // Update here since undo allow is effected by demo mode
    // removal. However we only change the enabled state of the
    // items when not in demo mode
    bw->Game->allow_undo = iMaximum != iCurrent;

    // update undo menu item, if demomode is inactive
    if (!bDemoModeActive && !is_paused && !mFinished) {
        undoAction->setEnabled(bw->Game->allow_undo);
    }
}

void KMahjongg::demoModeChanged(bool bActive)
{
    bDemoModeActive = bActive;

    pauseAction->setChecked(is_paused);
    demoAction->setChecked(bActive || is_paused);

    if (is_paused) {
        stateChanged("paused");
    } else if (mFinished) {
        stateChanged("finished");
    } else if (bActive) {
        stateChanged("active");
    } else {
        stateChanged("inactive");
        undoAction->setEnabled(bw->Game->allow_undo);
        redoAction->setEnabled(bw->Game->allow_redo);
    }
}

void KMahjongg::restartGame()
{
    if (!bDemoModeActive) {
        bw->calculateNewGame(bw->getGameNum());

        // initialise button states
        bw->Game->allow_redo = bw->Game->allow_undo = 0;

        timerReset();

        // update the initial enabled/disabled state for
        // the menu and the tool bar.
        mFinished = false;
        demoModeChanged(false);

        if (is_paused) {
            pauseAction->setChecked(false);
            is_paused = false;
            bw->pause();
        }
    }
}

void KMahjongg::loadGame()
{
    QString fname;

    // Get the name of the file to load
    KUrl url = KFileDialog::getOpenUrl(KUrl(), "*.kmgame", this, i18n("Load Game" ));

    if (url.isEmpty()) {
        return;
    }

    KIO::NetAccess::download(url, fname, this);

    // open the file for reading
    QFile infile(fname);

    if (!infile.open(QIODevice::ReadOnly)) {
        KMessageBox::sorry(this, i18n("Could not read from file. Aborting."));
        return;
    }

    QDataStream in(&infile);

    // verify the magic
    QString magic;
    in >> magic;

    if (QString::compare(magic, gameMagic, Qt::CaseSensitive) != 0) {
        KMessageBox::sorry(this, i18n("File is not a KMahjongg game."));
        infile.close();

        return;
    }

    // Read the version
    qint32 version;
    in >> version;

    if (version == gameDataVersion) {
        in.setVersion(QDataStream::Qt_4_0);
    } else {
        KMessageBox::sorry(this, i18n("File format not recognized."));
        infile.close();

        return;
    }

    QString theTilesName;
    QString theBackgroundName;
    QString theBoardLayoutName;
    in >> theTilesName;
    bw->loadTileset(theTilesName);
    in >> theBackgroundName;
    bw->loadBackground(theBackgroundName, false);
    in >> theBoardLayoutName;

    //GameTime
    uint seconds;
    in >> seconds;
    gameTimer->setTime(seconds);

    delete bw->Game;
    bw->loadBoardLayout(theBoardLayoutName);
    bw->Game = new GameData(bw->theBoardLayout.board());
    bw->Game->loadFromStream(in);

    infile.close();

    KIO::NetAccess::removeTempFile(fname);

    // refresh the board
    bw->gameLoaded();

    mFinished = false;
    demoModeChanged(false);
}

void KMahjongg::saveGame()
{
    //Pause timer
    gameTimer->pause();

    // Get the name of the file to save
    KUrl url = KFileDialog::getSaveUrl(KUrl(), "*.kmgame", this, i18n("Save Game"));

    if (url.isEmpty()) {
        gameTimer->resume();

        return;
    }

    if (!url.isLocalFile()) {
        KMessageBox::sorry(this, i18n("Only saving to local files currently supported."));
        gameTimer->resume();

        return;
    }

    QFile outfile(url.path());

    if (!outfile.open(QIODevice::WriteOnly)) {
        KMessageBox::sorry(this, i18n("Could not write saved game."));
        gameTimer->resume();

        return;
    }

    QDataStream out(&outfile);

    // Write a header with a "magic number" and a version
    out << QString(gameMagic);
    out << (qint32) gameDataVersion;
    out.setVersion(QDataStream::Qt_4_0);

    out << bw->theTiles.path();
    out << bw->theBackground.path();
    out << bw->theBoardLayout.path();

    //GameTime
    out << gameTimer->seconds();
    // Write the Game data
    bw->Game->saveToStream(out);

    outfile.close();
    gameTimer->resume();
}


#include "kmahjongg.moc"