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
// Copyright 2020 Zachary Stewart
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Implementation of the basic game of battleship with two players and five ships on a
//! 10x10 grid.
use std::{cmp::Ordering, ops::Deref};

use thiserror::Error;

pub use crate::board::rectangular::Coordinate;
use crate::{
    board::{self, rectangular::RectDimensions, BoardSetup},
    game::uniform,
    ships::{Line, ShapeProjection},
};

/// Alias to ShipRef with fixed generic types.
pub type ShipRef<'a> = board::ShipRef<'a, Ship, RectDimensions>;
/// Alias to CellRef with fixed generic types.
pub type CellRef<'a> = board::CellRef<'a, Ship, RectDimensions>;

/// Player ID for the simple game. Either `P1` or `P2`.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Player {
    P1,
    P2,
}

impl Player {
    /// Get the oponent of this player.
    pub fn opponent(self) -> Self {
        match self {
            Player::P1 => Player::P2,
            Player::P2 => Player::P1,
        }
    }
}

/// Ship ID for the simple game.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub enum Ship {
    /// Carrier: length 5.
    Carrier,
    /// Battleship: length 4.
    Battleship,
    /// Cruiser: length 3.
    Cruiser,
    /// Submarine: length 3.
    Submarine,
    /// Destroyer: length 2.
    Destroyer,
}

impl Ship {
    /// Get the shape cooresponding to this ship ID.
    fn get_shape(self) -> Line {
        Line::new(self.len())
    }

    /// Get a slice containing a list of all ships.
    pub const ALL: &'static [Ship] = &[
        Ship::Carrier,
        Ship::Battleship,
        Ship::Cruiser,
        Ship::Submarine,
        Ship::Destroyer,
    ];

    /// Get the length of this ship type.
    pub fn len(self) -> usize {
        match self {
            Ship::Carrier => 5,
            Ship::Battleship => 4,
            Ship::Cruiser => 3,
            Ship::Submarine => 3,
            Ship::Destroyer => 2,
        }
    }
}

/// Reason why a ship could not be placed at a given position.
#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
pub enum CannotPlaceReason {
    /// The ship did not fit in the given direction.
    #[error("insufficient space for the ship at the specified position")]
    InsufficientSpace,
    /// The ship was already placed.
    #[error("specified ship was already placed")]
    AlreadyPlaced,
    /// The space selected overlaps a ship that was already placed.
    #[error("the specified position was already occupied")]
    AlreadyOccupied,
}

/// Placement orientation of a ship.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Orientation {
    Up,
    Down,
    Left,
    Right,
}

impl Orientation {
    /// Check if the given projection is pointed along this orientation.
    fn check_dir(self, proj: &ShapeProjection<Coordinate>) -> bool {
        if proj.len() < 2 {
            // None of the current ships should have len 1, but support it here anyway.
            true
        } else {
            let dx = proj[0].x.cmp(&proj[1].x);
            let dy = proj[0].y.cmp(&proj[1].y);
            match (self, dx, dy) {
                (Orientation::Up, Ordering::Equal, Ordering::Greater) => true,
                (Orientation::Down, Ordering::Equal, Ordering::Less) => true,
                (Orientation::Left, Ordering::Greater, Ordering::Equal) => true,
                (Orientation::Right, Ordering::Less, Ordering::Equal) => true,
                _ => false,
            }
        }
    }
}

/// Represents a placement of a ship. Allows extracting the orientation and start, as well
/// as iterating the coordinates.
pub struct Placement([Coordinate]);

impl Placement {
    fn from_coords(coords: &[Coordinate]) -> &Placement {
        unsafe { std::mem::transmute(coords) }
    }

