summaryrefslogtreecommitdiffstats
path: root/kjumpingcube/brain.cpp
blob: d662057eed8d1e215e8b1c133cb829c3d946107f (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
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
/* ****************************************************************************
  This file is part of the game 'KJumpingCube'

  Copyright (C) 1998-2000 by Matthias Kiefer
                            <matthias.kiefer@gmx.de>

  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 "brain.h"
#include "cube.h"

#include <math.h>

#include <tdeapplication.h>

#undef DEBUG // uncomment this to get useful messages
#include <assert.h>

#ifdef DEBUG
#include <iostream.h>
#endif

#include "prefs.h"

Brain::Brain(int initValue)
{
   setSkill(Prefs::EnumSkill::Beginner);
   stopped=false;
   active=false;
   currentLevel=0;

   // initialize the random number generator
   random.setSeed(initValue);
}

void Brain::setSkill(int newSkill)
{
   _skill=newSkill;

   switch(_skill)
   {
      case Prefs::EnumSkill::Beginner:
         maxLevel=1;
	 break;
      case Prefs::EnumSkill::Average:
         maxLevel=3;
         break;
      case Prefs::EnumSkill::Expert:
         maxLevel=5;
         break;
      default:
         break;
   }
}

int Brain::skill() const
{
   return _skill;
}

void Brain::stop()
{
   stopped=true;
}


bool Brain::isActive()  const
{
   return active;
}



bool Brain::getHint(int& row, int& column,CubeBox::Player player ,CubeBox box)
{
   if(isActive())
      return false;

   active=true;
   stopped=false;
   currentPlayer=player;

   int i=0,j=0;
   int moves=0; // how many moves are the favourable ones
   CubeBox::Player opponent=(player==CubeBox::One)?CubeBox::Two : CubeBox::One;

   // if more than one cube has the same rating this array is used to select
   // one
   coordinate* c2m=new coordinate[box.dim()*box.dim()];

   // Array, which holds the assessment of the separate moves
   double **worth=new double*[box.dim()];
   for(i=0;i<box.dim();i++)
      worth[i]=new double[box.dim()];

   // alle Werte auf kleinstmöglichen Wert setzen
   double min=-pow(2.0,sizeof(long int)*8-1);  // Maximum auf kleinst möglichen Wert setzen

   for(i=0;i<box.dim();i++)
     for(j=0;j<box.dim();j++)
     {
        worth[i][j]=min;
     }


   // find the favourable cubes to increase
   moves=findCubes2Move(c2m,player,box);


   // if only one cube is found, then don't check recursively the move
   if(moves==1)
   {
#ifdef DEBUG
      cerr << "found only one favourable cube" << endl;
#endif
      row=c2m[0].row;
      column=c2m[0].column;
   }
   else
   {
#ifdef DEBUG
      cerr << "found more than one favourable cube: " << moves << endl;
#endif
      for(i=0;i<moves;i++)
      {
	 // if Thinking process stopped
	 if(stopped)
	 {
#ifdef DEBUG
	     cerr << "brain stopped" << endl;
#endif
	     active=false;
             for(i=0;i<box.dim();i++)
                delete[] worth[i];
             delete [] worth;

             delete [] c2m;

	     return false;
	 }

#ifdef DEBUG
	 cerr << "checking cube " << c2m[i].row << "," << c2m[i].column << endl;
#endif
         // for every found possible move, simulate this move and store the assessment
	 worth[c2m[i].row][c2m[i].column]=doMove(c2m[i].row,c2m[i].column,player,box);

#ifdef DEBUG
	 cerr << "cube "  << c2m[i].row << "," << c2m[i].column << " : " << worth[c2m[i].row][c2m[i].column] << endl;
#endif
      }


      // find the maximum
      double max=-1E99;  // set max to minimum value

#ifdef DEBUG
      cerr << "searching for the maximum" << endl;
#endif

      for(i=0;i<moves;i++)
      {
         if(box[c2m[i].row][c2m[i].column]->owner()!=(Cube::Owner)opponent)
         {
            if(worth[c2m[i].row][c2m[i].column]>max )
            {
               max=worth[c2m[i].row][c2m[i].column];
            }
         }
      }

#ifdef DEBUG
      cerr << "found Maximum : " << max << endl;
#endif

      // found maximum more than one time ?
      int counter=0;
      for(i=0;i<moves;i++)
      {
#ifdef DEBUG
         cerr << c2m[i].row << "," << c2m[i].column << " : " << worth[c2m[i].row][c2m[i].column] << endl;
#endif
         if(worth[c2m[i].row][c2m[i].column]==max)
            if(box[c2m[i].row][c2m[i].column]->owner() != (Cube::Owner)opponent)
	    {
	       c2m[counter].row=c2m[i].row;
	       c2m[counter].column=c2m[i].column;
	       counter++;
	    }
      }

      assert(counter>0);


      // if some moves are equal, choose a random one
      if(counter>1)
      {

#ifdef DEBUG
         cerr << "choosing a random cube: " << endl ;
#endif
         counter=random.getLong(counter);
      }

      row=c2m[counter].row;
      column=c2m[counter].column;
#ifdef DEBUG
      cerr << "cube: " << row << "," << column << endl;
#endif
   }

   // clean up
   for(i=0;i<box.dim();i++)
      delete[] worth[i];
   delete [] worth;

   delete [] c2m;

   active=false;

   return true;
}



double Brain::doMove(int row, int column, CubeBox::Player player , CubeBox box)
{
   double worth=0;
   currentLevel++; // increase the current depth of recurse calls


   // if the maximum depth isn't reached
   if(currentLevel < maxLevel)
   {
       // test, if possible to increase this cube
      if(!box.simulateMove(player,row,column))
      {
         currentLevel--;
         return 0;
      }

      // if the player has won after simulating this move, return the assessment of the field
      if(box.playerWon(player))
      {
         currentLevel--;

	 return (long int)pow((float)box.dim()*box.dim(),(maxLevel-currentLevel))*box.assessField(currentPlayer);
      }


      int i;
      int moves=0;
      // if more than one cube has the same rating this array is used to select
      // one
      coordinate* c2m=new coordinate[box.dim()*box.dim()];

      // the next move has does the other player
      player=(player==CubeBox::One)? CubeBox::Two : CubeBox::One;

      // find the favourable cubes to increase
      moves=findCubes2Move(c2m,player,box);

      // if only one cube is found, then don't check recursively the move
      if(moves==1)
      {
         box.simulateMove(player,c2m[0].row,c2m[0].column);
         worth=(long int)pow((float)box.dim()*box.dim(),(maxLevel-currentLevel-1))*box.assessField(currentPlayer);
      }
      else
      {
         for(i=0;i<moves;i++)
         {
            kapp->processEvents();

	    // if thinking process stopped
	    if(stopped)
	    {
	       currentLevel--;
	       return 0;
	    }

	    // simulate every possible move
	    worth+=doMove(c2m[i].row,c2m[i].column,player,box);
         }
      }
      delete [] c2m;
      currentLevel--;
      return worth;

   }
   else
   {
      // if maximum depth of recursive calls are reached, return the assessment
      currentLevel--;
      box.simulateMove(player,row,column);

      return box.assessField(currentPlayer);
   }

}

int Brain::findCubes2Move(coordinate *c2m,CubeBox::Player player,CubeBox& box)
{
   int i,j;
   int opponent=(player==CubeBox::One)? CubeBox::Two : CubeBox::One;
   int moves=0;
   int min=9999;

   if(_skill==Prefs::EnumSkill::Beginner)
   {
      int max=0;
      for(i=0;i<box.dim();i++)
        for(j=0;j<box.dim();j++)
        {
           if(box[i][j]->owner() != opponent)
           {
              c2m[moves].row=i;
              c2m[moves].column=j;
              c2m[moves].val=box[i][j]->value();

              if(c2m[moves].val>max)
                 max=c2m[moves].val;

              moves++;

	   }
        }

    // find all moves with maximum value
    int counter=0;
    for(i=0;i<moves;i++)
    {
       if(c2m[i].val==max)
       {
	  c2m[counter].row=c2m[i].row;
	  c2m[counter].column=c2m[i].column;
	  c2m[counter].val=c2m[i].val;

          counter++;
        }
     }

     if(counter!=0)
     {
        moves=counter;
     }
   }
   else // if skill is not Beginner
   {
      int secondMin=min;
      // put values on the cubes
      for(i=0;i<box.dim();i++)
        for(j=0;j<box.dim();j++)
        {
	   // use only cubes, who don't belong to the opponent
	   if(box[i][j]->owner() != opponent)
	   {
	      int val;

	      // check neighbours of every cube
	      val=assessCube(i,j,player,box);


#ifdef DEBUG
	      if(currentLevel==0)
	         cerr << i << "," << j << " : " << val << endl;
#endif
	      // only if val >= 0 its a favourable move
              if( val > 0 )
              {
	         if(val<min)
	         {
	            secondMin=min;
		    min=val;
	         }

	         // store coordinates
	         c2m[moves].row=i;
	         c2m[moves].column=j;
	         c2m[moves].val=val;
                 moves++;
	      }
	   }
        }


	// If all cubes are bad, check all cubes for the next move
	if(moves==0)
	{
	   min=4;
	   for(i=0;i<box.dim();i++)
	      for(j=0;j<box.dim();j++)
	      {
	         if(box[i][j]->owner() != opponent)
		 {
                    c2m[moves].row=i;
                    c2m[moves].column=j;
                    c2m[moves].val=( box[i][j]->max() - box[i][j]->value() );
                    if(c2m[moves].val<min)
                       min=c2m[moves].val;
                    moves++;
		 }
	      }
        }

	int counter=0;
	// find all moves with minimum assessment
	for(i=0;i<moves;i++)
	{
	   if(c2m[i].val==min)
	   {
              c2m[counter].row=c2m[i].row;
              c2m[counter].column=c2m[i].column;
              c2m[counter].val=c2m[i].val;

              counter++;
           }
	   else if(_skill == Prefs::EnumSkill::Average)
	   {
	      if(c2m[i].val == secondMin)
	      {
                 c2m[counter].row=c2m[i].row;
                 c2m[counter].column=c2m[i].column;
                 c2m[counter].val=c2m[i].val;

		 counter++;
	      }
	   }
	}

	if(counter!=0)
	{
	   moves=counter;
	}
   }

   int maxMoves=10;
	// if more than maxMoves moves are favourable, take maxMoves random moves
	// because it will take to much time if you check all
	if(moves > maxMoves)
	{
	   // find maxMoves random cubes to move with
	   coordinate* tempC2M=new coordinate[maxMoves];

	   coordinate tmp={-1,-1,0};
	   for(i=0;i<maxMoves;i++)
              tempC2M[i]=tmp;

	   // this array takes the random chosen numbers, so that no
	   // number will be taken two times
	   int *results=new int[moves];
	   for(i=0;i<moves;i++)
	      results[i]=0;

	   for(i=0;i<maxMoves;i++)
	   {
	      int temp;
	      do
	      {
	         temp=random.getLong(moves);
	      }
	      while(results[temp]!=0);

	      results[temp]=1;

	      tempC2M[i].row=c2m[temp].row;
	      tempC2M[i].column=c2m[temp].column;
	      tempC2M[i].val=c2m[temp].val;
	   }
	   delete [] results;

	   for(i=0;i<maxMoves;i++)
	   {
	      c2m[i].row=tempC2M[i].row;
	      c2m[i].column=tempC2M[i].column;
	      c2m[i].val=tempC2M[i].val;
	   }
	   delete [] tempC2M;

	   moves=maxMoves;
	}


   return moves;

}


int Brain::assessCube(int row,int column,CubeBox::Player player,CubeBox& box) const
{
   int diff;

   if(row==0)  // first row
   {
      if(column == 0)  // upper left corner
      {
         diff=getDiff(0,1,player,box) ;
         int temp=getDiff(1,0,player,box);
         if(temp < diff)
            diff=temp;
      }
      else if(column == box.dim()-1) // upper right corner
      {
         diff=getDiff(0,column-1,player,box);
         int temp=getDiff(1,column,player,box);
         if(temp < diff)
	    diff=temp;
      }
      else
      {
         diff=getDiff(row,column-1,player,box);
         int temp=getDiff(row,column+1,player,box);
         if(temp < diff)
            diff = temp;
         temp=getDiff(row+1,column,player,box);
         if(temp < diff)
            diff = temp;
      }
   }
   else if(row==box.dim()-1) // last row
   {
      if(column == 0) // lower left corner
      {
         diff=getDiff(row,1,player,box);
         int temp=getDiff(row-1,0,player,box);
         if(temp < diff)
            diff=temp;
      }
      else if(column == box.dim()-1) // lower right corner
      {
         diff=getDiff(row,column-1,player,box);
         int temp=getDiff(row-1,column,player,box);
         if(temp < diff)
            diff=temp;
      }
      else
      {
         diff=getDiff(row,column-1,player,box);
         int temp=getDiff(row,column+1,player,box);
         if(temp < diff)
            diff = temp;
         temp=getDiff(row-1,column,player,box);
         if(temp < diff)
            diff = temp;
      }
   }
   else if(column == 0) // first column
   {
       diff = getDiff(row,1,player,box);
       int temp = getDiff(row-1,0,player,box);
       if(temp < diff)
          diff = temp;
       temp = getDiff(row+1,0,player,box);
       if(temp < diff)
          diff = temp;
   }
   else if(column == box.dim()-1) // last column
   {
      diff = getDiff(row,column-1,player,box);
      int temp = getDiff(row-1,column,player,box);
      if(temp < diff)
         diff = temp;
      temp = getDiff(row+1,column,player,box);
      if(temp < diff)
         diff = temp;
   }
   else
   {
      diff=getDiff(row-1,column,player,box);
      int temp=getDiff(row+1,column,player,box);
      if(temp < diff)
         diff = temp;
      temp=getDiff(row,column-1,player,box);
      if(temp < diff)
         diff = temp;
      temp=getDiff(row,column+1,player,box);
      if(temp < diff)
         diff = temp;
   }

   int temp;
   temp=( box[row][column]->max()-box[row][column]->value() );

   int val;
   val=diff-temp+1;
   val=val*(temp+1);

   return val;
}


int Brain::getDiff(int row,int column, CubeBox::Player player, CubeBox& box) const
{
	int diff;

	if(box[row][column]->owner() != (Cube::Owner)player)
	{
           diff=( box[row][column]->max() - box[row][column]->value() );
	}
	else
	{
           diff=( box[row][column]->max() - box[row][column]->value()+1 );
	}

	return diff;
}