wip impl tic-tac-toe
This commit is contained in:
parent
71d89ed8c4
commit
fa76804ed7
7
Cargo.lock
generated
Normal file
7
Cargo.lock
generated
Normal file
|
|
@ -0,0 +1,7 @@
|
|||
# This file is automatically @generated by Cargo.
|
||||
# It is not intended for manual editing.
|
||||
version = 4
|
||||
|
||||
[[package]]
|
||||
name = "tictactoe-rust-foropenspiel"
|
||||
version = "0.1.0"
|
||||
91
src/game.rs
Normal file
91
src/game.rs
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
use std::{fmt, str};
|
||||
|
||||
// ------------- Player
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Player {
|
||||
Player0,
|
||||
Player1,
|
||||
}
|
||||
|
||||
impl From<u8> for Player {
|
||||
fn from(item: u8) -> Self {
|
||||
match item {
|
||||
0 => Player::Player0,
|
||||
1 => Player::Player1,
|
||||
_ => Player::Player0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Player> for u8 {
|
||||
fn from(player: Player) -> u8 {
|
||||
match player {
|
||||
Player::Player0 => 0,
|
||||
Player::Player1 => 1,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl fmt::Display for Player {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let repr = match (self) {
|
||||
Player::Player0 => "x",
|
||||
Player::Player1 => "o",
|
||||
};
|
||||
let mut s = String::new();
|
||||
s.push_str(repr);
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------- CellState
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum CellState {
|
||||
Cross,
|
||||
Nought,
|
||||
Empty,
|
||||
}
|
||||
|
||||
impl From<Player> for CellState {
|
||||
fn from(player: Player) -> CellState {
|
||||
match player {
|
||||
Player::Player0 => CellState::Cross,
|
||||
Player::Player1 => CellState::Nought,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
impl fmt::Display for CellState {
|
||||
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
|
||||
let repr = match (self) {
|
||||
CellState::Cross => "x",
|
||||
CellState::Nought => "o",
|
||||
CellState::Empty => ".",
|
||||
};
|
||||
let mut s = String::new();
|
||||
s.push_str(repr);
|
||||
write!(f, "{s}")
|
||||
}
|
||||
}
|
||||
|
||||
// ------------ Board
|
||||
|
||||
type Board = Vec<CellState>;
|
||||
|
||||
impl Board {
|
||||
fn hasLine(&self, Player player) -> bool {
|
||||
let c: CellState = player.into();
|
||||
(self[0] == c && self[1] == c && self[2] == c) ||
|
||||
(self[3] == c && self[4] == c && self[5] == c) ||
|
||||
(self[6] == c && self[7] == c && self[8] == c) ||
|
||||
(self[0] == c && self[3] == c && self[6] == c) ||
|
||||
(self[1] == c && self[4] == c && self[7] == c) ||
|
||||
(self[2] == c && self[5] == c && self[8] == c) ||
|
||||
(self[0] == c && self[4] == c && self[8] == c) ||
|
||||
(self[2] == c && self[4] == c && self[6] == c);
|
||||
}
|
||||
|
||||
}
|
||||
Loading…
Reference in a new issue