    pub fn orientation(&self) -> Orientation {
        if self.len() < 2 {
            // None of the current ships are less than 2 len, but we can handle it anyway.
            Orientation::Up
        } else {
            let dx = self[0].x.cmp(&self[1].x);
            let dy = self[0].y.cmp(&self[1].y);
            match (dx, dy) {
                (Ordering::Equal, Ordering::Greater) => Orientation::Up,
                (Ordering::Equal, Ordering::Less) => Orientation::Down,
                (Ordering::Greater, Ordering::Equal) => Orientation::Left,
                (Ordering::Less, Ordering::Equal) => Orientation::Right,
                // Shouldn't happen since we don't allow building paths that don't follow
                // these rules.
                _ => panic!("Coordinates don't point along a valid orientation"),
            }
        }
    }

    /// Get the coordinate where this placement starts.
    pub fn start(&self) -> &Coordinate {
        // This will panic if len is 0. That's OK because this type has no public
        // constructor and we know that within this module we never create placements with
        // 0 length.
        &self[0]
    }
}

impl Deref for Placement {
    type Target = [Coordinate];

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

/// Struct used to setup the simple game.
pub struct GameSetup(uniform::GameSetup<Player, Ship, RectDimensions, Line>);

impl GameSetup {
    /// Create a [`GameSetup`] for the game, including two players with one of each ship.
    pub fn new() -> Self {
        let mut setup = uniform::GameSetup::new();
        Self::add_ships(
            setup
                .add_player(Player::P1, RectDimensions::new(10, 10))
                .unwrap(),
        );
        Self::add_ships(
            setup
                .add_player(Player::P2, RectDimensions::new(10, 10))
                .unwrap(),
        );
        GameSetup(setup)
    }

    /// Add the initial ships for the player.
    fn add_ships(board: &mut BoardSetup<Ship, RectDimensions, Line>) {
        Self::add_ship(Ship::Carrier, board);
        Self::add_ship(Ship::Battleship, board);
        Self::add_ship(Ship::Cruiser, board);
        Self::add_ship(Ship::Submarine, board);
        Self::add_ship(Ship::Destroyer, board);
    }

    /// Add the given ship to the board.
    fn add_ship(ship: Ship, board: &mut BoardSetup<Ship, RectDimensions, Line>) {
        board.add_ship(ship, ship.get_shape()).unwrap();
    }

    /// Tries to start the game. If all players are ready, returns a [`Game`], otherwise
    /// returns self.
    pub fn start(self) -> Result<Game, Self> {
        match self.0.start() {
            Ok(game) => Ok(Game(game)),
            Err(setup) => Err(GameSetup(setup)),
        }
    }

    /// Return true if both players are ready to start the game.
    pub fn ready(&self) -> bool {
        self.0.ready()
    }

    /// Check if the specified player is ready.
    pub fn is_player_ready(&self, player: Player) -> bool {
        self.0.get_board(&player).unwrap().ready()
    }

