我正在尝试在网络程序集中创建一个游戏。我选择用 Rust 来准备它并使用 Cargo-Web 进行编译。我设法获得了一个有效的游戏循环,但由于 Rust 借用机制,我在添加 MouseDownEvent 侦听器时遇到了问题。我非常喜欢编写“安全”代码(不使用“不安全”关键字)
此时,游戏只需将红色框从 (0,0) 移动到 (700,500),速度取决于距离。我希望下一步使用用户单击更新目的地。
这是游戏的简化且有效的代码。
静态/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>The Game!</title>
</head>
<body>
<canvas id="canvas" width="600" height="600">
<script src="game.js"></script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
src/main.rs
mod game;
use game::Game;
use stdweb::console;
use stdweb::traits::*;
use stdweb::unstable::TryInto;
use stdweb::web::document;
use stdweb::web::CanvasRenderingContext2d;
use stdweb::web::html_element::CanvasElement;
use stdweb::web::event::MouseDownEvent;
fn main()
{
let canvas: CanvasElement = document()
.query_selector("#canvas")
.unwrap()
.unwrap()
.try_into()
.unwrap();
canvas.set_width(800u32);
canvas.set_height(600u32);
let context = canvas.get_context().unwrap();
let game: Game = Game::new();
// canvas.add_event_listener(|event: MouseDownEvent|
// { …Run Code Online (Sandbox Code Playgroud)