From 74489c43b602f07e680dc3f7774e4cb8670d659b Mon Sep 17 00:00:00 2001 From: Simon Gardling Date: Mon, 3 Feb 2025 20:03:38 -0500 Subject: [PATCH] cleanup --- Cargo.toml | 2 +- src/agent.rs | 2 +- src/board.rs | 41 +++++++++++++++-------------------------- 3 files changed, 17 insertions(+), 28 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 99c751b..e844640 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -4,4 +4,4 @@ version = "0.1.0" edition = "2021" [dependencies] -num = "0.4.3" +num = "0.4" diff --git a/src/agent.rs b/src/agent.rs index f6c404f..15b5ee9 100644 --- a/src/agent.rs +++ b/src/agent.rs @@ -22,7 +22,7 @@ impl Agent for ManualAgent { stdin.lock().read_line(&mut input).ok()?; let numbers = input .split_whitespace() - .map(|i| usize::from_str_radix(i, 10).ok()) + .map(|i| i.parse::().ok()) .collect::>>(); if let Some(numbers) = numbers { if numbers.len() == 2 { diff --git a/src/board.rs b/src/board.rs index e06f6d9..054ae79 100644 --- a/src/board.rs +++ b/src/board.rs @@ -1,5 +1,5 @@ use crate::{misc::split_from, piece::Piece}; -use std::fmt; +use std::{cmp::Ordering, fmt}; pub const BOARD_SIZE: usize = 8; @@ -185,38 +185,27 @@ impl Board { captured } - // keep score of each color + /// Returns (White score, Black score) pub fn get_score(&self) -> (usize, usize) { - let mut white_score = 0; - let mut black_score = 0; - - for row in &self.board { - for &cell in row { - match cell { - Some(Piece::White) => white_score += 1, - Some(Piece::Black) => black_score += 1, - _ => {} - } - } - } - (white_score, black_score) + self.board + .iter() + .flatten() + .flatten() + .map(|cell| match cell { + Piece::White => (1, 0), + Piece::Black => (0, 1), + }) + .fold((0_usize, 0usize), |(a, b), (c, d)| (a + c, b + d)) } // Get the winning piece (for game over screen mainly) pub fn get_winner(&self) -> Option { let (white_score, black_score) = self.get_score(); - // White wins - if white_score > black_score { - Some(Piece::White) - } - // Black Wins - else if black_score > white_score { - Some(Piece::Black) - } - // Tie - else { - None + match white_score.cmp(&black_score) { + Ordering::Greater => Some(Piece::White), // White win + Ordering::Less => Some(Piece::Black), // Black win + Ordering::Equal => None, // Tie } }