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
use std::collections::VecDeque;
use std::collections::BTreeSet;
use std::str::FromStr;
use std::fmt;
use std::mem;

use piece::Stone;
use piece::Piece;
use piece::Player;
use board::Board;
use board::PieceIter;
use board::PieceCount;
use board::board_from_str;
use board::str_from_board;
use point::Point;
use turn::Direction;

#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struct Square {
    pub pieces: Vec<Piece>,
}

impl Square {
    pub fn new() -> Square {
        Square { pieces: vec![] }
    }

    pub fn len(&self) -> usize {
        self.pieces.len()
    }

    pub fn add_piece(&mut self, piece: Piece) -> Result<(), String> {
        match self.pieces.last_mut() {
            Some(base) => try!(piece.move_onto(base)),
            None => {}
        }
        self.pieces.push(piece);
        Ok(())
    }

    fn place_piece(&mut self, piece: Piece) -> Result<(), &str> {
        if self.len() != 0 {
            return Err("Cannot place stone on top of existing stone.");
        }
        self.pieces.push(piece);
        Ok(())
    }

    // Used for moving stones eligibility
    pub fn mover(&self) -> Option<Player> {
        self.pieces.last().map(|piece| piece.owner())
    }

    // Used for road wins
    pub fn owner(&self) -> Option<Player> {
        self.pieces.last().and_then(|piece|
            if piece.stone() == Stone::Standing {
                None
            } else {
                Some(piece.owner())
            })
    }

    // Used for winning the flats
    pub fn scorer(&self) -> Option<Player> {
        self.pieces.last().and_then(|piece|
            if piece.stone() == Stone::Flat {
                Some(piece.owner())
            } else {
                None
            })
    }
}

#[derive(Clone, Debug, RustcDecodable, RustcEncodable)]
pub struct NaiveBoard {
    grid: Vec<Vec<Square>>,
    count: PieceCount,
}

impl NaiveBoard {
    fn at_mut(&mut self, point: &Point) -> Result<&mut Square, &str> {
        let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point"));
        row.get_mut(point.x).ok_or("Invalid point")
    }
}

impl Board for NaiveBoard {
    fn new(board_size: usize) -> NaiveBoard {
        assert!(board_size >= 4 && board_size <= 8);
        NaiveBoard {
            grid: vec![vec![Square::new(); board_size]; board_size],
            count: PieceCount::new(board_size),
        }
    }

    fn at(&self, point: &Point) -> Result<PieceIter, &str> {
        let row = try!(self.grid.get(point.y).ok_or("Invalid point"));
        let cell = try!(row.get(point.x).ok_or("Invalid point"));
        Ok(PieceIter::NaiveBoardIter {
            square: cell.pieces.clone(),
            index: 0,
        })
    }

    fn at_reset(&mut self, point: &Point) -> Result<PieceIter, &str> {
        let row = try!(self.grid.get_mut(point.y).ok_or("Invalid point"));
        let square = try!(row.get_mut(point.x).ok_or("Invalid point"));
        Ok(PieceIter::NaiveBoardIter {
            square: mem::replace(square, Square::new()).pieces,
            index: 0,
        })
    }

    fn size(&self) -> usize {
        self.grid.len()
    }

    fn place_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> {
        {
            let square = try!(self.at_mut(point));
            try!(square.place_piece(piece));
        }
        self.count.add(&piece);
        Ok(())
    }

    fn add_piece(&mut self, point: &Point, piece: Piece) -> Result<(), String> {
        {
            let square = try!(self.at_mut(point));
            try!(square.add_piece(piece));
        }
        Ok(())
    }

    fn count(&self) -> PieceCount {
        self.count
    }

    fn follow(&self,
              starts: &mut VecDeque<Point>,
              player: Player)
              -> BTreeSet<Point> {
        let mut connected = BTreeSet::new();
        let mut visited = BTreeSet::new();

        while let Some(start) = starts.pop_front() {
            visited.insert(start);
            if self.at(&start).ok().and_then(|p| p.owner()) == Some(player) {
                connected.insert(start);
                for point in Direction::neighbors(&start, self.size()) {
                    if !visited.contains(&point) {
                        starts.push_back(point)
                    }
                }
            }
        }
        connected
    }
}

impl FromStr for NaiveBoard {
    type Err=();
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        board_from_str::<NaiveBoard>(s)
    }
}

impl fmt::Display for NaiveBoard {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        str_from_board(self, f)
    }
}