Rust - 将事件侦听器添加到网络组装游戏中



我正在尝试在 Web 程序集中创建游戏。我选择在 rust 中准备它并使用 cargo-web 编译它。我设法获得了一个有效的游戏循环,但由于锈蚀借用机制,我在添加 MouseDownEvent 侦听器时遇到了问题。我非常愿意编写"安全"代码(不使用"不安全"关键字)

此时,游戏只是根据距离将红色框从 (0,0) 移动到 (700,500)。我希望下一步使用用户单击更新目标。

这是游戏的简化和工作代码。

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

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|
// {
//     game.destination.x = (event.client_x() as f64);
//     game.destination.y = (event.client_y() as f64);
// });
game_loop(game, context, 0f64);
}

fn game_loop(mut game : Game, context : CanvasRenderingContext2d, timestamp : f64)
{
game.cycle(timestamp);
draw(&game,&context);
stdweb::web::window().request_animation_frame( |time : f64| { game_loop(game, context, time); } );
}

fn draw(game : &Game, context: &CanvasRenderingContext2d)
{
context.clear_rect(0f64,0f64,800f64,800f64);
context.set_fill_style_color("red");
context.fill_rect(game.location.x, game.location.y, 5f64, 5f64);
}

src/game.rs

pub struct Point
{
pub x: f64,
pub y: f64,
}
pub struct Game
{
pub time: f64,
pub location: Point,
pub destination: Point,
}
impl Game
{
pub fn new() -> Game
{
let game = Game
{   
time: 0f64,
location: Point{x: 0f64, y: 0f64},
destination: Point{x: 700f64, y: 500f64},
};
return game;
}
pub fn cycle(&mut self, timestamp : f64)
{
if timestamp - self.time > 10f64
{
self.location.x += (self.destination.x - self.location.x) / 10f64; 
self.location.y += (self.destination.y - self.location.y) / 10f64;
self.time = timestamp;
}
}
}

main.rs 注释掉的部分是我尝试添加MouseDownEvent侦听器。不幸的是,它会产生编译错误:

error[E0505]: cannot move out of `game` because it is borrowed
--> srcmain.rs:37:15
|
31 |       canvas.add_event_listener(|event: MouseDownEvent|
|       -                         ----------------------- borrow of `game` occurs here
|  _____|
| |
32 | |     {
33 | |         game.destination.x = (event.client_x() as f64);
| |         ---- borrow occurs due to use in closure
34 | |         game.destination.y = (event.client_y() as f64);
35 | |     });
| |______- argument requires that `game` is borrowed for `'static`
36 |
37 |       game_loop(game, context, 0f64);
|                 ^^^^ move out of `game` occurs here

我非常想知道如何正确实现一种将用户输入读取到游戏中的方法。它不需要是异步的。

我认为在这种情况下编译器错误消息非常清楚。您正在尝试在'static生命周期中借用关闭中的game,然后您还试图移动game。这是不允许的。我建议再读一遍《The Rust Programming Language》一书。专注于第 4 章 - 了解所有权。

为了缩短它,您的问题归结为类似 -如何共享可以变异的状态。有很多方法可以实现这一目标,但这实际上取决于您的需求(单线程或多线程等)。我将使用RcRefCell来解决这个问题。

Rc(std::rc):

类型Rc<T>提供在堆中分配的T类型的值的共享所有权。在Rc上调用clone会生成指向堆中相同值的新指针。当指向给定值的最后一个Rc指针被销毁时,指向的值也会被销毁。

RefCell(std::cell):

Cell<T>RefCell<T>类型的值可以通过共享引用(即公共&T类型)来改变,而大多数 Rust 类型只能通过唯一的(&mut T)引用来改变。我们说Cell<T>RefCell<T>提供"内部可变性",与表现出"遗传可变性"的典型 Rust 类型相反。

这是我对你的结构所做的:

struct Inner {
time: f64,
location: Point,
destination: Point,
}
#[derive(Clone)]
pub struct Game {
inner: Rc<RefCell<Inner>>,
}

这是什么意思?Inner保存游戏状态(与旧Game相同的字段)。新Game只有一个字段inner,其中包含共享状态。

  • Rc<T>(在这种情况下TRefCell<Inner>) - 允许我多次克隆inner,但它不会克隆T
  • RefCell<T>(在这种情况下TInner) - 允许我以不变或可变的方式借用T,检查是在运行时完成的

我现在可以多次克隆Game结构,它不会克隆RefCell<Inner>,只会克隆GameRc。这就是enclose!宏在更新main.rs中所做的:

let game: Game = Game::default();
canvas.add_event_listener(enclose!( (game) move |event: MouseDownEvent| {
game.set_destination(event);
}));
game_loop(game, context, 0.);

如果没有enclose!宏:

let game: Game = Game::default();
// game_for_mouse_down_event_closure holds the reference to the
// same `RefCell<Inner>` as the initial `game`
let game_for_mouse_down_event_closure = game.clone();
canvas.add_event_listener(move |event: MouseDownEvent| {
game_for_mouse_down_event_closure.set_destination(event);
});
game_loop(game, context, 0.);

更新game.rs

use std::{cell::RefCell, rc::Rc};
use stdweb::traits::IMouseEvent;
use stdweb::web::event::MouseDownEvent;
#[derive(Clone, Copy)]
pub struct Point {
pub x: f64,
pub y: f64,
}
impl From<MouseDownEvent> for Point {
fn from(e: MouseDownEvent) -> Self {
Self {
x: e.client_x() as f64,
y: e.client_y() as f64,
}
}
}
struct Inner {
time: f64,
location: Point,
destination: Point,
}
impl Default for Inner {
fn default() -> Self {
Inner {
time: 0.,
location: Point { x: 0., y: 0. },
destination: Point { x: 700., y: 500. },
}
}
}
#[derive(Clone)]
pub struct Game {
inner: Rc<RefCell<Inner>>,
}
impl Default for Game {
fn default() -> Self {
Game {
inner: Rc::new(RefCell::new(Inner::default())),
}
}
}
impl Game {
pub fn update(&self, timestamp: f64) {
let mut inner = self.inner.borrow_mut();
if timestamp - inner.time > 10f64 {
inner.location.x += (inner.destination.x - inner.location.x) / 10f64;
inner.location.y += (inner.destination.y - inner.location.y) / 10f64;
inner.time = timestamp;
}
}
pub fn set_destination<T: Into<Point>>(&self, location: T) {
let mut inner = self.inner.borrow_mut();
inner.destination = location.into();
}
pub fn location(&self) -> Point {
self.inner.borrow().location
}
}

更新main.rs

use stdweb::traits::*;
use stdweb::unstable::TryInto;
use stdweb::web::document;
use stdweb::web::event::MouseDownEvent;
use stdweb::web::html_element::CanvasElement;
use stdweb::web::CanvasRenderingContext2d;
use game::Game;
mod game;
// https://github.com/koute/stdweb/blob/master/examples/todomvc/src/main.rs#L31-L39
macro_rules! enclose {
( ($( $x:ident ),*) $y:expr ) => {
{
$(let $x = $x.clone();)*
$y
}
};
}
fn game_loop(game: Game, context: CanvasRenderingContext2d, timestamp: f64) {
game.update(timestamp);
draw(&game, &context);
stdweb::web::window().request_animation_frame(|time: f64| {
game_loop(game, context, time);
});
}
fn draw(game: &Game, context: &CanvasRenderingContext2d) {
context.clear_rect(0., 0., 800., 800.);
context.set_fill_style_color("red");
let location = game.location();
context.fill_rect(location.x, location.y, 5., 5.);
}
fn main() {
let canvas: CanvasElement = document()
.query_selector("#canvas")
.unwrap()
.unwrap()
.try_into()
.unwrap();
canvas.set_width(800);
canvas.set_height(600);
let context = canvas.get_context().unwrap();
let game: Game = Game::default();
canvas.add_event_listener(enclose!( (game) move |event: MouseDownEvent| {
game.set_destination(event);
}));
game_loop(game, context, 0.);
}

附言在将来共享任何代码之前,请安装并使用 rustfmt。

在您的示例中,game_loop拥有game,因为它被移动到循环中。所以任何应该改变游戏的事情都需要发生在game_loop内部。若要将事件处理融入其中,您有多种选择:

选项 1

game_loop轮询事件。

您创建一个事件队列,您的game_loop将有一些逻辑来获取第一个事件并处理它。

您将不得不在这里处理同步,因此我建议您阅读一般的互斥和并发。但是,一旦掌握了窍门,这应该是一件相当容易的任务。您的循环获得一个引用,每个事件处理程序获得一个,所有这些都尝试解锁互斥锁,然后访问队列(可能是向量)。

这将使您的game_loop成为其中唯一的真理,这是一种流行的引擎设计,因为它很容易推理和开始。

但也许你想不那么集中。

选项 2

让事件在循环之外发生

这个想法将是一个更大的重构。你会把你的Game放在一个lazy_static里,周围有一个互斥体。

每次调用game_loop,它都会尝试锁定所述互斥体,然后执行游戏计算。

当输入事件发生时,该事件还会尝试在Game上获取互斥体。这意味着在game_loop处理时,不会处理任何输入事件,但它们会尝试在即时报价之间进入。

这里的一个挑战是保持输入顺序并确保输入处理得足够快。要完全正确,这可能是一个更大的挑战。但是设计会给你一些可能性。

这个想法的充实版本是Amethyst,它是大规模平行的,使设计干净。但他们在发动机后面采用了更复杂的设计。

最新更新