    /// Get an iterator over all the ship IDs for the given player and the coordinates
    /// where that ship is placed, if any.
    pub fn get_ships<'a>(
        &'a self,
        player: Player,
    ) -> impl 'a + Iterator<Item = (Ship, Option<&'a Placement>)> {
        self.0.get_board(&player).unwrap().iter_ships().map(|ship| {
            (
                *ship.id(),
                ship.placement().map(|v| Placement::from_coords(v)),
            )
        })
    }

    /// Get the ships for the specified player which still need to be placed.
    pub fn get_pending_ships<'a>(&'a self, player: Player) -> impl 'a + Iterator<Item = Ship> {
        self.get_ships(player)
            .filter_map(|(ship, placement)| match placement {
                Some(_) => None,
                None => Some(ship),
            })
    }

    /// Get the the coordinates where the given ship is placed, if any.
    pub fn get_placement(&self, player: Player, ship: Ship) -> Option<&Placement> {
        self.0
            .get_board(&player)
            .unwrap()
            .get_ship(ship)
            .unwrap()
            .placement()
            .map(|v| Placement::from_coords(v))
    }

    /// Check if the given placement would be valid, without attempting to actually place
    /// the ship.
    pub fn check_placement(
        &self,
        player: Player,
        ship: Ship,
        start: Coordinate,
        dir: Orientation,
    ) -> Result<(), CannotPlaceReason> {
        let board = self.0.get_board(&player).unwrap();
        let ship = board.get_ship(ship).unwrap();
        let proj = ship
            .get_placements(start)
            .find(|proj| dir.check_dir(proj))
            .ok_or(CannotPlaceReason::InsufficientSpace)?;
        ship.check_placement(&proj).map_err(|err| match err {
            board::CannotPlaceReason::AlreadyOccupied => CannotPlaceReason::AlreadyOccupied,
            board::CannotPlaceReason::AlreadyPlaced => CannotPlaceReason::AlreadyPlaced,
            // We will never provide an invalid projection.
            board::CannotPlaceReason::InvalidProjection => unreachable!(),
        })
    }

    /// Try to place the specified ship at the specified position, returning an
    /// error if placement is not possible.
    pub fn place_ship(
        &mut self,
        player: Player,
        ship: Ship,
        start: Coordinate,
        dir: Orientation,
    ) -> Result<(), CannotPlaceReason> {
        let board = self.0.get_board_mut(&player).unwrap();
        let mut ship = board.get_ship_mut(ship).unwrap();
        let proj = ship
            .get_placements(start)
            .find(|proj| dir.check_dir(proj))
            .ok_or(CannotPlaceReason::InsufficientSpace)?;
        ship.place(proj).map_err(|err| match err.reason() {
            board::CannotPlaceReason::AlreadyOccupied => CannotPlaceReason::AlreadyOccupied,
            board::CannotPlaceReason::AlreadyPlaced => CannotPlaceReason::AlreadyPlaced,
            // We will never provide an invalid projection.
            board::CannotPlaceReason::InvalidProjection => unreachable!(),
        })
    }

    /// Clear the placement of the specified ship. Return true if the ship was previously
    /// placed.
    pub fn unplace_ship(&mut self, player: Player, ship: Ship) -> bool {
        self.0
            .get_board_mut(&player)
            .unwrap()
            .get_ship_mut(ship)
            .unwrap()
            .unplace()
            .is_some()
    }

    /// Get an iterator over the specified player's board. The iterator's item is another
    /// iterator that iterates over a single row.
    pub fn iter_board<'a>(
        &'a self,
        player: Player,
    ) -> impl 'a + Iterator<Item = impl 'a + Iterator<Item = Option<Ship>>> {
        let board = self.0.get_board(&player).unwrap();
        board
            .dimensions()
            .iter_coordinates()
            .map(move |row| row.map(move |coord| board.get_coord(&coord).copied()))
    }
}

/// Reason why a shot at the board failed.
#[derive(Debug, Error, Copy, Clone, Eq, PartialEq)]
pub enum CannotShootReason {
    /// The game is already over
    #[error("the game is already over")]
    AlreadyOver,

    /// The target player is the player whose turn it is.
    #[error("player attempted to shoot out of turn")]
    OutOfTurn,

    /// The specified cell is out of bounds for the grid.
    #[error("the target coordinate is out of bounds")]
    OutOfBounds,

    /// The specified cell has already been shot.
    #[error("the target cell was already shot")]
    AlreadyShot,
}

/// Outcome of a successfully-fired shot.
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum ShotOutcome {
    /// Nothing was hit.
    Miss,
    /// The given ship was hit but it was not sunk.
    Hit(Ship),
    /// The given ship was hit and it was sunk but the player still had other ships.
    Sunk(Ship),
    /// The given ship was hit and sunk, and the target player has no remaining ships.
    Victory(Ship),
}

/// Simplified game that uses a fixed set of ships and players.
pub struct Game(uniform::Game<Player, Ship, RectDimensions>);

impl Game {
    /// Get the player whose turn it currently is.
    pub fn current(&self) -> Player {
        *self.0.current()
    }

    /// Get the status of the game. Returns `None` if the game is in progress, otherwise
    /// returns the winner.
    pub fn winner(&self) -> Option<Player> {
        self.0.winner().copied()
    }

