Skip to content

Commit 2cc1673

Browse files
committed
Refactor
1 parent b2200a9 commit 2cc1673

File tree

3 files changed

+49
-25
lines changed

3 files changed

+49
-25
lines changed

examples/wasm/Cargo.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@ keymap = { path = "../../", default-features = false, features = ["wasm", "deriv
1414
keymap_parser = { path = "../../keymap_parser" }
1515
wasm-bindgen = "0.2"
1616
wasm-bindgen-futures = "0.4"
17-
web-sys = { version = "0.3", features = ["KeyboardEvent", "console", "Window", "Document", "HtmlElement", "KeyboardEventInit"] }
17+
web-sys = { version = "0.3", features = ["KeyboardEvent", "Window", "Document", "HtmlElement", "KeyboardEventInit"] }
1818
serde = { version = "1.0", features = ["derive"] }
1919
toml = "0.8"
2020

examples/wasm/game.js

Lines changed: 36 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
// Configuration constants
22
const CONFIG = {
3-
GROUND_HEIGHT: 20,
3+
GROUND_HEIGHT: 22,
44
PLAYER: {
55
WIDTH: 80,
66
HEIGHT: 40,
@@ -460,6 +460,7 @@ class Game {
460460
this.gameSpeed = CONFIG.GAME.INITIAL_SPEED;
461461
this.gameOver = false;
462462
this.paused = false;
463+
this.key = "";
463464

464465
// Delta time approach instead of frame limiting
465466
this.lastTime = 0;
@@ -475,15 +476,7 @@ class Game {
475476
canvas.focus();
476477

477478
UI.restartButton.addEventListener("click", () => this.reset());
478-
UI.shareButton.addEventListener("click", () => this.share());
479-
}
480-
481-
share() {
482-
const text = `I scored ${this.score} in Nyan Jump! Try to beat me!`;
483-
const hashtags = "keymap-rs,rust,wasm";
484-
const url = `https://x.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(window.location)}&hashtags=${hashtags}`;
485-
486-
window.open(url, "_blank");
479+
UI.shareButton.addEventListener("click", () => share(this.score));
487480
}
488481

489482
reset() {
@@ -498,6 +491,7 @@ class Game {
498491
this.gameSpeed = CONFIG.GAME.INITIAL_SPEED;
499492
this.gameOver = false;
500493
this.paused = false;
494+
this.key = "";
501495
this._hideGameOverUI();
502496
this.accumulator = 0; // Ensure game logic runs on first frame after reset
503497

@@ -508,6 +502,13 @@ class Game {
508502
});
509503
}
510504

505+
setKey(key, desc) {
506+
this.key = [key, desc]
507+
.filter(Boolean)
508+
.map((s) => s.toLowerCase())
509+
.join(" - ");
510+
}
511+
511512
togglePause() {
512513
this.paused = !this.paused;
513514
if (!this.paused) {
@@ -539,6 +540,18 @@ class Game {
539540
ctx.fillText(`Score: ${this.score}`, 10, 20);
540541
}
541542

543+
_drawKey() {
544+
let fontSize = 10;
545+
ctx.fillStyle = "#ccc";
546+
ctx.font = `${fontSize}px "${CONFIG.GAME.FONT_FACE}"`;
547+
ctx.textAlign = "center";
548+
ctx.fillText(
549+
this.key,
550+
canvas.width / 2,
551+
GROUND_Y + CONFIG.GROUND_HEIGHT - (CONFIG.GROUND_HEIGHT - fontSize) / 2,
552+
);
553+
}
554+
542555
_handleScoring() {
543556
this.obstacleManager.updateScoring(this.player, () => {
544557
this.score++;
@@ -619,12 +632,21 @@ class Game {
619632
this.rainbowTrail.draw();
620633
this.obstacleManager.draw();
621634
this._drawScore();
635+
this._drawKey();
622636

623637
// Update and draw FPS
624638
this.fpsCounter.draw();
625639
}
626640
}
627641

642+
function share(score) {
643+
const text = `I scored ${score} in Nyan Jump! Try to beat me!`;
644+
const hashtags = "keymap-rs,rust,wasm";
645+
const url = `https://x.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(window.location)}&hashtags=${hashtags}`;
646+
647+
window.open(url, "_blank");
648+
}
649+
628650
// Game instance
629651
let game = new Game();
630652

@@ -655,12 +677,12 @@ export function isGameOver() {
655677
return game.gameOver;
656678
}
657679

658-
export function setGameOver() {
659-
game.gameOver = true;
660-
}
661-
662680
export function pauseGame() {
663681
if (!game.gameOver) {
664682
game.togglePause();
665683
}
666684
}
685+
686+
export function setKey(key, description) {
687+
game.setKey(key, description);
688+
}

examples/wasm/src/lib.rs

Lines changed: 12 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,17 @@ use keymap::DerivedConfig;
33
use serde::Deserialize;
44
use wasm_bindgen::prelude::*;
55
use wasm_bindgen::JsCast;
6-
use web_sys::{console, window, KeyboardEvent};
6+
use web_sys::{window, KeyboardEvent};
77

88
#[wasm_bindgen(module = "/game.js")]
99
extern "C" {
1010
fn jump();
1111
fn moveLeft(is_moving: bool);
1212
fn moveRight(is_moving: bool);
1313
fn isGameOver() -> bool;
14-
fn setGameOver();
1514
fn resetGame();
1615
fn pauseGame();
16+
fn setKey(key: String, desc: String);
1717
}
1818

1919
#[derive(Debug, Clone, keymap::KeyMap, Deserialize, Hash, PartialEq, Eq)]
@@ -60,11 +60,7 @@ pub fn get_keymap_as_json() -> String {
6060
.items
6161
.iter()
6262
.map(|(action, entry)| {
63-
let keys: Vec<String> = entry
64-
.keys
65-
.iter()
66-
.map(|k| format!("\"{}\"", k))
67-
.collect();
63+
let keys: Vec<String> = entry.keys.iter().map(|k| format!("\"{}\"", k)).collect();
6864
let description = entry.description.clone();
6965
format!(
7066
"{{ \"action\": \"{:?}\", \"keys\": [{}], \"description\": \"{}\" }}",
@@ -74,6 +70,7 @@ pub fn get_keymap_as_json() -> String {
7470
)
7571
})
7672
.collect();
73+
7774
format!("[{}]", keymap_info.join(","))
7875
}
7976

@@ -102,18 +99,23 @@ pub fn init_game() {
10299
}
103100

104101
pub fn handle_key_event(event: &KeyboardEvent, is_keydown: bool) {
102+
let config = derived_config();
103+
105104
// Log the key that was pressed
106105
if is_keydown {
107106
let key = event.to_keymap().unwrap();
108-
console::log_1(&key.to_string().into());
107+
let mut desc = String::new();
108+
if let Some((_, item)) = config.get_item(event) {
109+
desc = item.description.clone();
110+
};
111+
112+
setKey(key.to_string(), desc);
109113
}
110114

111115
if isGameOver() {
112116
return;
113117
}
114118

115-
let config = derived_config();
116-
117119
if let Some(action) = config.get(event) {
118120
match action {
119121
Action::Jump => {

0 commit comments

Comments
 (0)