summaryrefslogtreecommitdiffstats
path: root/kreversi/Position.cpp
blob: 22ffb3cfb7fa1b28832ea65d3bc294094e2c8d65 (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
/* Yo Emacs, this -*- C++ -*-
 *******************************************************************
 *******************************************************************
 *
 *
 * KREVERSI
 *
 *
 *******************************************************************
 *
 * A Reversi (or sometimes called Othello) game
 *
 *******************************************************************
 *
 * Created 1997 by Mario Weilguni <[email protected]>. This file
 * is ported from Mats Luthman's <[email protected]> JAVA applet.
 * Many thanks to Mr. Luthman who has allowed me to put this port
 * under the GNU GPL. Without his wonderful game engine kreversi
 * would be just another of those Reversi programs a five year old
 * child could beat easily. But with it it's a worthy opponent!
 *
 * If you are interested on the JAVA applet of Mr. Luthman take a
 * look at http://www.sylog.se/~mats/
 *
 *******************************************************************
 *
 * This file is part of the KDE project "KREVERSI"
 *
 * KREVERSI 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, or (at your option)
 * any later version.
 *
 * KREVERSI 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 KREVERSI; see the file COPYING.  If not, write to
 * the Free Software Foundation, 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 *******************************************************************
 */

// The class Position is used to represent an Othello position as white and
// black pieces and empty squares (see class Score) on an 8x8 Othello board.


#include "kdebug.h"

#include "Position.h"
#include <stdlib.h>


Position::Position()
{
  setupStartPosition();
}


Position::Position(Position &pos, SimpleMove &move)
{
  constrCopy(pos, move);
}


Position &Position::operator=(Position &pos)
{
  // Copy the position itself.
  for (uint row = 0; row < 10; row++)
    for (uint col = 0; col < 10; col++)
      m_board[row][col] = pos.m_board[row][col];
  m_toMove = pos.m_toMove;

  m_score    = pos.m_score;

  return *this;
}


// ----------------------------------------------------------------
//                Helpers to the constructors


// Construct a Position by copying another one and then make a move.
//

void Position::constrCopy(Position &pos, SimpleMove &move)
{
  *this = pos;
  doMove(move);
}


// Setup the Position by setting it to the initial Reversi position.

void Position::setupStartPosition()
{
  // Initialize the real board
  for (uint i = 0; i < 10; i++)
    for (uint j = 0; j < 10; j++)
      m_board[i][j] = Nobody;

  // The initial position
  m_board[4][4] = White;
  m_board[5][5] = White;
  m_board[5][4] = Black;
  m_board[4][5] = Black;

  // Black always starts the game in Reversi.
  m_toMove = Black;

  // Each side starts out with two pieces.
  m_score.set(White, 2);
  m_score.set(Black, 2);
}


// ----------------------------------------------------------------
//                          Access methods


Color Position::color(uint x, uint y) const
{
  if (x < 1 || x > 8 || y < 1 || y > 8)
    return Nobody;

  return m_board[x][y];
}


// ----------------------------------------------------------------
//                      Moves in the position


// Return true if the move is legal.
//
// NOTE: This function does *NOT* test wether the move is done
//       by the color to move.  That must be checked separately.
//

bool Position::moveIsLegal(SimpleMove &move) const
{
  if (m_board[move.x()][move.y()] != Nobody) 
    return false;

  Color  color    = move.color();
  Color  opponent = ::opponent(color);

  // Check in all directions and see if there is a turnable row of
  // opponent pieces.  If there is at least one such row, then the
  // move is legal.
  for (int xinc = -1; xinc <= 1; xinc++) {
    for (int yinc = -1; yinc <= 1; yinc++) {
      int  x, y;

      if (xinc == 0 && yinc == 0)
	continue;

      // Find the end of such a row of pieces.
      for (x = move.x()+xinc, y = move.y()+yinc; m_board[x][y] == opponent;
	   x += xinc, y += yinc)
	;

      // If the row ends with a piece of our own and there was at
      // least one opponent piece between it and the move point, then
      // we have found a turnable row.
      if (m_board[x][y] == color 
	  && (x - xinc != move.x() || y - yinc != move.y()))
	return true;
    }
  }

  return false;
}


// See if 'color' can make a move in the current position.  This is
// independent of wether it is 'color's turn to move or not.

bool Position::moveIsPossible(Color color) const
{
  // Make it simple: Step through all squares and see if it is a legal move.
  for (uint i = 1; i < 9; i++)
    for (uint j = 1; j < 9; j++) {
      SimpleMove  move(color, i, j);

      if (moveIsLegal(move)) 
	return true;
    }

  return false;
}


// Return true if any side can move.  (If not, the game is over.)

bool Position::moveIsAtAllPossible() const
{
  return (moveIsPossible(White) || moveIsPossible(Black));
}


// Make a move in the position.  
//
// Return true if the move was legal, otherwise return false.
//
bool Position::doMove(SimpleMove &move, QValueList<char> *turned)
{
  if (move.color() == Nobody)
    return false;

  Color  color    = move.color();
  Color  opponent = ::opponent(color);

  // Put the piece on the board
  m_board[move.x()][move.y()] = color;
  m_score.inc(color);

  // Turn pieces.
  uint  scoreBefore = m_score.score(color);
  for (int xinc = -1; xinc <= 1; xinc++) {
    for (int yinc = -1; yinc <= 1; yinc++) {
      int x, y;

      // Skip the case where both xinc and yinc == 0, since then we
      // won't move in any direction at all.
      if (xinc == 0 && yinc == 0)
	continue;

      // Find the end point (x, y) of a possible row of turnable pieces.
      for (x = move.x()+xinc, y = move.y()+yinc; m_board[x][y] == opponent;
	   x += xinc, y += yinc)
	;

      // If the row was indeed turnable, then do it.
      if (m_board[x][y] == color) {
	for (x -= xinc, y -= yinc; x != move.x() || y != move.y();
	     x -= xinc, y -= yinc) {
	  // Turn the piece.
	  m_board[x][y] = color;
	  if (turned)
	    turned->append(10 * x + y);

	  // Make the piece count correct again.
	  m_score.inc(color);
	  m_score.dec(opponent);
	}
      }
    }
  }

  // If nothing was turned, the move wasn't legal.
  if (m_score.score(color) == scoreBefore) {
    m_board[move.x()][move.y()] = Nobody;
    m_score.dec(color);

    return false;
  }

  // Set the next color to move.
  if (moveIsPossible(opponent))
    m_toMove = opponent;
  else if (moveIsPossible(color))
    m_toMove = color;
  else
    m_toMove = Nobody;

  return true;
}


bool Position::doMove(Move &move)
{
  move.m_turnedPieces.clear();
  return doMove((SimpleMove &) move, &move.m_turnedPieces);
}


bool Position::undoMove(Move &move)
{
  Color  color = move.color();
  Color  other = opponent(color);

  // Sanity checks
  // 1. The move must be on the board and be of the right color.
  if (color != m_board[move.x()][move.y()]) {
    //kdDebug() << "move on the board is wrong color: " << (int) color << "["
    //      << move.x() << "," << move.y() << "]" << endl;
    return false;
  }

  // 2. All turned pieces must be on the board anb be of the right color.
  QValueList<char>::iterator  it;
  for (it = move.m_turnedPieces.begin(); 
       it != move.m_turnedPieces.end(); 
       ++it) {
    int  sq = *it;

    if (m_board[sq / 10][sq % 10] != color) {
      //kdDebug() << "turned piece the board is wrong color: [" 
      //	<< sq / 10 << "," << sq % 10 << "]" << endl;
      return false;
    }
  }

  // Ok, everything seems allright.  Let's do it!
  // 1. Unturn all the turned pieces.
  for (it = move.m_turnedPieces.begin(); 
       it != move.m_turnedPieces.end(); 
       ++it) {
    int  sq = *it;

    m_board[sq / 10][sq % 10] = other;
    m_score.dec(color);
    m_score.inc(other);
  }

  // 2. Remove the move itself.
  m_score.dec(color);
  m_board[move.x()][move.y()] = Nobody;


  return true;
}


MoveList  Position::generateMoves(Color color) const
{
  MoveList  moves;

  // Make it simple: Step through all squares and see if it is a legal move.
  for (uint i = 1; i < 9; i++) {
    for (uint j = 1; j < 9; j++) {
      Move  move(color, i, j);

      if (moveIsLegal(move)) 
	moves.append(move);
    }
  }

  return moves;
}


QString Position::asString() const
{
  QString  result;

  for (uint y = 1; y < 9; ++y) {
    for (uint x = 1; x < 9; ++x) {
      switch (m_board[x][y]) {
      case Nobody:  result.append(' ');  break;
      case Black:   result.append('*');  break;
      case White:   result.append('o');  break;
      default:      result.append('?');  break;
      }
    }

    result.append('\n');
  }

  return result;
}