Home Web Front-end JS Tutorial Tic Tac Toe in Rust Webassembly

Tic Tac Toe in Rust Webassembly

Dec 18, 2024 pm 05:45 PM

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

Copy after login

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




Copy after login

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>



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


          

            
        
Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles