大家好,我正在做关于蛇JS游戏的教程。我想在我正在监听“ keydown”事件的事件监听器上设置一个断点。我想看看触发此事件后发生的一切。因此,使用chrome工具,我将代码标记为该行。然后刷新页面,以查看程序暂停的位置。在html加载之前。我想先加载游戏板,然后再按箭头键暂停。我该怎么办?
let food = {
x : Math.floor(Math.random()*17+1) * box,
y : Math.floor(Math.random()*15+3) * box
}
//create the score
let score = 0;
//control snake direction
document.addEventListener('keydown', direction);//ADD-BREAKPOINT-HERE-------------------------------------------------------------
//declare the global variable to hold the direction
let d;
function direction(event) {
if(event.keyCode == 37 && d != 'RIGHT') {
d = 'LEFT';
}
else if(event.keyCode == 38 && d != 'DOWN') {
d = 'UP';
}
else if(event.keyCode == 39 && d != 'LEFT') {
d = 'RIGHT';
}
else if(event.keyCode == 40 && d != 'UP') {
d = 'DOWN';
}
}
//draw the board
function draw() {
//uses drawImage() method to draw background image to canvas
ctx.drawImage(ground, 0, 0);
for (let i = 0; i < snake.length; i++) {
//use ternary operator if current iteration is of index 0 - style = green else style = white
ctx.fillStyle = (i === 0)? 'green' : 'white';
// fill with chosen color
ctx.fillRect(snake[i].x, snake[i].y, box, box);
// set stroke or outline to red
ctx.strokeStyle = 'red';
// draw outline
ctx.strokeRect(snake[i].x, snake[i].y, box, box);
}
//draw food image
ctx.drawImage(foodImg, food.x, food.y);
//draw score
ctx.fillStyle = 'white';
ctx.font = '45px Orbitron';
ctx.fillText(score, 2 * box, 1.6 * box);
//old head position
let snakeX = snake[0].x;
let snakeY = snake[0].y;
//move to chosen direction
if(d == 'LEFT') snakeX -= box;
if(d == 'UP') snakeY -= box;
if(d == 'RIGHT') snakeX += box;
if(d == 'DOWN') snakeY += box;
//remove the tail
snake.pop();
//create new head
let newHead = {
x : snakeX,
y : snakeY
}
//add new head
snake.unshift(newHead);
}
let game = setInterval(draw, 100);
<!DOCTYPE html>
<html lang="en">
<head>
<title>Snake Game</title>
<style>
canvas{
display: block;
margin: 0 auto;
}
</style>
<link href="https://fonts.googleapis.com/css?family=Orbitron" rel="stylesheet">
</head>
<canvas id="snake" width="608" height="608"></canvas>
<script src="script.js"></script>
</html>