summaryrefslogtreecommitdiffstats
path: root/fifteenapplet/fifteenapplet.cpp
blob: 8393f9e8e81d2e35bda295e6c2d676495a12322a (plain)
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
/*****************************************************************

Copyright (c) 2001 Matthias Elter <elter@kde.org>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

******************************************************************/

#include <stdlib.h>
#include <time.h>

#include <tqlayout.h>
#include <tqpainter.h>
#include <tqpopupmenu.h>

#include <klocale.h>
#include <kglobal.h>
#include <kmessagebox.h>
#include <kaboutapplication.h>

#include "fifteenapplet.h"
#include "fifteenapplet.moc"

extern "C"
{
    KDE_EXPORT KPanelApplet* init(TQWidget *tqparent, const TQString& configFile)
    {
        KGlobal::locale()->insertCatalogue("kfifteenapplet");
        return new FifteenApplet(configFile, KPanelApplet::Normal,
                                 KPanelApplet::About, tqparent, "kfifteenapplet");
    }
}

FifteenApplet::FifteenApplet(const TQString& configFile, Type type, int actions,
                               TQWidget *tqparent, const char *name)
    : KPanelApplet(configFile, type, actions, tqparent, name), _aboutData(0)
{
    // setup table
    _table = new PiecesTable(this);
    setCustomMenu(_table->popup());

    // setup tqlayout
    TQHBoxLayout *_layout = new TQHBoxLayout(this);
    _layout->add(_table);

    srand(time(0));
}

int FifteenApplet::widthForHeight(int h) const
{
    return h; // we want to be quadratic
}

int FifteenApplet::heightForWidth(int w) const
{
    return w; // we want to be quadratic
}

void FifteenApplet::about()
{
    if(!_aboutData) {
	_aboutData = new KAboutData("kfifteenapplet", I18N_NOOP("KFifteenApplet"), "1.0",
                                    I18N_NOOP("Fifteen pieces applet.\n\n"
                                              "The goal is to put the sliding pieces into numerical order.\n"
                                              "Select \"Randomize Pieces\" from the right mouse button menu\n"
                                              "to start a game."),
                                    KAboutData::License_BSD, "(c) 2001, Matthias Elter");
	_aboutData->addAuthor("Matthias Elter", 0, "elter@kde.org");
    }

    KAboutApplication dialog(_aboutData);
    dialog.exec();
}

PiecesTable::PiecesTable(TQWidget* tqparent, const char* name )
    : QtTableView(tqparent, name), _activeRow(-1), _activeCol(-1), _randomized(false)
{
    _menu = new TQPopupMenu(this);
    _menu->insertItem(i18n("R&andomize Pieces"), this, TQT_SLOT(randomizeMap()));
    _menu->insertItem(i18n("&Reset Pieces"), this, TQT_SLOT(resetMap()));
    _menu->adjustSize();    // setup table view

    setFrameStyle(StyledPanel | Sunken);
    setBackgroundMode(NoBackground);
    setMouseTracking(true);

    setNumRows(4);
    setNumCols(4);

    // init arrays
    initMap();
    initColors();
}

void PiecesTable::paintCell(TQPainter *p, int row, int col)
{
    int w = cellWidth();
    int h = cellHeight();
    int x2 = w - 1;
    int y2 = h - 1;

    int number = _map[col + row * numCols()] + 1;

    bool active = (row == _activeRow && col == _activeCol);

    // draw cell background
    if(number == 16)
        p->setBrush(tqcolorGroup().background());
    else
        p->setBrush(_colors[number-1]);
    p->setPen(NoPen);
    p->drawRect(0, 0, w, h);

    // draw borders
    if (height() > 40) {
        p->setPen(tqcolorGroup().text());
        if(col < numCols()-1)
            p->drawLine(x2, 0, x2, y2); // right border line

        if(row < numRows()-1)
            p->drawLine(0, y2, x2, y2); // bottom boder line
    }

    // draw number
    if (number == 16) return;
    if(active)
        p->setPen(white);
    else
        p->setPen(black);
    p->drawText(0, 0, x2, y2, AlignHCenter | AlignVCenter, TQString::number(number));
}

