Skip to content

Commit

Permalink
Add keyboard handling
Browse files Browse the repository at this point in the history
It's very rudimentary now -- allowing movement only.
  • Loading branch information
tomassedovic committed Dec 20, 2017
1 parent 2af535c commit 2741873
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
27 changes: 27 additions & 0 deletions dose-response.js
Expand Up @@ -13,6 +13,14 @@ ctx.font = '16px arial';

var wasm_instance;
var gamestate_ptr;
var keyqueue = [];

const keymap = {
ArrowUp: 0,
ArrowDown: 1,
ArrowLeft: 2,
ArrowRight: 3
};


fetch('target/wasm32-unknown-unknown/release/dose-response.wasm')
Expand Down Expand Up @@ -47,6 +55,12 @@ fetch('target/wasm32-unknown-unknown/release/dose-response.wasm')
}))

.then(results => {

document.addEventListener('keydown', (event) => {
console.log(event);
keyqueue.push(event);
});

console.log("The game has finished.");
console.log(results);
console.log(results.module);
Expand All @@ -60,7 +74,20 @@ fetch('target/wasm32-unknown-unknown/release/dose-response.wasm')

function update() {
//window.requestAnimationFrame(update);
//window.setTimeout(update, 100);
//console.log("calling update");
for(let key of keyqueue) {
var key_code = -1;
if(key.key in keymap) {
key_code = keymap[key.key];
}
wasm_instance.exports.key_pressed(
gamestate_ptr,
key_code,
key.ctrlKey, key.altKey, key.shiftKey, key.location);
}
keyqueue = [];

results.instance.exports.update(gamestate_ptr);
//console.log("called update");
}
Expand Down
27 changes: 27 additions & 0 deletions src/main.rs
Expand Up @@ -432,6 +432,33 @@ pub fn update(state_ptr: *mut State) {
std::mem::forget(state);
}

#[no_mangle]
pub extern "C" fn key_pressed(
state_ptr: *mut State,
external_code: i32,
ctrl: bool, alt: bool, shift: bool, location: i32
)
{
use std::ffi::CStr;

#[allow(unsafe_code)]
let mut state: Box<State> = unsafe { Box::from_raw(state_ptr) };

let code = match external_code {
0 => Some(keys::KeyCode::Up),
1 => Some(keys::KeyCode::Down),
2 => Some(keys::KeyCode::Left),
3 => Some(keys::KeyCode::Right),
_ => None,
};
if let Some(code) = code {
state.keys.push(keys::Key { code, alt, ctrl, shift});
}

std::mem::forget(state);

}


fn main() {
// NOTE: at our current font, the height of 43 is the maximum
Expand Down

0 comments on commit 2741873

Please sign in to comment.