Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save yitonghe00/5e3665d7edd65c1b03347a6dac8a5437 to your computer and use it in GitHub Desktop.
Save yitonghe00/5e3665d7edd65c1b03347a6dac8a5437 to your computer and use it in GitHub Desktop.
<link rel="stylesheet" href="css/game.css">
<body>
<script>
// The old runLevel function. Modify this...
function runLevel(level, Display) {
let display = new Display(document.body, level);
let state = State.start(level);
let ending = 1;
return new Promise(resolve => {
let paused = false;
const escHandler = (event) => {
if (event.key === 'Escape') {
event.preventDefault();
if (paused) runAnimation(frame);
paused = !paused;
}
}
window.addEventListener('keydown', escHandler);
const arrowKeys = trackKeys(["ArrowLeft", "ArrowRight", "ArrowUp"]);
const frame = function(time) {
state = state.update(time, arrowKeys);
display.syncState(state);
if (state.status == "playing") {
return true && !paused;
} else if (ending > 0) {
ending -= time;
return true && !paused;
} else {
display.clear();
window.removeEventListener('keydown', escHandler);
arrowKeys.unregister();
resolve(state.status);
return false;
}
}
runAnimation(frame);
});
}
function trackKeys(keys) {
let down = Object.create(null);
function track(event) {
if (keys.includes(event.key)) {
down[event.key] = event.type == "keydown";
event.preventDefault();
}
}
window.addEventListener("keydown", track);
window.addEventListener("keyup", track);
down.unregister = () => {
window.removeEventListener("keydown", track);
window.removeEventListener("keyup", track);
}
return down;
}
runGame(GAME_LEVELS, DOMDisplay);
</script>
</body>
@yitonghe00
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment