~neon/katomic/master

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
/*

   Copyright (C) 1998   Andreas Wüst (AndreasWuest@gmx.de)
   Copyright (C) 2006-2009   Dmitry Suzdalev (dimsuz@gmail.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 "gamewidget.h"
#include "highscores.h"
#include "playfield.h"
#include "prefs.h"

#include <QGraphicsView>
#include <QResizeEvent>
#include <QApplication> // for qApp->quit()
#include <QVBoxLayout>
#include <QTimer> // Next Level after N seconds
#include <KMessageBox>
#include <KLocalizedString>
#include <KConfig>
#include <QFileDialog>
#include "katomic_debug.h"

GameWidget::GameWidget ( const QString& levelSet, QWidget *parent )
    : QWidget( parent ), m_allowAnyLevelSwitch( false ), m_moves(0), m_level(0)
{
    m_highscore = new KAtomicHighscores();
    m_levelHighscore = 0;

    QVBoxLayout *top = new QVBoxLayout(this);
    top->setContentsMargins(0, 0, 0, 0);

    // playfield
    m_playField = new PlayField(this);

    m_view = new QGraphicsView(m_playField, this);
    int defaultFieldSize = FIELD_SIZE*MIN_ELEM_SIZE;
    // reserve some room for molecule preview
    m_view->setMinimumSize( defaultFieldSize+defaultFieldSize/4, defaultFieldSize );
    m_view->setVerticalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    m_view->setHorizontalScrollBarPolicy( Qt::ScrollBarAlwaysOff );
    m_view->setFrameStyle( QFrame::NoFrame );
    m_view->setCacheMode( QGraphicsView::CacheBackground );

    // TODO uncomment DontSavePainterState optimization back after this bug in Qt 4.6 preview will be
    // fixed (darktears promised it will get fixed in 4.6.0 release). Bug is about wrong coordinates
    // for QPainter passed to QGS::drawForeground() function
    m_view->setOptimizationFlags( 
            //QGraphicsView::DontSavePainterState |
            QGraphicsView::DontAdjustForAntialiasing );

    top->addWidget(m_view, 1);

    connect(m_playField, &PlayField::gameOver, this, &GameWidget::gameOver);
    connect(m_playField, &PlayField::updateMoves, this, &GameWidget::updateMoves);

    // Next level after some seconds after ending the game. See gameOver, nextLevel and prevLevel
    m_timer = new QTimer(this);
    m_timer->setSingleShot(true);
    connect(m_timer, &QTimer::timeout, this, &GameWidget::nextLevel);

    setLevelSet(levelSet);
}

GameWidget::~GameWidget()
{
    delete m_highscore;
}


bool GameWidget::setLevelSet(const QString& levelSet)
{
    if (m_levelSet.name() == levelSet)
    {
        //qCDebug(KATOMIC_LOG) << "level set named" << levelSet << "is already loaded";
        return true;
    }

    bool res = m_levelSet.load(levelSet);
    if (!res)
    {
        KMessageBox::error(this, i18n("Failed to load level set \"%1\". Check if it is installed on your computer.", levelSet));
        //qCDebug(KATOMIC_LOG) << "failed to load levelset" << levelSet;
        return false;
    }

    int lastPlayed = lastPlayedLevel();
    int maxLevel = maxAccessibleLevel();

    int startingLevel = qMin(lastPlayed, maxLevel);
    switchToLevel(startingLevel);

    return true;
}

const LevelSet& GameWidget::levelSet() const
{
    return m_levelSet;
}

QString GameWidget::currentMolecule() const
{
    return m_playField->moleculeName();
}

void GameWidget::moveUp()
{
    if(!m_playField->isLevelFinished())
        m_playField->moveSelectedAtom( PlayField::Up );
}

void GameWidget::moveDown()
{
    if(!m_playField->isLevelFinished())
        m_playField->moveSelectedAtom( PlayField::Down );
}

void GameWidget::moveLeft()
{
    if(!m_playField->isLevelFinished())
        m_playField->moveSelectedAtom( PlayField::Left );
}

void GameWidget::moveRight()
{
    if(!m_playField->isLevelFinished())
        m_playField->moveSelectedAtom( PlayField::Right );
}

void GameWidget::gameOver(int moves) {
    // writing this info only in normal mode
    if ( !m_allowAnyLevelSwitch &&
            maxAccessibleLevel() < m_level+1 )
    {
        saveMaxAccessibleLevel( m_level+1 );
    }

    QString message = i18n( "Level %1 finished. ", m_level );

    if( m_highscore->addScore( moves , m_levelSet.name(), m_level ) ) // new highscore!
    {
        message += i18n("Congratulations! You have a new highscore!" );
    }

    m_playField->showMessage( message );
    emit statsChanged(m_level, moves, m_highscore->levelHighscore(m_levelSet.name(), m_level));
    if (!m_allowAnyLevelSwitch)
    {
        // reuse this signal to allow switching levels over toolbar
        emit levelChanged(m_level);
        // after 4 seconds, nextLevel
        m_timer->start(4000);
    }
}

void GameWidget::updateMoves(int moves)
{
    m_moves = moves;
    emit statsChanged(m_level, moves, m_levelHighscore);
}

void GameWidget::switchToLevel (int l)
{
    const LevelData* levelData = m_levelSet.levelData(l);
    if (levelData)
    {
        m_level=l;

        m_playField->setLevelData(levelData);

        m_levelHighscore = m_highscore->levelHighscore( m_levelSet.name(), m_level );

        emit statsChanged(m_level, 0, m_levelHighscore);
        emit levelChanged(m_level);

        saveLastPlayedLevel();
    }
    else {
        //qCDebug(KATOMIC_LOG) << "failed to load level" << l;
    }
}

void GameWidget::restartLevel()
{
    switchToLevel(m_level);
}

void GameWidget::saveGame()
{
    QString fileName = QFileDialog::getSaveFileName( this, QString(), QString(), QStringLiteral("*.katomic") );
    if(fileName.isEmpty())
        return;
    KConfig config(fileName, KConfig::SimpleConfig);
    KConfigGroup gr = config.group("Savegame");
    gr.writeEntry( "Level", m_level );
    gr.writeEntry( "LevelSet", m_levelSet.name() );
    m_playField->saveGame( gr );
}

void GameWidget::loadGame()
{
    QString fileName = QFileDialog::getOpenFileName( this, QString(), QString(), QStringLiteral("*.katomic") );
    if(fileName.isEmpty())
        return;
    KConfig config(fileName, KConfig::SimpleConfig);
    KConfigGroup gr = config.group("Savegame");
    QString levelSet = gr.readEntry("LevelSet");
    if (levelSet.isEmpty())
    {
        //qCDebug(KATOMIC_LOG) << "note: savegame file doesn't contain info about levelset, assuming default one";
        levelSet = QStringLiteral(DEFAULT_LEVELSET_NAME);
    }

    bool res = setLevelSet(levelSet);
    if (res)
    {
        int l = gr.readEntry( "Level", 1 );
        switchToLevel(l);
        m_playField->loadGame( gr );
    }
}

void GameWidget::showHighscores ()
{
    // TODO: Implement me! Please... 8-)
}

int GameWidget::currentHighScore() const
{
    return m_levelHighscore;
}

void GameWidget::prevLevel()
{
    // if user hits toolbar buttons, stop timer
    if (m_timer->isActive())
        m_timer->stop();

    if (isPrevLevelAvailable())
    {
        switchToLevel(m_level-1);
    }
}

void GameWidget::nextLevel()
{
    // if user hits toolbar buttons, stop timer
    if (m_timer->isActive())
        m_timer->stop();

    if (isNextLevelAvailable())
    {
        switchToLevel(m_level+1);
    }
}

void GameWidget::resizeEvent( QResizeEvent* ev)
{
    m_playField->resize( ev->size().width(), ev->size().height() );
}

void GameWidget::saveLastPlayedLevel()
{
    KSharedConfigPtr cfg = KSharedConfig::openConfig();
    KConfigGroup grp(cfg, m_levelSet.name());
    grp.writeEntry("LastPlayedLevel", m_level);

    Preferences::setLastPlayedLevelSet(m_levelSet.name());
}

void GameWidget::saveMaxAccessibleLevel(int level)
{
    KSharedConfigPtr cfg = KSharedConfig::openConfig();
    KConfigGroup grp(cfg, m_levelSet.name());
    grp.writeEntry("MaxAccessibleLevel", level);
}

int GameWidget::lastPlayedLevel() const
{
    KSharedConfigPtr cfg = KSharedConfig::openConfig();
    KConfigGroup grp(cfg, m_levelSet.name());
    int lastPlayed = grp.readEntry("LastPlayedLevel", 1);
    lastPlayed = qMax(1, lastPlayed); // can't be less than 1
    //qCDebug(KATOMIC_LOG) << "last played level:" << lastPlayed;
    return lastPlayed;
}

int GameWidget::maxAccessibleLevel() const
{
    KSharedConfigPtr cfg = KSharedConfig::openConfig();
    KConfigGroup grp(cfg, m_levelSet.name());
    int maxAccessible = grp.readEntry("MaxAccessibleLevel", 1);
    //qCDebug(KATOMIC_LOG) << "max accessible level:" << maxAccessible;
    return maxAccessible;
}

bool GameWidget::isNextLevelAvailable() const
{
    bool avail = m_allowAnyLevelSwitch ? true :
        (m_level != maxAccessibleLevel() && m_level <= m_levelSet.levelCount());
    return avail;
}

bool GameWidget::isPrevLevelAvailable() const
{
    return m_level > 1;
}