how do i code tic tac toe in rust
- User
how do i code tic tac toe in rust
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
how do i code tic tac toe in rust
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Sure, I'll walk you through how to code a simple Tic Tac Toe game in Rust! This will be a console-based version where two players take turns entering moves. I'll keep it straightforward, with step-by-step explanations, and provide complete code you can copy and run.
Tic Tac Toe is a 2-player game on a 3x3 grid. Players alternate placing X or O, and the game ends when someone wins or the board is full (a draw). In Rust, we'll use:
I'll provide a complete, working code example with comments. This version uses a simple numbered board for input (e.g., players enter 1-9 to pick a cell), which makes it easy to play in the terminal.
Here's the full Rust code for Tic Tac Toe. I'll break it down after the code.
use std::io; // For handling user input
#[derive(Clone, Copy, PartialEq)] // Enum for the two players
enum Player {
X,
O,
}
fn main() {
println!("Welcome to Tic Tac Toe!");
println!("Players take turns entering a number 1-9 to place their mark.");
println!(" 1 | 2 | 3 ");
println!("---|---|---");
println!(" 4 | 5 | 6 ");
println!("---|---|---");
println!(" 7 | 8 | 9 ");
let mut board = [[' '; 3]; 3]; // 3x3 grid, initialized with spaces
let mut current_player = Player::X; // Start with player X
let mut game_over = false; // Flag to end the game
let mut moves_made = 0; // Count moves to detect draw
while !game_over {
display_board(&board); // Show the current board
let move_result = get_player_move(&mut board, current_player); // Get and apply the move
if move_result.is_err() {
println!("Invalid move! Try again."); // Handle invalid input
continue; // Skip to the next iteration
}
moves_made += 1; // Increment move count
// Check for win or draw
if check_win(&board, current_player) {
display_board(&board); // Show final board
println!("Player {:?} wins!", current_player); // Announce winner
game_over = true;
} else if moves_made == 9 {
display_board(&board); // Show final board
println!("It's a draw!"); // No winner
game_over = true;
}
// Switch players
current_player = if current_player == Player::X { Player::O } else { Player::X };
}
println!("Game over. Thanks for playing!");
}
fn display_board(board: &[[char; 3]; 3]) {
println!("\nCurrent Board:");
for row in board.iter() {
println!(" {} | {} | {} ", row[0], row[1], row[2]);
println!("---|---|---");
}
}
fn get_player_move(board: &mut [[char; 3]; 3], player: Player) -> Result<(), String> {
println!("Player {:?}, enter your move (1-9):", player);
let mut input = String::new(); // String to store input
io::stdin().read_line(&mut input).expect("Failed to read input"); // Read from stdin
let input_trimmed = input.trim(); // Remove whitespace
let position: usize = input_trimmed.parse().map_err(|_| "Invalid input, not a number")?; // Parse to number
// Map the input (1-9) to board indices (0-2 for rows and columns)
let row = (position - 1) / 3;
let col = (position - 1) % 3;
// Check if the position is valid and empty
if position < 1 || position > 9 {
return Err("Position must be between 1 and 9".to_string());
}
if board[row][col] != ' ' {
return Err("Cell is already occupied".to_string());
}
// Place the player's mark
let mark = if player == Player::X { 'X' } else { 'O' };
board[row][col] = mark;
Ok(()) // Return success
}
fn check_win(board: &[[char; 3]; 3], player: Player) -> bool {
let mark = if player == Player::X { 'X' } else { 'O' }; // Get the mark for the player
// Check rows
for row in 0..3 {
if board[row][0] == mark && board[row][1] == mark && board[row][2] == mark {
return true;
}
}
// Check columns
for col in 0..3 {
if board[0][col] == mark && board[1][col] == mark && board[2][col] == mark {
return true;
}
}
// Check diagonals
if (board[0][0] == mark && board[1][1] == mark && board[2][2] == mark) ||
(board[0][2] == mark && board[1][1] == mark && board[2][0] == mark) {
return true;
}
false // No win
}
Player enum represents X and O.[[char; 3]; 3] (3 rows, each with 3 characters). We use char for the cells, initialized to spaces (' ') for empty.Save the Code: Create a new file named tic_tac_toe.rs and paste the code into it.
Compile and Run:
rustc tic_tac_toe.rs./tic_tac_toe (on Linux/Mac) or tic_tac_toe.exe (on Windows).Alternatively, use Cargo for better project management:
cargo new tic_tac_toesrc/main.rs with the code above.cargo run5 places a mark in the center.This is a basic version. Here are some ideas to make it more advanced:
colored), or even build a GUI with a library like egui.expect for simplicity, but in a real app, you'd want more robust error handling.If you'd like me to expand on any part (e.g., adding AI, refactoring, or debugging tips), just let me know! Rust is great for this kind of project because it's safe and performant. Have fun coding! 🎉