Assigns a unique id later access HTML element score. Actual element is inserted in between "><"
document.getElementById() retrieves HTML element w/id "score" to modify its 'innerHTML" property
'innerHTML" property allows you to get or set HTML content inside an element. Here, value of VARIABLE score is assigned to the 'innerHTML' property of this element.
Comparison: element vs variable: former is used to access HTML element to display on frontend, latter is used to update backend data
[x] Use of callback function to control display based on keyboard input
// Code sets up a keydown event where when key is passed, event object 'e' is passed to callback function
document.addEventListener('keydown', function(e) {
// prevent snake from backtracking on itself by checking that it's
// not already moving on the same axis (pressing left while moving
// left won't do anything, and pressing right while moving left
// shouldn't let you collide with your own body)
// left arrow key
if (e.which === 37 && snake.dx === 0) {
snake.dx = -grid;
snake.dy = 0;
}
// up arrow key
else if (e.which === 38 && snake.dy === 0) {
snake.dy = -grid;
snake.dx = 0;
}
// right arrow key
else if (e.which === 39 && snake.dx === 0) {
snake.dx = grid;
snake.dy = 0;
}
// down arrow key
else if (e.which === 40 && snake.dy === 0) {
snake.dy = grid;
snake.dx = 0;
}
});
Callback function: passed as the second argument to addEventListener function and is executed when specified 'keydown' event occurs
Callback function checks which key was pressed by accessing the 'e.which' property (returns ASCII value of key pressed)
Based on ASCII updates snake.dx and snake.dy properties accordingly
Callback also used below where requestAnimationFrame function passes loop function (creates game loop)
Learning Takeaways
HTML
JAVASCRIPT
Output on snake game: SCORE: #