Rust: Tic Tac Toe Game With Minimax Algorithm

TicTacToe game with Rust and Minimax Algorithm

Hello fellow developers! πŸ‘‹ I always have been interested in learning Rust due to all the hype around it. I believe the best way to learn a new programming language is to build something with it. Since Rust is known to have low-level performance, I want to create a simple terminal-based game which is Tic Tac Toe with Minimax Algorithm for the AI opponent. Let’s develop the game.

Quick Demo

TicTacToe with Minimax built with Rust

Initialize Rust Project

Let’s create a Rust project with Cargo, the official package manager of Rust. Execute this command below.

cargo new rust-tictactoe
cd rust-tictactoe

Add Dependencies

We only use one dependency for this project which is tabled to print a nice table for our TicTacToe board. Open Cargo.toml and add the dependency.

Board Functions

First, We will focus on functions to create, update and print the TicTacToe board on the terminal. Copy-paste the codes below to main.rs.

Let’s test the functions by running the project with Cargo.

cargo run
TicTacToe board functions

Game State Functions

Next, We create functions to check the game states if there is a winner or if it is a draw. Copy-paste the codes below to main.rs.

Let’s test the functions by running the project with Cargo.

cargo run
Rust TicTacToe game state functions

User Input Functions

Next, We create functions to get user input for the X or O character and the user’s move. Copy-paste the codes below to main.rs.

Let’s test the functions by running the project with Cargo.

cargo run
Rust TicTacToe user input functions

AI and Minimax Functions

Next, We create functions to create the AI opponent with Minimax Algorithm. Copy-paste the codes below to main.rs.

Let’s test the functions by running the project with Cargo.

cargo run
Rust TicTacToe AI minimax functions

The Game Flow

Now all of our functions are ready and we can combine those functions to create the TicTacToe game flow. Copy-paste the codes below to the main function.

Let’s test the functions by running the project with Cargo.

cargo run
Rust TicTacToe with AI minimax completed

Congratulation! We build a TicTacToe game with an unbeatable AI opponent using Rust. πŸŽ‰

It’s my first Rust project so the source code can be messy. If you to help me to improve the source code, here’s my Github repo: https://github.com/arisnacg/rust-tictactoe

Happy Coding 🍻

--

--