Created
May 22, 2022 22:45
-
-
Save yitonghe00/5e3665d7edd65c1b03347a6dac8a5437 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
3 state solution: https://eloquentjavascript.net/code/#16.2