how do i code tic tac toe in rust
- User
how do i code tic tac toe in rust
Assistant
Tic Tac Toe in Rust
Here's a fully functional implementation of Tic Tac Toe in Rust. This version includes:
- A 3x3 grid
- Alternating turns for
XandO - Input validation
- Win/draw detection
Code:
use std::io; const SIZE: usize = 3; // The game board struct Board { cells: [[char; SIZE]; SIZE], } impl Board { fn new() -> Self { Board { cells: [[' '; SIZE]; SIZE], } } // Print the current state of the board fn display(&self) { for row in 0..SIZE { for col in 0..SIZE { print!(" {} ", self.cells[row][col]); if col < SIZE - 1 { print!("|"); } } println!(); if row < SIZE - 1 { println!("---+---+---"); } } } // Check if a move is valid (empty cell) fn is_valid_move(&self, row: usize, col: usize) -> bool { self.cells[row][col] == ' ' } // Make a move (place 'X' or 'O') fn make_move(&mut self, row: usize, col: usize, player: char) { self.cells[row][col] = player; } // Check for a win fn check_win(&self, player: char) -> bool { // Rows for row in 0..SIZE { if self.cells[row][0] == player && self.cells[row][1] == player && self.cells[row][2] == player { return true; } } // Columns for col in 0..SIZE { if self.cells[0][col] == player && self.cells[1][col] == player && self.cells[2][col] == player { return true; } } // Diagonals if (self.cells[0][0] == player && self.cells[1][1] == player && self.cells[2][2] == player) || (self.cells[0][2] == player && self.cells[1][1] == player && self.cells[2][0] == player) { return true; } false } // Check if the board is full (draw) fn is_full(&self) -> bool { self.cells.iter().flatten().all(|&c| c != ' ') } } fn get_user_input(prompt: &str) -> usize { loop { println!("{}", prompt); let mut input = String::new(); io::stdin().read_line(&mut input).expect("Failed to read line"); let input: usize = match input.trim().parse() { Ok(num) => num, Err(_) => { println!("Invalid input. Please enter a number."); continue; } }; if input >= 1 && input <= 3 { return input - 1; // 0-based index } else { println!("Out of bounds. Enter 1, 2, or 3."); } } } fn main() { let mut board = Board::new(); let mut current_player = 'X'; loop { // Display the board board.display(); // Get player move println!("Player {}, enter row (1-3):", current_player); let row = get_user_input("Enter row (1-3):"); let col = get_user_input("Enter column (1-3):"); // Validate move if !board.is_valid_move(row, col) { println!("Invalid move! Cell already occupied."); continue; } // Make the move board.make_move(row, col, current_player); // Check for win if board.check_win(current_player) { board.display(); println!("Player {} WINS!", current_player); break; } // Check for draw if board.is_full() { board.display(); println!("It's a DRAW!"); break; } // Switch player current_player = if current_player == 'X' { 'O' } else { 'X' }; } }How it works:
Boardstruct: Represents the 3x3 grid.display: Prints the current state of the board.is_valid_move: Checks if a cell is empty.make_move: PlacesXorOin a cell.check_win: Verifies rows, columns, and diagonals for a win.is_full: Checks if all cells are filled (draw).get_user_input: Handles user input (row/col).mainloop:- Displays the board.
- Asks the current player for input.
- Validates and makes the move.
- Checks for win/draw.
- Switches player (
X<->O).
Run the code:
- Save this file as
tic_tac_toe.rs. - Compile and run:
Or with Cargo:rustc tic_tac_toe.rs ./tic_tac_toecargo new tic_tac_toe cd tic_tac_toe # Replace src/main.rs with the above code cargo run
Example Gameplay:
1 | 2 | 3 ---+---+--- 4 | 5 | 6 ---+---+--- 7 | 8 | 9 Player X, enter row (1-3): 1 Enter column (1-3): 1 X | | ---+---+--- | | ---+---+--- | | Player O, enter row (1-3): 2 Enter column (1-3): 2 X | | ---+---+--- | O | ---+---+--- | | # Keep playing until someone wins or it's a draw!Happy coding! Let me know if you need any improvements (like AI opponents 😄).
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.