Permalink
Browse files

Add keyboard handling

It's very rudimentary now -- allowing movement only.
  • Loading branch information...
tomassedovic committed Dec 20, 2017
1 parent 2af535c commit 2741873ff6e34c88b4a5929ca477fc8dea877c7b
Showing with 54 additions and 0 deletions.
  1. +27 −0 dose-response.js
  2. +27 −0 src/main.rs
@@ -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')
@@ -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);
@@ -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");
}
@@ -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

0 comments on commit 2741873

Please sign in to comment.