diff options
Diffstat (limited to 'src/game_loop.rs')
-rw-r--r-- | src/game_loop.rs | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/src/game_loop.rs b/src/game_loop.rs new file mode 100644 index 0000000..34dd477 --- /dev/null +++ b/src/game_loop.rs @@ -0,0 +1,31 @@ +use std::cell::RefCell; +use std::rc::Rc; + +use wasm_bindgen::prelude::Closure; +use wasm_bindgen::JsCast; + +use crate::game::Game; + +pub fn run(game: Game, update_period: i32) { + game.render(); + + let f = Rc::new(RefCell::new(None)); + let g = f.clone(); + + *g.borrow_mut() = Some(Closure::wrap(Box::new(move |_| { + + game.update(); + game.render(); + + set_timeout(f.borrow().as_ref().unwrap(), update_period); + + }) as Box<dyn FnMut(i32)>)); + + set_timeout(g.borrow().as_ref().unwrap(), update_period); +} + +fn set_timeout(f: &Closure<dyn FnMut(i32)>, timeout: i32) { + web_sys::window().unwrap() + .set_timeout_with_callback_and_timeout_and_arguments_0(f.as_ref().unchecked_ref(), timeout) + .unwrap(); +} |