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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
|
/* Yo Emacs, this -*- C++ -*-
Copyright (C) 1999-2001 Jens Hoefkens
jens@hoefkens.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.
$Id$
*/
#include "kbggnubg.moc"
#include "kbggnubg.h"
#include <kapplication.h>
#include <kmessagebox.h>
#include <stdlib.h>
#include <time.h>
#include <unistd.h>
#include <tqlayout.h>
#include <kiconloader.h>
#include <kstdaction.h>
#include <tqbuttongroup.h>
#include <tqcheckbox.h>
#include <kconfig.h>
#include <iostream>
#include <klocale.h>
#include <kmainwindow.h>
#include <klineeditdlg.h>
#include <tqregexp.h>
#include <kregexp.h>
#include <knotifyclient.h>
#include <string.h>
#include <stdio.h>
#include <signal.h>
#include "kbgstatus.h"
#include "kbgboard.h"
#include "version.h"
// == cube =====================================================================
/*
* Double the cube for the player that can double - asks player
*/
void KBgEngineGNU::cube()
{
handleCommand("double");
}
/*
* Double the cube for player w
*/
void KBgEngineGNU::doubleCube(const int w)
{
dummy = w; // avoid compiler warning
cube();
}
void KBgEngineGNU::handleLine(const TQString &l)
{
if (l.isEmpty())
return;
TQString line(l);
/*
* Start of a new game/match
*/
if (line.contains(TQRegExp("^gnubg rolls [1-6], .* rolls [1-6]\\."))) {
KRegExp e("^gnubg rolls ([1-6]), .* rolls ([1-6])\\.");
e.match(line.latin1());
if (int r = strcmp(e.group(1), e.group(2)))
turn = (r < 0) ? uRoll : tRoll;
}
/*
* Bug fixes for older versions of GNUBG - to be removed
*/
if (line.contains(TQRegExp("^.* cannot move\\..+$"))) {
KRegExp e("(^.* cannot move.)(.*$)");
e.match(line.latin1());
handleLine(e.group(1));
handleLine(e.group(2));
return;
}
if (line.contains(TQRegExp("^Are you sure you want to start a new game, and discard the one in progress\\?"))) {
KRegExp e("(^Are you sure you want to start a new game, and discard the one in progress\\? )(.+$)");
e.match(line.latin1());
handleLine(e.group(1));
handleLine(e.group(2));
return;
}
/*
* Cube handling
*/
if (line.contains(TQRegExp("^gnubg accepts and immediately redoubles to [0-9]+\\.$"))) {
// redoubles mess up the game counter "turn"
//KBgtqStatus st(board);
//st.setCube(32, BOTH);
//emit newState(st);
}
if (line.contains(TQRegExp("^gnubg doubles\\.$"))) {
// TODO: we need some generic class for this. the class
// can be shared between all engines
#if 0
KBgtqStatus st(board);
int ret = KMessageBox::warningYesNoCancel
(0, i18n("gnubg doubles the cube to %1.").tqarg(2*st.cube(THEM)),
i18n("gnubg doubles"),
i18n("&Accept"), i18n("Re&double"), i18n("&Reject"), true);
switch (ret) {
case KMessageBox::Yes:
handleCommand("accept");
break;
case KMessageBox::No:
handleCommand("redouble");
break;
case KMessageBox::Cancel:
handleCommand("reject");
break;
}
#endif
}
/*
* Ignore the following messages
*/
if (line.contains(TQRegExp("^TTY boards will be given in raw format"))) {
line = " ";
}
/*
* Board messages
*/
if (line.contains(TQRegExp("^board:"))) {
KBgtqStatus st(line);
/*
* Do preliminary analysis of board
*/
if (st.doubled()) {
--turn;
return;
}
if (strcmp(board.latin1(),line.latin1()))
++turn %= maxTurn;
board = line;
/*
* Act according to the current state in the move/roll cycle
*/
switch (turn) {
case uRoll:
if (st.cube() > 0) {
emit infoText(i18n("Please roll or double."));
KNotifyClient::event("roll or double");
} else {
emit infoText(i18n("Please roll."));
KNotifyClient::event("roll");
}
emit allowCommand(Roll, true);
emit allowCommand(Cube, true);
break;
case uMove:
st.setDice(THEM, 0, 0);
st.setDice(THEM, 1, 0);
emit infoText(i18n("You roll %1 and %2.").tqarg(st.dice(US, 0)).tqarg(st.dice(US, 1)));
switch (st.moves()) {
case 0:
// get a message
break;
case 1:
emit infoText(i18n("Please move 1 piece."));
break;
default:
emit infoText(i18n("Please move %1 pieces.").tqarg(st.moves()));
break;
}
emit allowCommand(Roll, false);
break;
case tRoll:
break;
case tMove:
st.setDice(US, 0, 0);
st.setDice(US, 1, 0);
emit infoText(i18n("gnubg rolls %1 and %2.").tqarg(st.dice(THEM, 0)).tqarg(st.dice(THEM, 1)));
if (st.moves() == 0)
emit infoText(i18n("gnubg cannot move."));
break;
}
/*
* Bookkeeping
*/
undoCounter = 0;
toMove = st.moves();
emit allowMoving(st.turn() == US);
emit newState(st);
emit statText(i18n("%1 vs. %2").tqarg(st.player(US)).tqarg(st.player(THEM)));
emit allowCommand(Load, true );
emit allowCommand(Undo, false);
emit allowCommand(Redo, false);
emit allowCommand(Done, false);
return;
}
/*
* Show the line...
*/
line.replace(TQRegExp(" "), " ");
if (!line.isEmpty())
emit infoText(line);
}
/*
* Handle textual commands. All commands are passed to gnubg.
*/
void KBgEngineGNU::handleCommand(const TQString& cmd)
{
cmdList += cmd;
nextCommand();
}
// == start and init games =====================================================
/*
* Start a new game.
*/
void KBgEngineGNU::newGame()
{
/*
* If there is a game running we warn the user first
*/
if (gameRunning && (KMessageBox::warningYesNo((TQWidget *)tqparent(),
i18n("A game is currently in progress. "
"Starting a new one will terminate it."),
TQString(), i18n("Start New Game"), i18n("Continue Old Game"))
== KMessageBox::No))
return;
/*
* Start new game
*/
handleCommand("new game");
if (gameRunning)
handleCommand("yes");
gameRunning = true;
emit infoText(i18n("Starting a new game."));
}
// == various slots & functions ================================================
/*
* Quitting is fine at any time
*/
bool KBgEngineGNU::queryClose()
{
return true;
}
/*
* Quitting is fine at any time
*/
bool KBgEngineGNU::queryExit()
{
return true;
}
/*
* Load the last known sane state of the board
*/
void KBgEngineGNU::load()
{
handleCommand("show board");
}
/*
* Store if cmd is allowed or not
*/
void KBgEngineGNU::setAllowed(int cmd, bool f)
{
switch (cmd) {
case Roll:
rollingAllowed = f;
return;
case Undo:
undoPossible = f;
return;
case Cube:
doublePossible = f;
return;
case Done:
donePossible = f;
return;
}
}
// == configuration handling ===================================================
void KBgEngineGNU::setupOk()
{
// nothing yet
}
void KBgEngineGNU::setupCancel()
{
// nothing yet
}
void KBgEngineGNU::setupDefault()
{
// nothing yet
}
void KBgEngineGNU::getSetupPages(KDialogBase *nb)
{
/*
* Main Widget
*/
TQVBox *w = nb->addVBoxPage(i18n("GNU Engine"), i18n("Here you can configure the GNU backgammon engine"),
kapp->iconLoader()->loadIcon(PROG_NAME "_engine", KIcon::Desktop));
}
/*
* Restore settings
*/
void KBgEngineGNU::readConfig()
{
KConfig* config = kapp->config();
config->setGroup("gnu engine");
// nothing yet
}
/*
* Save the engine specific settings
*/
void KBgEngineGNU::saveConfig()
{
KConfig* config = kapp->config();
config->setGroup("gnu engine");
// nothing yet
}
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// *****************************************************************************
// == constructor, destructor and other ========================================
/*
* Constructor
*/
KBgEngineGNU::KBgEngineGNU(TQWidget *tqparent, TQString *name, TQPopupMenu *pmenu)
: KBgEngine(tqparent, name, pmenu)
{
// obsolete
nameUS = "US";
nameTHEM = "THEM";
random.setSeed(getpid()*time(NULL));
/*
* internal statue variables
*/
rollingAllowed = undoPossible = gameRunning = donePossible = false;
connect(this, TQT_SIGNAL(allowCommand(int, bool)), this, TQT_SLOT(setAllowed(int, bool)));
/*
* Setup of menu
*/
resAction = new KAction(i18n("&Restart GNU Backgammon"), 0, this, TQT_SLOT(startGNU()), this);
resAction->setEnabled(false); resAction->plug(menu);
/*
* Restore last stored settings
*/
readConfig();
}
/*
* Destructor. Kill the child process and that's it.
*/
KBgEngineGNU::~KBgEngineGNU()
{
gnubg.kill();
}
// == start, restart, termination of gnubg =====================================
/*
* Start the GNU Backgammon process in the background and set up
* some communication links.
*/
void KBgEngineGNU::start()
{
/*
* Will be started later
*/
cmdTimer = new TQTimer(this);
connect(cmdTimer, TQT_SIGNAL(timeout()), TQT_SLOT(nextCommand()) );
emit infoText(i18n("This is experimental code which currently requires a specially "
"patched version of GNU Backgammon.<br/><br/>"));
/*
* Initialize variables
*/
partline = board = "";
/*
* Start the process - this requires that gnubg is in the PATH
*/
gnubg << "gnubg" << "--tty";
connect(&gnubg, TQT_SIGNAL(processExited(KProcess *)), this, TQT_SLOT(gnubgExit(KProcess *)));
connect(&gnubg, TQT_SIGNAL(receivedStderr(KProcess *, char *, int)),
this, TQT_SLOT(receiveData(KProcess *, char *, int)));
connect(&gnubg, TQT_SIGNAL(receivedStdout(KProcess *, char *, int)),
this, TQT_SLOT(receiveData(KProcess *, char *, int)));
connect(&gnubg, TQT_SIGNAL(wroteStdin(KProcess *)), this, TQT_SLOT(wroteStdin(KProcess *)));
startGNU();
}
/*
* Actually start the background process.
*/
void KBgEngineGNU::startGNU()
{
resAction->setEnabled(false);
if (!gnubg.start(KProcess::NotifyOnExit, KProcess::All))
KMessageBox::information((TQWidget *)tqparent(),
i18n("Could not start the GNU Backgammon process.\n"
"Make sure the program is in your PATH and is "
"called \"gnubg\".\n"
"Make sure that your copy is at least version 0.10"));
/*
* Set required gnubg options
*/
handleCommand("set output rawboard on");
}
/*
* The gnubg process has died. Stop all user activity and allow a restart.
*/
void KBgEngineGNU::gnubgExit(KProcess *proc)
{
ct->stop();
cmdTimer->stop();
emit allowCommand(Undo, false);
emit allowCommand(Roll, false);
emit allowCommand(Done, false);
emit allowCommand(Cube, false);
emit allowCommand(Load, false);
emit allowMoving(false);
emit infoText(TQString("<br/><font color=\"red\">") + i18n("The GNU Backgammon process (%1) has exited. ")
.tqarg(proc->pid()) + "</font><br/>");
resAction->setEnabled(true);
}
// == communication callbacks with GNU bg ======================================
/*
* Last command has been sent. Try to send pending ones.
*/
void KBgEngineGNU::wroteStdin(KProcess *proc)
{
if (!proc->isRunning())
return;
nextCommand();
}
/*
* Try to send the next command from the command list to gnubg.
* If it fails, make sure we call ourselves again.
*/
void KBgEngineGNU::nextCommand()
{
if (!gnubg.isRunning())
return;
for (TQStringList::Iterator it = cmdList.begin(); it != cmdList.end(); ++it) {
TQString s = (*it) + "\n";
if (!gnubg.writeStdin(s.latin1(), strlen(s.latin1()))) {
cmdTimer->start(250, true);
cmdList.remove(TQString());
return;
}
(*it) = TQString();
}
cmdList.remove(TQString());
cmdTimer->stop();
}
/*
* Get data from GNU Backgammon and process them. Note that we may have
* to buffer the last line and wait for the closing newline...
*/
void KBgEngineGNU::receiveData(KProcess *proc, char *buffer, int buflen)
{
if (!proc->isRunning())
return;
char *buf = new char[buflen+1];
memcpy(buf, buffer, buflen);
buf[buflen] = '\0';
TQStringList l(TQStringList::split('\n', buf, true));
/*
* Restore partial lines from the previous time
*/
l.first() = partline + l.first();
partline = "";
if (buf[buflen-1] != '\n') {
partline = l.last();
l.remove(partline);
}
delete[] buf;
/*
* Handle the information from gnubg
*/
for (TQStringList::Iterator it = l.begin(); it != l.end(); ++it)
handleLine(*it);
}
// == moving ===================================================================
/*
* Finish the last move - called by the timer and directly by the user
*/
void KBgEngineGNU::done()
{
ct->stop();
emit allowMoving(false);
emit allowCommand(Done, false);
emit allowCommand(Undo, false);
emit allowCommand(Redo, false);
// Transform the string to FIBS format
lastmove.replace(0, 2, "move ");
lastmove.replace(TQRegExp("\\+"), " ");
lastmove.replace(TQRegExp("\\-"), " ");
// sent it to the server
handleCommand(lastmove);
}
/*
* Undo the last move
*/
void KBgEngineGNU::undo()
{
ct->stop();
redoPossible = true;
++undoCounter;
emit allowMoving(true);
emit allowCommand(Done, false);
emit allowCommand(Redo, true);
emit undoMove();
}
/*
* Redo the last move
*/
void KBgEngineGNU::redo()
{
--undoCounter;
emit redoMove();
}
/*
* Take the move string and make the changes on the working copy
* of the state.
*/
void KBgEngineGNU::handleMove(TQString *s)
{
lastmove = *s;
int index = 0;
TQString t = s->mid(index, s->find(' ', index));
index += 1 + t.length();
int moves = t.toInt();
/*
* Allow undo and possibly start the commit timer
*/
redoPossible &= ((moves < toMove) && (undoCounter > 0));
emit allowCommand(Undo, moves > 0);
emit allowCommand(Redo, redoPossible);
emit allowCommand(Done, moves == toMove);
if (moves == toMove && cl >= 0) {
emit allowMoving(false);
ct->start(cl, true);
}
}
// == dice & rolling ===========================================================
/*
* Roll random dice for the player whose turn it is. We can ignore the
* value of w, since we have the turn value.
*/
void KBgEngineGNU::roll()
{
if (turn == uRoll)
handleCommand("roll");
}
void KBgEngineGNU::rollDice(const int w)
{
roll();
}
// EOF
|