@@ -10,11 +10,8 @@ We also load all of our images.
10
10
*/
11
11
12
12
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" ) ;
18
15
canvas . width = 512 ;
19
16
canvas . height = 480 ;
20
17
document . body . appendChild ( canvas ) ;
@@ -70,16 +67,16 @@ let monsterY = 100;
70
67
*
71
68
* This is just to let JavaScript know when the user has pressed a key.
72
69
*/
73
- let keysDown = { } ;
70
+ let keysPressed = { } ;
74
71
function setupKeyboardListeners ( ) {
75
72
// Check for keys pressed where key represents the keycode captured
76
73
// 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 ;
79
76
} , false ) ;
80
77
81
- addEventListener ( "keyup" , function ( key ) {
82
- delete keysDown [ key . keyCode ] ;
78
+ document . addEventListener ( "keyup" , function ( e ) {
79
+ keysPressed [ e . key ] = false ;
83
80
} , false ) ;
84
81
}
85
82
@@ -94,22 +91,21 @@ let update = function () {
94
91
// Update the time.
95
92
elapsedTime = Math . floor ( ( Date . now ( ) - startTime ) / 1000 ) ;
96
93
97
-
98
- if ( 38 in keysDown ) { // Player is holding up key
94
+ if ( keysPressed [ "ArrowUp" ] ) {
99
95
heroY -= 5 ;
100
96
}
101
- if ( 40 in keysDown ) { // Player is holding down key
97
+ if ( keysPressed [ "ArrowDown" ] ) {
102
98
heroY += 5 ;
103
99
}
104
- if ( 37 in keysDown ) { // Player is holding left key
100
+ if ( keysPressed [ "ArrowLeft" ] ) {
105
101
heroX -= 5 ;
106
102
}
107
- if ( 39 in keysDown ) { // Player is holding right key
103
+ if ( keysPressed [ "ArrowRight" ] ) {
108
104
heroX += 5 ;
109
105
}
110
106
111
107
// Check if player and monster collided. Our images
112
- // are about 32 pixels big.
108
+ // are 32 pixels big.
113
109
if (
114
110
heroX <= ( monsterX + 32 )
115
111
&& monsterX <= ( heroX + 32 )
@@ -126,7 +122,7 @@ let update = function () {
126
122
/**
127
123
* This function, render, runs as often as possible.
128
124
*/
129
- var render = function ( ) {
125
+ function render ( ) {
130
126
if ( bgReady ) {
131
127
ctx . drawImage ( bgImage , 0 , 0 ) ;
132
128
}
@@ -144,7 +140,7 @@ var render = function () {
144
140
* update (updates the state of the game, in this case our hero and monster)
145
141
* render (based on the state of our game, draw the right things)
146
142
*/
147
- var main = function ( ) {
143
+ function main ( ) {
148
144
update ( ) ;
149
145
render ( ) ;
150
146
// Request to do this again ASAP. This is a special method
0 commit comments