summaryrefslogtreecommitdiffstats
path: root/libksirtet/common/ai.cpp
blob: bc1c67225545741d0745eedd4a75b6947d51d14f (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
#include "ai.h"
#include "ai.moc"

#include <assert.h>

#include <qlabel.h>
#include <qhbox.h>
#include <qvbox.h>
#include <qlayout.h>
#include <qgrid.h>
#include <qwhatsthis.h>

#include <klocale.h>
#include <kconfig.h>
#include <kapplication.h>

#include "commonprefs.h"
#include "board.h"
#include "base/piece.h"
#include "base/factory.h"


//-----------------------------------------------------------------------------
AIPiece::AIPiece()
    : _current(0)
{}

AIPiece::~AIPiece()
{
    delete _current;
}

void AIPiece::init(const Piece *piece, Board *b)
{
    _piece = piece;
    _board = b;
    if ( _current==0 ) _current = new Piece;
    reset();
}

void AIPiece::reset()
{
    curPos = 0;
    curRot = 0;
    if (_piece) _current->copy(_piece);
//    else _current->generateNext(0);
    nbRot = _current->nbConfigurations() - 1;
    nbPos = _board->matrix().width() - _current->size().first + 1;
}

bool AIPiece::increment()
{
    curPos++;
    if ( curPos==nbPos ) {
        if ( curRot==nbRot ) {
//            if ( _piece || _current->type()==Piece::info().nbTypes() ) {
                reset();
                return false;
//            }
//            _current->generateNext(_current->type()+1);
//            nbRot = _current->nbConfigurations() - 1;
//            curRot = 0;
        }
        _current->rotate(true, QPoint(0, 0));
        nbPos = _board->matrix().width() - _current->size().first + 1;
        curRot++;
        curPos = 0;
    }
    return true;
}

bool AIPiece::place()
{
    if ( curRot==3 ) {
        if ( !_board->rotateRight() ) return false;
    } else for (uint i=0; i<curRot; i++)
        if ( !_board->rotateLeft() ) return false;
    curDec = curPos - _board->currentPos().first - _current->min().first;
    if ( curDec!=0 && _board->moveRight(curDec)!=(uint)kAbs(curDec) )
        return false;
    _board->dropDown();
    return !_board->isGameOver();
}

//-----------------------------------------------------------------------------
const AI::Data AI::LastData = { 0, 0, 0, false, 0 };

AI::AI(uint tTime, uint oTime, const Data *DATA)
    : timer(this), thinkTime(tTime), orderTime(oTime), stopped(false),
      board(0)
{
    connect(&timer, SIGNAL(timeout()), SLOT(timeout()));

    for (uint i=0; DATA[i].name; i++) {
        Element element;
        element.coefficient = 0.;
        element.trigger = 0;
        element.data = &DATA[i];
        _elements.append(element);
    }
    settingsChanged();
}

void AI::resizePieces(uint size)
{
    uint oldSize = pieces.size();
    for (uint i=size; i<oldSize; i++) delete pieces[i];
    pieces.resize(size);
    for (uint i=oldSize; i<size; i++) pieces[i] = new AIPiece;
}

AI::~AI()
{
    delete board;
    resizePieces(0);
}

void AI::initThink()
{
    board->copy(*main);
}

void AI::launch(Board *m)
{
    main = m;
    if ( board==0 )
        board = static_cast<Board *>(bfactory->createBoard(false, 0));

    pieces[0]->init(main->currentPiece(), board); // current
    if ( pieces.size()>=2 ) pieces[1]->init(main->nextPiece(), board); // next

    state = Thinking;
    hasBestPoints = false;
    startTimer();
}

void AI::stop()
{
    timer.stop();
    stopped = true;
}

void AI::start()
{
    if (stopped) {
        startTimer();
        stopped = false;
    }
}

void AI::startTimer()
{
    switch (state) {
    case Thinking:     timer.start(thinkTime, true); break;
    case GivingOrders: timer.start(orderTime, true); break;
    }
}

void AI::timeout()
{
    switch (state) {
    case Thinking:
        if ( think() ) state = GivingOrders;
        break;
    case GivingOrders:
        if ( emitOrder() ) return;
        break;
    }

    startTimer();
}

bool AI::emitOrder()
{
    if ( bestRot==3 ) {
        bestRot = 0;
        main->pRotateRight();
    } else if (bestRot) {
        bestRot--;
        main->pRotateLeft();
    } else if ( bestDec>0 ) {
        bestDec--;
        main->pMoveRight();
    } else if ( bestDec<0 ) {
        bestDec++;
        main->pMoveLeft();
    } else {
        main->pDropDownStart();
        return true;
    }
    return false;
}

bool AI::think()
{
    initThink();
    bool moveOk = true;
    for (uint i=0; i<pieces.size(); i++)
        if ( !pieces[i]->place() ) {
            moveOk = false;
            break;
        }
    if (moveOk) {
        double p = points();
        if ( !hasBestPoints || p>bestPoints
             || (p==hasBestPoints && random.getBool()) ) {
            hasBestPoints = true;
            bestPoints = p;
            bestDec = pieces[0]->dec();
            bestRot = pieces[0]->rot();
        }
    }

    for (uint i=pieces.size(); i>0; i--)
        if ( pieces[i-1]->increment() ) return false;
    return true;
}

double AI::points() const
{
    double pts = 0;
    for (uint i=0; i<_elements.size(); i++) {
        if ( _elements[i].coefficient==0.0 ) continue;
        double v = _elements[i].data->function(*main, *board);
        if ( _elements[i].data->triggered && qRound(v)<_elements[i].trigger )
            continue;
        pts += _elements[i].coefficient * v;
    }
    return pts;
}

void AI::settingsChanged()
{
    int d = CommonPrefs::thinkingDepth();
    resizePieces(d);
    for (uint i=0; i<_elements.size(); i++) {
        const Data &data = *_elements[i].data;
        _elements[i].coefficient = AIConfig::coefficient(data);
        if (data.triggered) _elements[i].trigger = AIConfig::trigger(data);
    }
    if ( timer.isActive() ) launch(main);
}

double AI::nbOccupiedLines(const Board &, const Board &current)
{
    return current.matrix().height() - current.nbClearLines();
}

double AI::nbHoles(const Board &, const Board &current)
{
    uint nb = 0;
    for (uint i=0; i<current.matrix().width(); i++) {
        for (int j=current.firstColumnBlock(i)-1; j>=0; j--) {
            KGrid2D::Coord c(i, j);
            if ( current.matrix()[c]==0 ) nb++;
        }
    }
    return nb;
}

double AI::peakToPeak(const Board &, const Board &current)
{
    int min = current.matrix().height()-1;
    for (uint i=0; i<current.matrix().width(); i++)
        min = kMin(min, current.firstColumnBlock(i));
    return (int)current.firstClearLine()-1 - min;
}

double AI::mean(const Board &, const Board &current)
{
    double mean = 0;
    for (uint i=0; i<current.matrix().width(); i++)
        mean += current.firstColumnBlock(i);
    return mean / current.matrix().width();
}

double AI::nbSpaces(const Board &main, const Board &current)
{
    double nb = 0;
    double m = mean(main, current);
    for (uint i=0; i<current.matrix().width(); i++) {
        int j = current.firstColumnBlock(i);
        if ( j<m ) nb += m - j;
    }
    return nb;
}

double AI::nbRemoved(const Board &main, const Board &current)
{
    return current.nbRemoved() - main.nbRemoved();
}


//-----------------------------------------------------------------------------
const uint AIConfig::minThinkingDepth = 1;
const uint AIConfig::maxThinkingDepth = 2;

AIConfig::AIConfig(const QValueVector<AI::Element> &elements)
    : QWidget(0, "ai config")
{
    QGridLayout *top = new QGridLayout(this, 3, 2, KDialog::marginHint(),
                                       KDialog::spacingHint());

    QLabel *label = new QLabel(i18n("Thinking depth:"), this);
    top->addWidget(label, 0, 0);
    KIntNumInput *in = new KIntNumInput(this, "kcfg_ThinkingDepth");
    in->setRange(minThinkingDepth, maxThinkingDepth);
    top->addWidget(in, 0, 1);

    top->addRowSpacing(1, KDialog::spacingHint());

    QGrid *grid = new QGrid(2, this);
    top->addMultiCellWidget(grid, 2, 2, 0, 1);
    for (uint i=0; i<elements.size(); i++) {
        const AI::Data &data = *elements.at(i).data;
        QLabel *label = new QLabel(i18n(data.label), grid);
        if (data.whatsthis) QWhatsThis::add(label, i18n(data.whatsthis));
        label->setFrameStyle(QFrame::Panel | QFrame::Plain);

        QVBox *vb = new QVBox(grid);
        if (data.whatsthis) QWhatsThis::add(vb, i18n(data.whatsthis));
        vb->setMargin(KDialog::spacingHint());
        vb->setSpacing(KDialog::spacingHint());
        vb->setFrameStyle(QFrame::Panel | QFrame::Plain);
        if (data.triggered) {
            KIntNumInput *trig = new KIntNumInput(vb, triggerKey(data.name));
            trig->setRange(0, 10, 1, true);
        }
        KDoubleNumInput *coeff = new KDoubleNumInput(vb, coefficientKey(data.name));
        coeff->setRange(0.0, 1.0, 1.0, true);
    }
}

QCString AIConfig::triggerKey(const char *name)
{
    return "kcfg_Trigger_" + QCString(name);
}

QCString AIConfig::coefficientKey(const char *name)
{
    return "kcfg_Coefficient_" + QCString(name);
}

double AIConfig::coefficient(const AI::Data &data)
{
    KConfigSkeletonItem *item = CommonPrefs::self()->findItem( QString("Coefficient_%1").arg(data.name) );
    assert(item);
    return item->property().toDouble();
}

int AIConfig::trigger(const AI::Data &data)
{
    KConfigSkeletonItem *item = CommonPrefs::self()->findItem( QString("Trigger_%1").arg(data.name) );
    assert(item);
    return item->property().toInt();
}