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

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Java and JavaScript are different programming languages, each suitable for different application scenarios. Java is used for large enterprise and mobile application development, while JavaScript is mainly used for web page development.

The following points should be noted when processing dates and time in JavaScript: 1. There are many ways to create Date objects. It is recommended to use ISO format strings to ensure compatibility; 2. Get and set time information can be obtained and set methods, and note that the month starts from 0; 3. Manually formatting dates requires strings, and third-party libraries can also be used; 4. It is recommended to use libraries that support time zones, such as Luxon. Mastering these key points can effectively avoid common mistakes.

PlacingtagsatthebottomofablogpostorwebpageservespracticalpurposesforSEO,userexperience,anddesign.1.IthelpswithSEObyallowingsearchenginestoaccesskeyword-relevanttagswithoutclutteringthemaincontent.2.Itimprovesuserexperiencebykeepingthefocusonthearticl

JavaScriptispreferredforwebdevelopment,whileJavaisbetterforlarge-scalebackendsystemsandAndroidapps.1)JavaScriptexcelsincreatinginteractivewebexperienceswithitsdynamicnatureandDOMmanipulation.2)Javaoffersstrongtypingandobject-orientedfeatures,idealfor

Event capture and bubble are two stages of event propagation in DOM. Capture is from the top layer to the target element, and bubble is from the target element to the top layer. 1. Event capture is implemented by setting the useCapture parameter of addEventListener to true; 2. Event bubble is the default behavior, useCapture is set to false or omitted; 3. Event propagation can be used to prevent event propagation; 4. Event bubbling supports event delegation to improve dynamic content processing efficiency; 5. Capture can be used to intercept events in advance, such as logging or error processing. Understanding these two phases helps to accurately control the timing and how JavaScript responds to user operations.

JavaScripthassevenfundamentaldatatypes:number,string,boolean,undefined,null,object,andsymbol.1)Numbersuseadouble-precisionformat,usefulforwidevaluerangesbutbecautiouswithfloating-pointarithmetic.2)Stringsareimmutable,useefficientconcatenationmethodsf

If JavaScript applications load slowly and have poor performance, the problem is that the payload is too large. Solutions include: 1. Use code splitting (CodeSplitting), split the large bundle into multiple small files through React.lazy() or build tools, and load it as needed to reduce the first download; 2. Remove unused code (TreeShaking), use the ES6 module mechanism to clear "dead code" to ensure that the introduced libraries support this feature; 3. Compress and merge resource files, enable Gzip/Brotli and Terser to compress JS, reasonably merge files and optimize static resources; 4. Replace heavy-duty dependencies and choose lightweight libraries such as day.js and fetch

The main difference between ES module and CommonJS is the loading method and usage scenario. 1.CommonJS is synchronously loaded, suitable for Node.js server-side environment; 2.ES module is asynchronously loaded, suitable for network environments such as browsers; 3. Syntax, ES module uses import/export and must be located in the top-level scope, while CommonJS uses require/module.exports, which can be called dynamically at runtime; 4.CommonJS is widely used in old versions of Node.js and libraries that rely on it such as Express, while ES modules are suitable for modern front-end frameworks and Node.jsv14; 5. Although it can be mixed, it can easily cause problems.
