断点未停止事件侦听器上的程序流



大家好,我正在做一个关于贪吃蛇JS游戏的教程。我想在我拥有的事件侦听器上设置一个断点,该侦听器正在侦听"键控"事件。我想查看触发此事件后发生的一切。因此,使用我的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>

我认为这就是你需要的。

最新更新