search
HomeWeb Front-endJS TutorialTic Tac Toe in Rust Webassembly

Tic Tac Toe in Rust   Webassembly

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]
        })
    }
}

</string></string></string></string>

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:



    <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>


    <h1 id="Tic-Tac-Toe">Tic Tac Toe</h1>
    <div>



<p>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.</p>

<p>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/).</p>

<p>Now open a web browser page and type in the address field <br>
http://localhost:8000/ or http://127.0.0.1:8000  to play the game.</p>

<p>I hope you enjoy it and apologies for the long post.</p>

<p>Thank you so much. Enjoy!.</p>


          </div>

            
        

The above is the detailed content of Tic Tac Toe in Rust Webassembly. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment