better error handling

This commit is contained in:
JOLIMAITRE Matthieu 2022-04-04 15:10:15 +03:00
parent 5fde51e81b
commit 22fab08702

View file

@ -1,7 +1,7 @@
use std::{error::Error, fmt::Display}; use std::{error::Error, fmt::Display};
use super::{ use super::{
controller::{Controller, Move, PlayerController}, controller::{Controller, ControllerError, Move, PlayerController},
grid::Grid, grid::Grid,
}; };
@ -34,20 +34,27 @@ impl Default for Rules {
} }
#[derive(Debug)] #[derive(Debug)]
pub enum Err2048 { pub enum GameError {
GridIsFull, GridIsFull,
ControllerError(ControllerError),
} }
impl Display for Err2048 { impl From<ControllerError> for GameError {
fn from(error: ControllerError) -> Self {
Self::ControllerError(error)
}
}
impl Display for GameError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let msg = match self { match self {
&Self::GridIsFull => "grid is full", Self::GridIsFull => f.write_str("grid is full"),
}; GameError::ControllerError(err) => err.fmt(f),
f.write_str(msg) }
} }
} }
impl Error for Err2048 {} impl Error for GameError {}
pub struct Game { pub struct Game {
board: Grid, board: Grid,
@ -70,7 +77,7 @@ impl Game {
} }
} }
pub fn turn(&mut self) -> Result<(), Box<dyn Error>> { pub fn turn(&mut self) -> Result<(), GameError> {
for _ in 0..self.spawn_per_turn { for _ in 0..self.spawn_per_turn {
self.spawn_random()?; self.spawn_random()?;
} }
@ -80,7 +87,7 @@ impl Game {
Ok(()) Ok(())
} }
pub fn spawn_random(&mut self) -> Result<(), Box<dyn Error>> { pub fn spawn_random(&mut self) -> Result<(), GameError> {
let mut potentials = vec![]; let mut potentials = vec![];
for x in 0..self.board.size() { for x in 0..self.board.size() {
for y in 0..self.board.size() { for y in 0..self.board.size() {
@ -91,7 +98,7 @@ impl Game {
} }
let potential_count = potentials.len() as f32; let potential_count = potentials.len() as f32;
if potential_count == 0. { if potential_count == 0. {
return Err(Err2048::GridIsFull.into()); return Err(GameError::GridIsFull.into());
} }
let random = rand::random::<f32>() * potential_count; let random = rand::random::<f32>() * potential_count;
let index = random.floor() as usize; let index = random.floor() as usize;