void PiecesTable::resizeEvent(TQResizeEvent *e)
{
    QtTableView::resizeEvent(e);

    // set font
    TQFont f = font();
    if (height() > 50)
        f.setPixelSize(8);
    else if (height() > 40)
        f.setPixelSize(7);
    else if (height() > 24)
        f.setPixelSize(5);
    else
        f.setPixelSize(3);

    setFont(f);

    setCellWidth(contentsRect().width()/ numRows());
    setCellHeight(contentsRect().height() / numCols());
}

void PiecesTable::initColors()
{
    _colors.resize(numRows() * numCols());
    for (int r = 0; r < numRows(); r++)
        for (int c = 0; c < numCols(); c++)
            _colors[c + r *numCols()] = TQColor(255 - 70 * c,255 - 70 * r, 150);
}

void PiecesTable::initMap()
{
    _map.resize(16);
    for (unsigned int i = 0; i < 16; i++)
        _map[i] = i;

    _randomized = false;
}

void PiecesTable::randomizeMap()
{
    TQMemArray<int> positions;
    positions.fill(0, 16);

    for (unsigned int i = 0; i < 16; i++) {
        while(1) {
            int r = (int) (((double)rand() / RAND_MAX) * 16);
            if(positions[r] == 0) {
                _map[i] = r;
                positions[r] = 1;
                break;
            }
        }
    }
    tqrepaint();
    _randomized = true;
}

void PiecesTable::resetMap()
{
    initMap();
    tqrepaint();
}

void PiecesTable::checkwin()
{
    if(!_randomized) return;

    int i;
    for (i = 0; i < 16; i++)
        if(i != _map[i])
            break;

    if (i == 16)
        KMessageBox::information(this, i18n("Congratulations!\nYou win the game!"), i18n("Fifteen Pieces"));
}

void PiecesTable::mousePressEvent(TQMouseEvent* e)
{
    QtTableView::mousePressEvent(e);

    if (e->button() == Qt::RightButton) {
        // execute RMB popup and check result
        _menu->exec(mapToGlobal(e->pos()));
        e->accept();
        return;
    }
    else {
        // GAME LOGIC

        // find the free position
        int pos = _map.find(15);
        if(pos < 0) return;

        int frow = pos / numCols();
        int fcol = pos - frow * numCols();

        // find click position
        int row = findRow(e->y());
        int col = findCol(e->x());

        // sanity check
        if (row < 0 || row >= numRows()) return;
        if (col < 0 || col >= numCols()) return;

        // valid move?
        if(row != frow && col != fcol) return;

        // rows match -> shift pieces
        if(row == frow) {

            if (col < fcol) {
                for(int c = fcol; c > col; c--) {
                    _map[c + row * numCols()] = _map[ c-1 + row *numCols()];
                    updateCell(row, c, false);
                }
            }
            else if (col > fcol) {
                for(int c = fcol; c < col; c++) {
                    _map[c + row * numCols()] = _map[ c+1 + row *numCols()];
                    updateCell(row, c, false);
                }
            }
        }
        // cols match -> shift pieces
        else if (col == fcol) {

            if (row < frow) {
                for(int r = frow; r > row; r--) {
                    _map[col + r * numCols()] = _map[ col + (r-1) *numCols()];
                    updateCell(r, col, false);
                }
            }
            else if (row > frow) {
                for(int r = frow; r < row; r++) {
                    _map[col + r * numCols()] = _map[ col + (r+1) *numCols()];
                    updateCell(r, col, false);
                }
            }
        }
        // move free cell to click position
        _map[col + row * numCols()] = 15;
        updateCell(row, col, false);

        // check if the player wins with this move
        checkwin();
    }
}

void PiecesTable::mouseMoveEvent(TQMouseEvent* e)
{
    QtTableView::mouseMoveEvent(e);

    // highlight on mouse over
    int row = findRow(e->y());
    int col = findCol(e->x());

    int oldrow = _activeRow;
    int oldcol = _activeCol;

    if(row >= numRows()
       || col >= numCols()
       || row < 0
       || col < 0) {
        _activeRow = -1;
        _activeCol = -1;
    }
    else {
        _activeRow = row;
        _activeCol = col;
    }

    updateCell(oldrow, oldcol, false);
    updateCell(row, col, false);
}