Experimenting Further

Rogue WebAssembly is far from perfect. There are plenty of areas for improvement: we can clean up the code, refactor methods, and make different choices with regard to the allocation of responsibilities between WebAssembly and JavaScript.

Before moving on to the next chapter, it might be worth your time to make some changes to the game. Experiment with moving more logic and state into the Rust code to try to keep the outer index.js as small as possible. What other features do you think would make the game more interesting? Try giving players the ability to fight each other by adding support for it in the PlayerCore Rust struct. Given the Rot.js scheduler system, can you add more NPCs (Non-Player Characters) to the game?

Your end result might not be a best-selling AAA-grade game, but playing around with this framework, experimenting with new things, and, most importantly, breaking it and trying to fix it, will give you invaluable muscle memory when it comes to writing Rust code and troubleshooting WebAssembly applications.

Using the js_sys Crate

At the top of the lib.rs file you wrote for the game, there are some externs declared that map to existing JavaScript functions, namely alert and console.log. It would get very tedious very quickly if you wanted your Rust code to have access to more native JavaScript functions and you had to manually write each one of those extern bindings.

Thankfully you don’t have to write those bindings yourself. The work has already been done for you in the js_sys[22] crate. This crate, which is part of wasm-bindgen, contains all of the mappings you need to global JavaScript functions. Instead of manually defining the binding for alert like you did in this chapter, you can simply call js_sys::alert. Not only has all this work been done for you, but it saves you the trouble of figuring out exactly how to map the data types and parameters.

In the process of improving your copy of Rogue WebAssembly, go through and see if there are spots where you might be able to clean up the Rust or JavaScript code by making js_sys calls.

But wait, there’s more! For the low price of nothing, you also get access to the web_sys crate! This crate has all of the JavaScript Web API bindings[23] in it. Your rust code can make web_sys calls and, at runtime, the JavaScript host will make web API calls on your behalf. Hopefully, at this point, you’re starting to think that you have supervillain-like powers at your fingertips and you’re feeling inspired to build your next world domination strategy in WebAssembly and Rust.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.70.248