summaryrefslogtreecommitdiffstats
path: root/kmines/field.cpp
blob: d7a9e1c4b45965e3bb54a465e1d7d9dcb5e32140 (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
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
/*
 * Copyright (c) 1996-2002 Nicolas HADACEK (hadacek@kde.org)
 *
 * 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 "field.h"
#include "field.moc"

#include <math.h>

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

#include <tdelocale.h>
#include <knotifyclient.h>

#include "settings.h"
#include "solver/solver.h"
#include "dialogs.h"


using namespace KGrid2D;

const Field::ActionData Field::ACTION_DATA[Nb_Actions] = {
  { "Reveal",         "reveal",          I18N_NOOP("Case revealed")       },
  { "AutoReveal",     "autoreveal",      I18N_NOOP("Case autorevealed")   },
  { "SetFlag",        "mark",            I18N_NOOP("Flag set")            },
  { "UnsetFlag",      "unmark",          I18N_NOOP("Flag unset")          },
  { "SetUncertain",   "set_uncertain",   I18N_NOOP("Question mark set")   },
  { "UnsetUncertain", "unset_uncertain", I18N_NOOP("Question mark unset") }
};

Field::Field(TQWidget *parent)
    : FieldFrame(parent), _state(Init), _solvingState(Regular), _level(Level::Easy)
{}

void Field::readSettings()
{
    if ( inside(_cursor) ) {
        TQPainter p(this);
        drawCase(p, _cursor);
    }
    if ( Settings::magicReveal() ) emit setCheating();
}

TQSize Field::sizeHint() const
{
  return TQSize(2*frameWidth() + _level.width()*Settings::caseSize(),
               2*frameWidth() + _level.height()*Settings::caseSize());
}

void Field::setLevel(const Level &level)
{
    _level = level;
    reset(false);
    adjustSize();
}

void Field::setReplayField(const TQString &field)
{
    setState(Replaying);
    initReplay(field);
}

void Field::setState(GameState state)
{
    Q_ASSERT( state!=GameOver );
    emit gameStateChanged(state);
    _state = state;
}

void Field::reset(bool init)
{
    BaseField::reset(_level.width(), _level.height(), _level.nbMines());
    if ( init || _state==Init ) setState(Init);
    else setState(Stopped);
    if (Settings::magicReveal()) emit setCheating();
    _currentAction = Settings::EnumMouseAction::None;
    _reveal = false;
    _cursor.first = _level.width()/2;
    _cursor.second = _level.height()/2;
    _advisedCoord = Coord(-1, -1);
    update();
}

void Field::paintEvent(TQPaintEvent *e)
{
	TQPainter painter(this);
	drawFrame(&painter);
	if ( _state==Paused ) return;

    Coord min = fromPoint(e->rect().topLeft());
    bound(min);
    Coord max = fromPoint(e->rect().bottomRight());
    bound(max);
	for (short i=min.first; i<=max.first; i++)
	    for (short j=min.second; j<=max.second; j++)
            drawCase(painter, Coord(i,j));
}

void Field::changeCase(const Coord &p, CaseState newState)
{
    BaseField::changeCase(p, newState);
    TQPainter painter(this);
	drawCase(painter, p);
	if ( isActive() ) emit updateStatus( hasMine(p) );
}

TQPoint Field::toPoint(const Coord &p) const
{
    TQPoint qp;
    qp.setX( p.first*Settings::caseSize() + frameWidth() );
    qp.setY( p.second*Settings::caseSize() + frameWidth() );
    return qp;
}

Coord Field::fromPoint(const TQPoint &qp) const
{
	double i = (double)(qp.x() - frameWidth()) / Settings::caseSize();
    double j = (double)(qp.y() - frameWidth()) / Settings::caseSize();
    return Coord((int)floor(i), (int)floor(j));
}

int Field::mapMouseButton(TQMouseEvent *e) const
{
	switch (e->button()) {
	case TQt::LeftButton:  return Settings::mouseAction(Settings::EnumButton::left);
	case TQt::MidButton:   return Settings::mouseAction(Settings::EnumButton::mid);
	case TQt::RightButton: return Settings::mouseAction(Settings::EnumButton::right);
	default:              return Settings::EnumMouseAction::ToggleFlag;
	}
}

void Field::revealActions(bool press)
{
    if ( _reveal==press ) return; // avoid flicker
    _reveal = press;

	switch (_currentAction) {
	case Reveal:
		pressCase(_cursor, press);
		break;
	case AutoReveal:
		pressClearFunction(_cursor, press);
		break;
	default:
		break;
	}
}

void Field::mousePressEvent(TQMouseEvent *e)
{
    if ( !isActive() || (_currentAction!=Settings::EnumMouseAction::None) ) return;

    emit setMood(Stressed);
    _currentAction = mapMouseButton(e);

    Coord p = fromPoint(e->pos());
    if ( !inside(p) ) return;
    placeCursor(p);
    revealActions(true);
}

void Field::mouseReleaseEvent(TQMouseEvent *e)
{
    if ( !isActive() ) return;

    int tmp = _currentAction;
    emit setMood(Normal);
    revealActions(false);
    int ma = mapMouseButton(e);
    _currentAction = Settings::EnumMouseAction::None;
    if ( ma!=tmp ) return;

    Coord p = fromPoint(e->pos());
    if ( !inside(p) ) return;
    placeCursor(p);

    switch (ma) {
    case Settings::EnumMouseAction::ToggleFlag:          doMark(p); break;
    case Settings::EnumMouseAction::ToggleUncertainFlag: doUmark(p); break;
    case Settings::EnumMouseAction::Reveal:              doReveal(p); break;
    case Settings::EnumMouseAction::AutoReveal:          doAutoReveal(p); break;
    default: break;
    }
}

void Field::mouseMoveEvent(TQMouseEvent *e)
{
	if ( !isActive() ) return;

    Coord p = fromPoint(e->pos());
    if ( p==_cursor ) return; // avoid flicker

	revealActions(false);
    if ( !inside(p) ) return;
    placeCursor(p);
	revealActions(true);
}

void Field::pressCase(const Coord &c, bool pressed)
{
	if ( state(c)==Covered ) {
        TQPainter painter(this);
        drawCase(painter, c, pressed);
    }
}

void Field::pressClearFunction(const Coord &p, bool pressed)
{
    pressCase(p, pressed);
    CoordList n = coveredNeighbours(p);
    TQPainter painter(this);
    for (CoordList::const_iterator it=n.begin(); it!=n.end(); ++it)
        drawCase(painter, *it, pressed);
}

void Field::keyboardAutoReveal()
{
	_cursor_back = _cursor;
	pressClearFunction(_cursor_back, true);
	TQTimer::singleShot(50, this, TQ_SLOT(keyboardAutoRevealSlot()));
}

void Field::keyboardAutoRevealSlot()
{
	pressClearFunction(_cursor_back, false);
	doAutoReveal(_cursor_back);
}

void Field::doAutoReveal(const Coord &c)
{
	if ( !isActive() ) return;
    if ( state(c)!=Uncovered ) return;
    emit addAction(c, AutoReveal);
    resetAdvised();
    doAction(AutoReveal, c, Settings::magicReveal());
}

void Field::pause()
{
    switch (_state) {
    case Paused:  setState(Playing); break;
    case Playing: setState(Paused); break;
    default: return;
    }
    update();
}

void Field::moveCursor(Neighbour n)
{
    Coord c = neighbour(_cursor, n);
    if ( inside(c) ) placeCursor(c);
}

void Field::moveToEdge(Neighbour n)
{
    Coord c = toEdge(_cursor, n);
    if ( inside(c) ) placeCursor(c);
}

bool Field::doReveal(const Coord &c, CoordList *autorevealed,
                     bool *caseUncovered)
{
	if ( !isActive() ) return true;
    if ( state(c)!=Covered ) return true;
    if ( firstReveal() ) setState(Playing);
    CaseState state =
        doAction(Reveal, c, Settings::magicReveal(), autorevealed, caseUncovered);
    emit addAction(c, Reveal);
    return ( state!=Error );
}

void Field::doMark(const Coord &c)
{
	if ( !isActive() ) return;
    ActionType action;
    CaseState oldState = state(c);
    switch (oldState) {
	case Covered:   action = SetFlag; break;
	case Marked:    action = (Settings::uncertainMark() ? SetUncertain : UnsetFlag); break;
	case Uncertain:	action = UnsetUncertain; break;
	default:        return;
	}
    CaseState newState = doAction(action, c, Settings::magicReveal());
    addMarkAction(c, newState, oldState);
}

void Field::doUmark(const Coord &c)
{
	if ( !isActive() ) return;
    ActionType action;
    CaseState oldState = state(c);
    switch (oldState) {
	case Covered:
	case Marked:    action = SetUncertain; break;
	case Uncertain: action = UnsetUncertain; break;
	default:        return;
	}
    CaseState newState = doAction(action, c, Settings::magicReveal());
    addMarkAction(c, newState, oldState);
}


KMines::CaseState Field::doAction(ActionType type, const Coord &c,
                                  bool complete, CoordList *autorevealed,
                                  bool *caseUncovered)
{
    resetAdvised();
    CaseState state = Error;
    if ( _solvingState==Solved ) complete = false;

    KNotifyClient::event(winId(), ACTION_DATA[type].event,
                         i18n(ACTION_DATA[type].eventMessage));
    switch (type) {
    case Reveal:
        if ( !reveal(c, autorevealed, caseUncovered) )
            emit gameStateChanged(GameOver);
        else {
            state = Uncovered;
            if (complete) completeReveal();
        }
        break;
    case AutoReveal:
        if ( !autoReveal(c, caseUncovered) )
            emit gameStateChanged(GameOver);
        else {
            state = Uncovered;
            if (complete) completeReveal();
        }
        break;
    case SetFlag:
        state = Marked;
        if (complete) completeReveal();
        break;
    case UnsetFlag:
    case UnsetUncertain:
        state = Covered;
        break;
    case SetUncertain:
        state = Uncertain;
        break;
    case Nb_Actions:
        Q_ASSERT(false);
        break;
    }

    if ( state!=Error ) changeCase(c, state);
    return state;
}

void Field::addMarkAction(const Coord &c, CaseState newS, CaseState oldS)
{
    switch (newS) {
    case Marked:    emit addAction(c, SetFlag); return;
    case Uncertain: emit addAction(c, SetUncertain); return;
    default: break;
    }
    switch (oldS) {
    case Marked:    emit addAction(c, UnsetFlag); return;
    case Uncertain: emit addAction(c, UnsetUncertain); return;
    default: break;
    }
}

void Field::placeCursor(const Coord &p)
{
    if ( !isActive() ) return;

    Q_ASSERT( inside(p) );
    Coord old = _cursor;
    _cursor = p;
    if ( Settings::keyboardGame() ) {
        TQPainter painter(this);
        drawCase(painter, old);
        drawCase(painter, _cursor);
    }
}

void Field::resetAdvised()
{
    if ( !inside(_advisedCoord) ) return;
    TQPainter p(this);
    Coord tmp = _advisedCoord;
    _advisedCoord = Coord(-1, -1);
    drawCase(p, tmp);
}

void Field::setAdvised(const Coord &c, double proba)
{
    resetAdvised();
	_solvingState = Advised;
	_advisedCoord = c;
    _advisedProba = proba;
    if ( inside(c) ) {
        TQPainter p(this);
        drawCase(p, c);
    }
}

void Field::drawCase(TQPainter &painter, const Coord &c, bool pressed) const
{
	Q_ASSERT( inside(c) );

    TQString text;
    uint nbMines = 0;
    PixmapType type = NoPixmap;

	switch ( state(c) ) {
    case Covered:
        break;
	case Marked:
        type = FlagPixmap;
        pressed = false;
        break;
	case Error:
        type = ErrorPixmap;
        pressed = true;
        break;
	case Uncertain:
        text = '?';
        pressed = false;
        break;
	case Exploded:
        type = ExplodedPixmap;
        pressed = true;
        break;
	case Uncovered:
        pressed = true;
        if ( hasMine(c) ) type = MinePixmap;
        else {
            nbMines = nbMinesAround(c);
            if (nbMines) text.setNum(nbMines);
        }
	}

    int i = -1;
    if ( c==_advisedCoord ) {
        if ( _advisedProba==1 ) i = 0;
        else if ( _advisedProba>0.75 ) i = 1;
        else if ( _advisedProba>0.5  ) i = 2;
        else if ( _advisedProba>0.25 ) i = 3;
        else i = 4;
    }

    bool hasFocus = ( Settings::keyboardGame() && (c==_cursor) );
    drawBox(painter, toPoint(c), pressed, type, text, nbMines, i, hasFocus);
}