Hello everyone I'm going to show you how to create a simple Tic-Tac-Toe game in Rust with Webassembly.
First you need to install Rust you can do that by visiting official site (https://www.rust-lang.org/tools/install)
Then in Windows open a terminal or Powershell and make sure to run it as administrator and type the following command to create needed files and folders for your Rust game cargo new the name you want for the folder
after that navigate to your folder location using file explorer inside src folder which will be created you will find main.rs file right click and rename it to lib.rs
While you're there you can right click the file to open it in an editor of your choice you can use notepad++ which could be downloaded from (https://notepad-plus-plus.org/downloads/) and here is the code you need for lib.rs file:
use wasm_bindgen::prelude::*;
use serde::Serialize;
#[wasm_bindgen]
pub struct TicTacToe {
board: Vec<String>,
current_player: String,
game_over: bool,
winner: Option<String>,
}
#[derive(Serialize)]
struct GameState {
board: Vec<String>,
current_player: String,
game_over: bool,
winner: Option<String>,
}
#[wasm_bindgen]
impl TicTacToe {
#[wasm_bindgen(constructor)]
pub fn new() -> TicTacToe {
TicTacToe {
board: vec!["".to_string(); 9],
current_player: "X".to_string(),
game_over: false,
winner: None,
}
}
/// Handles a player's turn and returns the updated game state as a JSON string.
pub fn play_turn(&mut self, index: usize) -> String {
if self.game_over || !self.board[index].is_empty() {
return self.get_state();
}
self.board[index] = self.current_player.clone();
if self.check_winner() {
self.game_over = true;
self.winner = Some(self.current_player.clone());
} else if !self.board.contains(&"".to_string()) {
self.game_over = true; // Draw
} else {
self.current_player = if self.current_player == "X" {
"O".to_string()
} else {
"X".to_string()
};
}
self.get_state()
}
/// Resets the game to its initial state and returns the game state as a JSON string.
pub fn reset(&mut self) -> String {
self.board = vec!["".to_string(); 9];
self.current_player = "X".to_string();
self.game_over = false;
self.winner = None;
self.get_state()
}
/// Returns the current game state as a JSON string.
pub fn get_state(&self) -> String {
let state = GameState {
board: self.board.clone(),
current_player: self.current_player.clone(),
game_over: self.game_over,
winner: self.winner.clone(),
};
serde_json::to_string(&state).unwrap()
}
fn check_winner(&self) -> bool {
let win_patterns = [
[0, 1, 2], [3, 4, 5], [6, 7, 8], // Rows
[0, 3, 6], [1, 4, 7], [2, 5, 8], // Columns
[0, 4, 8], [2, 4, 6], // Diagonals
];
win_patterns.iter().any(|&line| {
let [a, b, c] = line;
!self.board[a].is_empty()
&& self.board[a] == self.board[b]
&& self.board[b] == self.board[c]
})
}
}
After make sure to save it and then navigate to your main folder and this time right click and edit Cargo.toml file and paste this code in it right at the end of [package] code:
[dependencies]
wasm-bindgen = "0.2" # Enables Wasm interop
serde = { version = "1.0", features = ["derive"] } # For serialization/deserialization
serde_json = "1.0" # Optional, if you use JSON in your app
[lib]
crate-type = ["cdylib"] # Required for WebAssembly
[features]
default = ["wee_alloc"]
[profile.release]
opt-level = "z" # Optimize for size, which is ideal for WebAssembly.
[dependencies.wee_alloc]
version = "0.4.5" # Optional, for smaller Wasm binary size
optional = true
[dev-dependencies]
wasm-bindgen-test = "0.3" # Optional, for testing in Wasm
Then save it as well and this time we need to get back to our terminal or Powershell and go to your main folder that you created with cargo command at the beginning and make sure you are inside your main folder by typing cd then your folder name
then type this command to create web files and folders needed:
wasm-pack build --target web
After that step you will notice that Webassembly has created more files and folders inside your main folder needed to run Rust code on the web, at this point from file explorer go to your main folder then create a new file by right click anywhere at the empty space inside the main folder that you created with cargo new command and click new then text document rename the new file index.html and open it in code editor in this case for example notepad++ just right click it and choose edit with notepad then paste this HTML code in it:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tic Tac Toe</title>
<style>
body {
font-family: 'Arial', sans-serif;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
min-height: 100vh;
margin: 0;
background: linear-gradient(to bottom right, #6a11cb, #2575fc);
color: white;
}
h1 {
font-size: 2.5rem;
margin-bottom: 10px;
text-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
}
#status {
font-size: 1.25rem;
margin-bottom: 20px;
padding: 10px;
background: rgba(0, 0, 0, 0.2);
border-radius: 8px;
}
#board {
display: grid;
grid-template-columns: repeat(3, 100px);
gap: 10px;
}
.cell {
width: 100px;
height: 100px;
background: rgba(255, 255, 255, 0.2);
border: 2px solid rgba(255, 255, 255, 0.5);
border-radius: 10px;
display: flex;
align-items: center;
justify-content: center;
font-size: 2rem;
font-weight: bold;
color: white;
box-shadow: 2px 2px 8px rgba(0, 0, 0, 0.3);
transition: transform 0.2s, background 0.3s;
cursor: pointer;
}
.cell.taken {
cursor: not-allowed;
background: rgba(255, 255, 255, 0.5);
color: black;
}
.cell:hover:not(.taken) {
transform: scale(1.1);
background: rgba(255, 255, 255, 0.4);
}
#reset {
margin-top: 20px;
padding: 10px 30px;
font-size: 1.25rem;
font-weight: bold;
color: #6a11cb;
background: white;
border: none;
border-radius: 5px;
box-shadow: 2px 2px 5px rgba(0, 0, 0, 0.3);
cursor: pointer;
transition: background 0.3s, transform 0.2s;
}
#reset:hover {
background: #f0f0f0;
transform: scale(1.05);
}
#reset:active {
transform: scale(0.95);
}
footer {
margin-top: 20px;
font-size: 0.9rem;
opacity: 1.0;
}
</style>
</head>
<body>
<h1>Tic Tac Toe</h1>
<div id="status">Loading game...</div>
<div id="board"></div>
<button id="reset">Reset Game</button>
<footer>Built with ❤️ using Rust and WebAssembly</footer>
<script type="module">
import init, { TicTacToe } from './pkg/tac.js';
async function run() {
await init();
const game = new TicTacToe();
const boardElement = document.getElementById('board');
const statusElement = document.getElementById('status');
const resetButton = document.getElementById('reset');
function render() {
const state = JSON.parse(game.get_state());
boardElement.innerHTML = '';
state.board.forEach((cell, index) => {
const cellElement = document.createElement('div');
cellElement.className = 'cell' + (cell ? ' taken' : '');
cellElement.textContent = cell;
if (!cell) {
cellElement.addEventListener('click', () => {
game.play_turn(index);
render();
});
}
boardElement.appendChild(cellElement);
});
if (state.game_over) {
statusElement.textContent = state.winner
? `${state.winner} wins! 🎉`
: 'It\'s a draw! ✨';
} else {
statusElement.textContent = `Current turn: ${state.current_player}`;
}
}
resetButton.addEventListener('click', () => {
game.reset();
render();
});
render();
}
run();
</script>
</body>
</html>
Just make sure in this line of code import init, { TicTacToe } from './pkg/type the name of javascript file located in pkg folder inside your main folder.js';
inside your main folder wasm command created a folder named "pkg" inside it you will find a javascript file ends in .js extension just make sure to type the name correctly in that line of code to point to it, save it and close the file.
Now your web application game is ready to launch, just one last thing we need to create a web server to host it in this case just get back to terminal windows or Powershell and navigate to your folder path make sure you're inside the folder using cd
command and initiate the server by typing this command python -m http.server
to install python follow this link (https://www.python.org/downloads/windows/).
Now open a web browser page and type in the address field
http://localhost:8000/
or http://127.0.0.1:8000
to play the game.
I hope you enjoy it and apologies for the long post.
Thank you so much. Enjoy!.
Top comments (0)