use crate::game::BoardDimensions;
use crate::game::Cell;
use crate::game::GameError;
use crate::game::LINE_LENGTH;
use crate::game::Placement;
use crate::game::Player;
use crate::game::Status;
use crate::game::Victory;
use std::fmt;
use tudi::Bounded;
use tudi::Coordinate;
use tudi::Grid;
use tudi::GridError;
const LINE_STEPS: [Step; 4] = [
Step::new(1, 0),
Step::new(0, 1),
Step::new(1, 1),
Step::new(1, -1),
];
#[derive(Debug)]
pub struct GameState {
grid: Grid<Player>,
current_player: Player,
status: Status,
}
impl GameState {
pub fn new() -> Self {
Self::with_dimensions(BoardDimensions::STANDARD)
}
pub fn with_dimensions(dimensions: BoardDimensions) -> Self {
Self {
grid: Grid::new(dimensions.column_count(), dimensions.row_count()),
current_player: Player::FIRST,
status: Status::InProgress,
}
}
pub fn dimensions(&self) -> BoardDimensions {
BoardDimensions::from_counts(self.column_count(), self.row_count())
}
pub fn column_count(&self) -> usize {
self.grid.x_count()
}
pub fn row_count(&self) -> usize {
self.grid.y_count()
}
pub const fn current_player(&self) -> Player {
self.current_player
}
pub const fn status(&self) -> &Status {
&self.status
}
pub const fn is_over(&self) -> bool {
self.status.is_over()
}
pub const fn winner(&self) -> Option<Player> {
self.status.winner()
}
pub fn disc_count(&self) -> usize {
self.grid.iter_elements_new().count()
}
pub fn is_full(&self) -> bool {
self.disc_count() == self.dimensions().cell_count()
}
pub fn piece_at(&self, cell: Cell) -> Option<Player> {
let coordinate = self.coordinate_of(cell)?;
self.player_at(coordinate)
}
pub fn is_playable(&self, column: usize) -> bool {
!self.is_over() && self.landing_coordinate(column).is_ok()
}
pub fn legal_moves(&self) -> Vec<usize> {
(0..self.column_count())
.filter(|column| self.is_playable(*column))
.collect()
}
pub fn landing_cell(&self, column: usize) -> Option<Cell> {
if self.is_over() {
return None;
}
let coordinate = self.landing_coordinate(column).ok()?;
self.cell_of(coordinate)
}
pub fn apply_move(&mut self, column: usize) -> Result<Placement, GameError> {
if self.is_over() {
return Err(GameError::GameOver);
}
let landing = self.landing_coordinate(column)?;
let player = self.current_player;
self.store(landing, player)?;
let cell = self.cell_of(landing).ok_or(GameError::Board {
reason: String::from("the disc landed outside the board"),
})?;
self.status = self.status_after(landing, player);
if !self.is_over() {
self.current_player = player.opponent();
}
Ok(Placement::new(player, cell))
}
fn landing_coordinate(&self, column: usize) -> Result<Coordinate, GameError> {
let mut candidate = Coordinate {
x: self.column_to_x(column)?,
y: self.grid.y_min_boundary(),
};
loop {
match self.grid.element(&candidate) {
Ok(_) => candidate.y += 1,
Err(GridError::UnoccupiedError(_)) => return Ok(candidate),
Err(GridError::OutOfBoundsError(_)) => {
return Err(GameError::ColumnFull { column });
}
Err(error) => {
return Err(GameError::Board {
reason: error.to_string(),
});
}
}
}
}
fn store(&mut self, coordinate: Coordinate, player: Player) -> Result<(), GameError> {
self.grid
.store_element(&coordinate, player)
.map(|_| ())
.map_err(|error| GameError::Board {
reason: error.to_string(),
})
}
fn status_after(&self, coordinate: Coordinate, player: Player) -> Status {
if let Some(line) = self.winning_line_through(coordinate, player) {
Status::Won(Victory::new(player, line))
} else if self.is_full() {
Status::Draw
} else {
Status::InProgress
}
}
fn winning_line_through(&self, coordinate: Coordinate, player: Player) -> Option<Vec<Cell>> {
LINE_STEPS.iter().find_map(|step| {
let line = self.line_through(coordinate, *step, player);
(line.len() >= LINE_LENGTH).then_some(line)
})
}
fn line_through(&self, coordinate: Coordinate, step: Step, player: Player) -> Vec<Cell> {
let mut current = self.far_end(coordinate, step.reversed(), player);
let mut line = Vec::new();
while self.player_at(current) == Some(player) {
if let Some(cell) = self.cell_of(current) {
line.push(cell);
}
current = step.applied_to(current);
}
line
}
fn far_end(&self, from: Coordinate, step: Step, player: Player) -> Coordinate {
let mut current = from;
while self.player_at(step.applied_to(current)) == Some(player) {
current = step.applied_to(current);
}
current
}
fn player_at(&self, coordinate: Coordinate) -> Option<Player> {
self.grid.element(&coordinate).ok().copied()
}
fn column_to_x(&self, column: usize) -> Result<i32, GameError> {
let offset = i32::try_from(column)
.ok()
.filter(|_| column < self.column_count());
offset
.map(|offset| self.grid.x_min_boundary() + offset)
.ok_or(GameError::ColumnOutOfRange {
column,
column_count: self.column_count(),
})
}
fn coordinate_of(&self, cell: Cell) -> Option<Coordinate> {
if cell.column >= self.column_count() || cell.row >= self.row_count() {
return None;
}
Some(Coordinate {
x: self.grid.x_min_boundary() + i32::try_from(cell.column).ok()?,
y: self.grid.y_min_boundary() + i32::try_from(cell.row).ok()?,
})
}
fn cells(&self) -> impl Iterator<Item = Cell> {
let column_count = self.column_count();
(0..self.row_count())
.rev()
.flat_map(move |row| (0..column_count).map(move |column| Cell::new(column, row)))
}
fn cell_of(&self, coordinate: Coordinate) -> Option<Cell> {
let column = usize::try_from(coordinate.x - self.grid.x_min_boundary()).ok()?;
let row = usize::try_from(coordinate.y - self.grid.y_min_boundary()).ok()?;
let is_on_board = column < self.column_count() && row < self.row_count();
is_on_board.then_some(Cell::new(column, row))
}
}
impl Default for GameState {
fn default() -> Self {
Self::new()
}
}
impl Clone for GameState {
fn clone(&self) -> Self {
let mut clone = Self::with_dimensions(self.dimensions());
for (coordinate, player) in self.grid.iter_elements_new() {
let stored = clone.grid.store_element(&coordinate, *player);
debug_assert!(stored.is_ok(), "a clone has the bounds of its original");
}
clone.current_player = self.current_player;
clone.status = self.status.clone();
clone
}
}
impl PartialEq for GameState {
fn eq(&self, other: &Self) -> bool {
self.dimensions() == other.dimensions()
&& self.current_player == other.current_player
&& self.status == other.status
&& self
.cells()
.all(|cell| self.piece_at(cell) == other.piece_at(cell))
}
}
impl Eq for GameState {}
impl fmt::Display for GameState {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
for (written, row) in (0..self.row_count()).rev().enumerate() {
if written > 0 {
formatter.write_str("\n")?;
}
for column in 0..self.column_count() {
let symbol = self
.piece_at(Cell::new(column, row))
.map_or('.', Player::token);
write!(formatter, "{symbol}")?;
}
}
Ok(())
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
struct Step {
x: i32,
y: i32,
}
impl Step {
const fn new(x: i32, y: i32) -> Self {
Self { x, y }
}
const fn reversed(self) -> Self {
Self::new(-self.x, -self.y)
}
const fn applied_to(self, coordinate: Coordinate) -> Coordinate {
Coordinate {
x: coordinate.x + self.x,
y: coordinate.y + self.y,
}
}
}