Select Git revision
CHANGELOG.md
-
Benoît Harrault authoredBenoît Harrault authored
To find the state of this project's repository at the time of any of these versions, check out the tags.
game_board.dart 6.63 KiB
// Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
enum PieceType {
empty,
black,
white,
}
/// This method flips a black piece to a white one, and vice versa. I'm still
/// unsure about having it as a global function, but don't know where else to
/// put it.
PieceType getOpponent(PieceType player) =>
(player == PieceType.black) ? PieceType.white : PieceType.black;
/// A position on the reversi board. Just an [x] and [y] coordinate pair.
class Position {
final int x;
final int y;
const Position(this.x, this.y);
}
/// An immutable representation of a reversi game's board.
class GameBoard {
static const int height = 8;
static const int width = 8;
final List<List<PieceType>> rows;
// Because calculating out all the available moves for a player can be
// expensive, they're cached here.
final _availableMoveCache = <PieceType, List<Position>>{};
/// Default constructor, which creates a board with pieces in starting
/// position.
GameBoard() : rows = _emptyBoard;
/// Copy constructor.
GameBoard.fromGameBoard(GameBoard other)
: rows = List.generate(height, (i) => List.from(other.rows[i]));
/// Retrieves the type of piece at a location on the game board.
PieceType getPieceAtLocation(int x, int y) {
assert(x >= 0 && x < width);
assert(y >= 0 && y < height);
return rows[y][x];
}
/// Gets the total number of pieces of a particular type.
int getPieceCount(PieceType pieceType) {
return rows.fold(
0,
(s, e) => s + e.where((e) => e == pieceType).length,
);
}
/// Calculates the list of available moves on this board for a player. These
/// moves are calculated for the first call and cached for any subsequent
/// ones.
List<Position> getMovesForPlayer(PieceType player) {
if (player == PieceType.empty) {
return [];
}
if (_availableMoveCache.containsKey(player)) {
return _availableMoveCache[player]!;
}
final legalMoves = <Position>[];