-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathlib.rs
83 lines (70 loc) · 1.85 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
mod utils;
use wasm_bindgen::prelude::wasm_bindgen;
use web_sys::Element;
// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
#[wasm_bindgen]
pub fn init() {
utils::set_panic_hook();
let apples = 1;
let trees = 0;
let window = web_sys::window().unwrap();
let document = window.document().unwrap();
let main = document.get_elements_by_tag_name("main").item(0).unwrap();
let dynamic_text: Element = document.create_element("p").unwrap();
main.prepend_with_node_1(&dynamic_text).unwrap();
let game_state = GameState {
dynamic_text,
apples,
trees,
};
let game = nuts::new_activity(game_state);
game.subscribe(GameState::update_text);
game.subscribe(GameState::buy);
game.subscribe(GameState::collect_apples);
nuts::publish(UpdateTextEvent);
set_timer();
}
struct GameState {
dynamic_text: Element,
apples: i32,
trees: i32,
}
struct UpdateTextEvent;
struct BuyEvent;
struct CollectEvent;
#[wasm_bindgen]
pub fn buy() {
nuts::publish(BuyEvent);
}
impl GameState {
fn update_text(&mut self, _: &UpdateTextEvent) {
self.dynamic_text.set_inner_html(&format!(
"You have {} apples and {} trees.",
self.apples, self.trees
));
}
fn buy(&mut self, _: &BuyEvent) {
if self.apples > 0 {
self.trees += 1;
self.apples -= 1;
nuts::publish(UpdateTextEvent);
}
}
fn collect_apples(&mut self, _: &CollectEvent) {
self.apples += self.trees;
nuts::publish(UpdateTextEvent);
}
}
use stdweb::js;
fn set_timer() {
js! {
setInterval(
@{||nuts::publish(CollectEvent)},
5000
)
}
}