emmaxshen / APCS_Blog

Apache License 2.0
0 stars 10 forks source link

JavaScript Ticket #44

Open emmaxshen opened 1 year ago

emmaxshen commented 1 year ago

Learning Takeaways

HTML

<p id="p1">SCORE:</p>
<p id="score"></p>

JAVASCRIPT

document.getElementById('score').innerHTML=score;

Output on snake game: SCORE: #


// 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;
  }
});