refactor, add lobby
This commit is contained in:
@@ -5,19 +5,6 @@ pub enum Cell {
|
||||
O,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Cell {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
let s: &str;
|
||||
match *self {
|
||||
Cell::X => s = "X",
|
||||
Cell::O => s = "O",
|
||||
Cell::Empty => s = " ",
|
||||
}
|
||||
|
||||
write!(f, "{}", s)
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Move {
|
||||
pub x: usize,
|
||||
pub y: usize,
|
||||
@@ -60,6 +47,10 @@ impl Board {
|
||||
}
|
||||
|
||||
pub fn is_valid_move(&self, m: &Move) -> bool {
|
||||
if m.x > 2 || m.y > 2 {
|
||||
return false;
|
||||
}
|
||||
|
||||
let i = m.x * 1 + m.y * 3;
|
||||
|
||||
m.piece == self.next && self.cells[i] == Cell::Empty
|
||||
@@ -107,42 +98,12 @@ impl Board {
|
||||
// no winner
|
||||
return None;
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Display for Board {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
||||
let mut s = String::new();
|
||||
pub fn cells(&self) -> Vec<Cell> {
|
||||
self.cells.clone()
|
||||
}
|
||||
|
||||
s.push_str(" 1 2 3 \n");
|
||||
|
||||
s.push_str(" ┌───┬───┬───┐\n");
|
||||
for i in 0..3 {
|
||||
match i {
|
||||
0 => s.push_str("a "),
|
||||
1 => s.push_str("b "),
|
||||
2 => s.push_str("c "),
|
||||
_ => {}
|
||||
}
|
||||
s.push_str(&format!(
|
||||
"│ {} │ {} │ {} │\n",
|
||||
self.cells[i * 3],
|
||||
self.cells[i * 3 + 1],
|
||||
self.cells[i * 3 + 2]
|
||||
));
|
||||
if i < 2 {
|
||||
s.push_str(" ├───┼───┼───┤\n");
|
||||
}
|
||||
}
|
||||
s.push_str(" └───┴───┴───┘\n");
|
||||
|
||||
match self.has_winner() {
|
||||
Some(w) => s.push_str(&format!("The winner is {w}")),
|
||||
None => match self.valid_moves_available() {
|
||||
true => s.push_str(&format!("Next: {}", self.next)),
|
||||
false => s.push_str("DRAW!"),
|
||||
},
|
||||
}
|
||||
|
||||
write!(f, "{s}")
|
||||
pub fn next_move(&self) -> Cell {
|
||||
self.next
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user