【问题标题】:breakpoint not stopping program flow on event listener断点不停止事件侦听器上的程序流
【发布时间】:2019-01-11 21:05:37
【问题描述】:

大家好,我正在做一个关于蛇 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>

【问题讨论】:

    标签: javascript debugging breakpoints


    【解决方案1】:

    我认为this is 你需要什么。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-07-24
      • 2022-01-02
      • 2013-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多