aboutsummaryrefslogtreecommitdiff
path: root/src/board.rs
blob: 484c31a65cd64c7a4b94f76dc1d3653e357c7e0a (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
use std::fmt;

// #[derive(Clone, Copy)]
pub struct Position {
    pub x: u8,
    pub y: u8,
}
impl fmt::Display for Position {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{:x}{}", 10 + self.x, self.y)
    }
}

#[derive(PartialEq)]
pub enum Player {
    Black,
    White,
}

impl fmt::Display for Player {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Player::Black => "B",
                Player::White => "W",
            }
        )
    }
}

#[derive(PartialEq)]
pub enum Stone {
    Flat,
    Standing,
    Capstone,
}

impl fmt::Display for Stone {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Stone::Flat => "",
                Stone::Standing => "S",
                Stone::Capstone => "C",
            }
        )
    }
}

// #[derive(Clone, Copy)]
pub enum Direction {
    Up,
    Down,
    Left,
    Right,
}

impl fmt::Display for Direction {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(
            f,
            "{}",
            match self {
                Direction::Up => "+",
                Direction::Down => "-",
                Direction::Left => "<",
                Direction::Right => ">",
            }
        )
    }
}

pub enum Action {
    Place(Player, Position, Stone),
    Move(Player, Position, Direction, Vec<u8>),
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Action::Place(player, pos, stone) => write!(f, "{}{}{}", pos, player, stone),
            Action::Move(_, pos, direction, drops) => write!(
                f,
                "{}{}{}",
                pos,
                direction,
                drops.into_iter().map(|q| q.to_string()).collect::<String>()
            ),
        }
    }
}

type Stack = Vec<(Player, Stone)>;

pub struct Board {
    size: u8,
    black_flats: u8,
    white_flats: u8,
    black_capstones: u8,
    white_capstones: u8,
    board: Vec<Stack>,
}

// How to solve code duplication between is_legal_action and
// perform_action?

// TODO: Generate all legal actions for a given player

pub type Logger = fn(String);

impl Board {
    fn remaining_pieces(&self, player: &Player, stone: &Stone) -> u8 {
        match player {
            Player::Black => {
                if *stone == Stone::Capstone {
                    self.black_capstones
                } else {
                    self.black_flats
                }
            }
            Player::White => {
                if *stone == Stone::Capstone {
                    self.white_capstones
                } else {
                    self.white_flats
                }
            }
        }
    }

    fn within_bounds(&self, pos: &Position) -> bool {
        if (pos.x < self.size) && (pos.y < self.size) {
            true
        } else {
            false
        }
    }

    fn lookup_square(&self, pos: &Position) -> Option<&Stack> {
        let y: usize = pos.y as usize;
        let x: usize = pos.x as usize;
        self.board.get(x + y * (self.size as usize))
    }

    fn is_legal_place(&self, player: &Player, pos: &Position, stone: &Stone, log: Logger) -> bool {
        /* In order to legally place a piece:
        1. The desired square must be empty
        2. The player must have sufficient pieces
         */
        if self.within_bounds(pos) {
            match self.lookup_square(pos) {
                Some(stack) => {
                    if stack.len() > 0 {
                        log(format!("{} is already occupied.", pos));
                        false
                    } else if self.remaining_pieces(player, stone) == 0 {
                        log(format!(
                            "{} has no more remaining {} pieces.",
                            player, stone
                        ));
                        false
                    } else {
                        true
                    }
                }
                None => {
                    log(format!("Internal error, lookup for {} failed.", pos));
                    false
                }
            }
        } else {
            log(format!("Position {} is not within bounds.", pos));
            false
        }
    }

    fn is_legal_move(
        &self,
        player: &Player,
        pos: &Position,
        direction: &Direction,
        drops: &Vec<u8>,
        log: Logger,
    ) -> bool {
        if self.within_bounds(pos) {
            match self.lookup_square(pos) {
                /* Rules for moving a stack:
                0. There are stones
                1. Top stone belongs to player
                2. Zero or One stones dropped on starting square
                3. Total number of stones moved does not exceed the carry capacity
                4. Direction does not contain a capstone
                5. Wall may only appear on last spot if it's capstone alone that covers
                6. All stones are used up before then end of the board is met
                 */
                Some(stack) => {
                    if stack.len() == 0 {
                        log(format!("{} has no stones to move.", pos));
                        false
                    } else if drops.len() == 0 {
                        log(format!("A drop sequence for must be specified for a move."));
                        false
                    } else if stack[0].0 != *player {
                        log(format!(
                            "{} may not move the stack at {} as it belongs to {}.",
                            player, pos, stack[0].0
                        ));
                        false
                    } else if drops[0] > 1 {
                        log(format!(
                            "A move may only drop 0 or 1 stones at it's origin square."
                        ));
                        false
                    // Do the sum in u32 just in case ?
                    } else if drops.iter().map(|&d| d as u32).sum::<u32>() > self.size as u32 {
                        log(format!(
                            "A move may not exceed the carry limit of {} stones.",
                            self.size
                        ));
                        false
                    } else {
                        let mut steps: usize = drops.len() - 1;
                        let cap: bool = stack[0].1 == Stone::Capstone;
                        let mut pos_new = Position { x: pos.x, y: pos.y };
                        let mut result = true;
                        while steps > 0 {
                            if {
                                match direction {
                                    Direction::Up => pos_new.y + 1 >= self.size,
                                    Direction::Down => pos_new.y == 0,
                                    Direction::Left => pos_new.x + 1 >= self.size,
                                    Direction::Right => pos_new.x == 0,
                                }
                            } {
                                log(format!("A move may not extend past the board."));
                                result = false;
                                break;
                            } else {
                                match direction {
                                    Direction::Up => pos_new.y += 1,
                                    Direction::Down => pos_new.y -= 1,
                                    Direction::Left => pos_new.x += 1,
                                    Direction::Right => pos_new.x -= 1,
                                }
                                match self.lookup_square(&pos_new) {
                                    Some(stack) => {
                                        if stack.len() > 0 {
                                            match stack[0].1 {
                                                Stone::Capstone => {
                                                    log(format!(
                                                        "A move may not cover a capstone."
                                                    ));
                                                    result = false;
                                                    break;
                                                }
                                                Stone::Standing => {
                                                    if (steps > 1) || (!cap) {
                                                        log(format!(
                                                        "A move may not cover a standing stone."
                                                    ));
                                                        result = false;
                                                        break;
                                                    }
                                                }
                                                Stone::Flat => (),
                                            }
                                        }
                                    }
                                    None => {
                                        log(format!("Internal error, lookup for {} failed.", pos));
                                        result = false;
                                        break;
                                    }
                                }
                            }
                            steps -= 1;
                        }
                        result
                    }
                }
                None => {
                    log(format!("Internal error, lookup for {} failed.", pos));
                    false
                }
            }
        } else {
            log(format!("Position {} is not within bounds.", pos));
            false
        }
    }

    fn is_legal_action(&self, mov: &Action, log: Logger) -> bool {
        match mov {
            Action::Place(player, pos, stone) => self.is_legal_place(player, pos, stone, log),
            Action::Move(player, pos, direction, drops) => false,
        }
    }
}