    /// Get an iterator over the specified player's board. The iterator's item is another
    /// iterator that iterates over a single row.
    pub fn iter_board<'a>(
        &'a self,
        player: Player,
    ) -> impl 'a + Iterator<Item = impl 'a + Iterator<Item = CellRef<'a>>> {
        let board = self.0.get_board(&player).unwrap();
        board
            .dimensions()
            .iter_coordinates()
            .map(move |row| row.map(move |coord| board.get_coord(coord).unwrap()))
    }

    /// Get an iterator over the specified player's ships.
    pub fn iter_ships<'a>(&'a self, player: Player) -> impl 'a + Iterator<Item = ShipRef<'a>> {
        self.0.get_board(&player).unwrap().iter_ships()
    }

    /// Get a reference to the cell with the specified coordinate in the specified
    /// player's board. Return None if the coord is out of bounds.
    pub fn get_coord(&self, player: Player, coord: Coordinate) -> Option<CellRef> {
        self.0.get_board(&player).unwrap().get_coord(coord)
    }

    /// Get a reference to the specified ship from the specified player's board.
    pub fn get_ship(&self, player: Player, ship: Ship) -> ShipRef {
        self.0.get_board(&player).unwrap().get_ship(&ship).unwrap()
    }

    /// Fire at the specified player on the specified coordinate.
    pub fn shoot(
        &mut self,
        target: Player,
        coord: Coordinate,
    ) -> Result<ShotOutcome, CannotShootReason> {
        self.0
            .shoot(target, coord)
            .map(|outcome| match outcome {
                uniform::ShotOutcome::Miss => ShotOutcome::Miss,
                uniform::ShotOutcome::Hit(ship) => ShotOutcome::Hit(ship),
                uniform::ShotOutcome::Sunk(ship) => ShotOutcome::Sunk(ship),
                // There are only two players so if one is defeated, we should go directly to
                // victory and never hit Defeated.
                uniform::ShotOutcome::Defeated(_) => unreachable!(),
                uniform::ShotOutcome::Victory(ship) => ShotOutcome::Victory(ship),
            })
            .map_err(|err| match err.reason() {
                uniform::CannotShootReason::AlreadyOver => CannotShootReason::AlreadyOver,
                uniform::CannotShootReason::SelfShot => CannotShootReason::OutOfTurn,
                // There are always exactly two players, so player will never be unknown.
                uniform::CannotShootReason::UnknownPlayer => unreachable!(),
                // Since there are only 2 players, if one is defeated, the reason will be
                // AlreadyOver not AlreadyDefeated
                uniform::CannotShootReason::AlreadyDefeated => unreachable!(),
                uniform::CannotShootReason::OutOfBounds => CannotShootReason::OutOfBounds,
                uniform::CannotShootReason::AlreadyShot => CannotShootReason::AlreadyShot,
            })
    }
}

#[cfg(feature = "rng_gen")]
mod rand_impl {
    use super::{Orientation, Player};
    use once_cell::sync::Lazy;
    use rand::{
        distributions::{Distribution, Standard, Uniform},
        Rng,
    };

    /// Uniform sampler to use to get values for player selection.
    static PLAYER_SAMPLER: Lazy<Uniform<u8>> = Lazy::new(|| Uniform::new(0, 2));

    impl Distribution<Player> for Standard {
        fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Player {
            match rng.sample(&*PLAYER_SAMPLER) {
                0 => Player::P1,
                _ => Player::P2,
            }
        }
    }

    /// Uniform sampler to use to get values for orientation selection.
    static ORIENTATION_SAMPLER: Lazy<Uniform<u8>> = Lazy::new(|| Uniform::new(0, 4));

    impl Distribution<Orientation> for Standard {
        fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Orientation {
            match rng.sample(&*ORIENTATION_SAMPLER) {
                0 => Orientation::Up,
                1 => Orientation::Down,
                2 => Orientation::Left,
                _ => Orientation::Right,
            }
        }
    }
}