Created
January 1, 2023 18:20
-
-
Save wjurkowlaniec/9cf995d2dc8df236e3db0e655039f71e to your computer and use it in GitHub Desktop.
first blood with Rust
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::io::{self, BufRead}; | |
use std::process::exit; | |
const PLAYER_SYMBOL: [&str; 2] = ["X", "O"]; | |
fn main() { | |
let mut board: [[&str; 3]; 3] = [[" ", " ", " "], [" ", " ", " "], [" ", " ", " "]]; | |
let mut current_player: usize = 0; | |
let mut moves_count: u8 = 0; | |
loop { | |
get_player_input(&mut board, current_player); | |
moves_count += 1; | |
print_board(board); | |
if current_player_won(board, PLAYER_SYMBOL[current_player]) { | |
println!("Player {} won!", PLAYER_SYMBOL[current_player]); | |
break; | |
} | |
if moves_count == 9 { | |
println!("Nobody won"); | |
break; | |
} | |
if current_player == 1 { | |
current_player = 0; | |
} else { | |
current_player = 1; | |
}; | |
} | |
exit(0); | |
} | |
fn current_player_won(board: [[&str; 3]; 3], current_player: &str) -> bool { | |
// horizontal | |
for i in 0..3 { | |
if board[i][0] == current_player | |
&& board[i][1] == current_player | |
&& board[i][2] == current_player | |
{ | |
return true; | |
} | |
} | |
// vertical | |
for i in 0..3 { | |
if board[0][i] == current_player | |
&& board[1][i] == current_player | |
&& board[2][i] == current_player | |
{ | |
return true; | |
} | |
} | |
// diagonal | |
if board[0][0] == current_player | |
&& board[1][1] == current_player | |
&& board[2][2] == current_player | |
{ | |
return true; | |
} | |
if board[0][2] == current_player | |
&& board[1][1] == current_player | |
&& board[2][0] == current_player | |
{ | |
return true; | |
} | |
return false; | |
} | |
fn get_player_input(board: &mut [[&str; 3]; 3], current_player: usize) { | |
loop { | |
let mut x: usize = 100; | |
let mut y: usize = 100; | |
println!("Enter coordinates (ex. 2,3): "); | |
let stdin = io::stdin(); | |
let line: String = stdin.lock().lines().next().unwrap().unwrap(); | |
let coordinates: Vec<&str> = line.split(",").collect(); | |
if coordinates.len() == 2 { | |
x = coordinates[0].parse::<usize>().unwrap_or(100); | |
y = coordinates[1].parse::<usize>().unwrap_or(100); | |
} | |
if x < 4 && x > 0 && y < 4 && y > 0 { | |
if board[x - 1][y - 1] == " " { | |
board[x - 1][y - 1] = PLAYER_SYMBOL[current_player]; | |
return; | |
} | |
} | |
println!("Wrong input, try again"); | |
} | |
} | |
fn print_board(board: [[&str; 3]; 3]) { | |
for i in 0..3 { | |
println!("{}", board[i].join("|")); | |
if i < 2 { | |
println!("-----"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment