Tic-tac-toe in rust
xxxxxxxxxx
pub fn tic_tac_toe(table: Vec<Vec<&str>>) -> String {
let player_x: &str = "X";
let player_o: &str = "O";
let mut player_x_won = false;
let mut player_o_won = false;
if horizontal(player_x, &table) || vertical(player_x, &table) || diagonals(player_x, &table) {
player_x_won = true;
}
if horizontal(player_o, &table) || vertical(player_o, &table) || diagonals(player_o, &table) {
player_o_won = true;
}
if player_o_won && player_x_won {
return "tie".to_string();
} else if player_x_won {
return "player X won".to_string();
} else if player_o_won {
return "player O won".to_string();
}
return "tie".to_string();
}
// "player O won"
pub fn diagonals(player: &str, table: &Vec<Vec<&str>>) -> bool {
table[0][0] == player && table[1][1] == player && table[2][2] == player || table [0][2] == player && table[1][1] == player && table[2][0] == player
// let len: usize = table.len();
// let mut count_diag1 = 0;
// let mut count_diag2 = 0;
// for i in 0..len {
// // Check top-left to bottom-right diagonal
// if table[i][i] == player {
// count_diag1 += 1;
// }
// // Check top-right to bottom-left diagonal
// if table[i][len - 1 - i] == player {
// count_diag2 += 1;
// }
// }
// count_diag1 == len || count_diag2 == len
}
pub fn horizontal(player: &str, table: &Vec<Vec<&str>>) -> bool {
// Check if the player has a winning horizontal line.
// iterate through the rows of the table and using nested loop to check if all the elements in the row match the player.
for row in table {
let mut count = 0;
for &cell in row {
// Increment if cell equals to player
if cell == player {
count += 1;
}
}
// Return true if row is complete.
if count == row.len() {
return true;
}
}
false
}
pub fn vertical(player: &str, table: &Vec<Vec<&str>>) -> bool {
let len: usize = table.len();
for col in 0..len {
let mut count = 0;
for row in 0..len {
// Access the element at (row, col)
let cell = table[row][col];
if cell == player {
count += 1;
}
}
// return true if row is complete.
if count == len {
return true;
}
}
false
}