Skip to content

Commit 02016de

Browse files
committed
Updating keyhandlers to use e.key instead of e.keyCode and using more consistent function declaration.
1 parent 9ba12fc commit 02016de

File tree

1 file changed

+14
-18
lines changed

1 file changed

+14
-18
lines changed

game.js

+14-18
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,8 @@ We also load all of our images.
1010
*/
1111

1212

13-
let canvas;
14-
let ctx;
15-
16-
canvas = document.createElement("canvas");
17-
ctx = canvas.getContext("2d");
13+
const canvas = document.createElement("canvas");
14+
const ctx = canvas.getContext("2d");
1815
canvas.width = 512;
1916
canvas.height = 480;
2017
document.body.appendChild(canvas);
@@ -70,16 +67,16 @@ let monsterY = 100;
7067
*
7168
* This is just to let JavaScript know when the user has pressed a key.
7269
*/
73-
let keysDown = {};
70+
let keysPressed = {};
7471
function setupKeyboardListeners() {
7572
// Check for keys pressed where key represents the keycode captured
7673
// For now, do not worry too much about what's happening here.
77-
addEventListener("keydown", function (key) {
78-
keysDown[key.keyCode] = true;
74+
document.addEventListener("keydown", function (e) {
75+
keysPressed[e.key] = true;
7976
}, false);
8077

81-
addEventListener("keyup", function (key) {
82-
delete keysDown[key.keyCode];
78+
document.addEventListener("keyup", function (e) {
79+
keysPressed[e.key] = false;
8380
}, false);
8481
}
8582

@@ -94,22 +91,21 @@ let update = function () {
9491
// Update the time.
9592
elapsedTime = Math.floor((Date.now() - startTime) / 1000);
9693

97-
98-
if (38 in keysDown) { // Player is holding up key
94+
if (keysPressed["ArrowUp"]) {
9995
heroY -= 5;
10096
}
101-
if (40 in keysDown) { // Player is holding down key
97+
if (keysPressed["ArrowDown"]) {
10298
heroY += 5;
10399
}
104-
if (37 in keysDown) { // Player is holding left key
100+
if (keysPressed["ArrowLeft"]) {
105101
heroX -= 5;
106102
}
107-
if (39 in keysDown) { // Player is holding right key
103+
if (keysPressed["ArrowRight"]) {
108104
heroX += 5;
109105
}
110106

111107
// Check if player and monster collided. Our images
112-
// are about 32 pixels big.
108+
// are 32 pixels big.
113109
if (
114110
heroX <= (monsterX + 32)
115111
&& monsterX <= (heroX + 32)
@@ -126,7 +122,7 @@ let update = function () {
126122
/**
127123
* This function, render, runs as often as possible.
128124
*/
129-
var render = function () {
125+
function render() {
130126
if (bgReady) {
131127
ctx.drawImage(bgImage, 0, 0);
132128
}
@@ -144,7 +140,7 @@ var render = function () {
144140
* update (updates the state of the game, in this case our hero and monster)
145141
* render (based on the state of our game, draw the right things)
146142
*/
147-
var main = function () {
143+
function main() {
148144
update();
149145
render();
150146
// Request to do this again ASAP. This is a special method

0 commit comments

Comments
 (0)