You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript贪吃蛇游戏ArrowUp按键移动失效问题求助

贪吃蛇上箭头按键失效问题排查与修复

问题出在你定义的key数组里:

const key = [
    "ArrowUp ",  // 这里多了一个末尾空格
    "ArrowRight",
    "ArrowDown",
    "ArrowLeft"
];

当按下上箭头时,event.code的实际值是ArrowUp(无空格),但数组里的项是带空格的"ArrowUp ",导致key.indexOf(event.code)返回-1,上箭头按键不会被识别,direction变量不会被赋值,所以move函数里的ArrowUp分支永远不会执行。

修复方案

把key数组中的"ArrowUp "修改为"ArrowUp",去掉末尾的空格:

const key = [
    "ArrowUp",
    "ArrowRight",
    "ArrowDown",
    "ArrowLeft"
];

修复后,上箭头按键就能正常触发方向变更,蛇的向上移动逻辑也会正常执行了。其他方向正常是因为它们的数组项没有多余空格,能正确匹配event.code的值。

修复后的完整代码

const snake = [
    {
        x: 15,
        y: 30
    }
];

const key = [
    "ArrowUp",
    "ArrowRight",
    "ArrowDown",
    "ArrowLeft"
];

let direction = null;
let interval = null;

function run(){
    const playboard = document.getElementById("playboard");

    for (let x = 0; x < config.x; x ++){
        for (let y = 0;y < config.y; y ++){
            const cell = document.createElement("div");
            cell.setAttribute("id",`${x}_${y}`);
            cell.setAttribute("class","cell");

            if (y === 59){
                cell.setAttribute("class","clearLeft");
            }
            playboard.appendChild(cell);
        }
    }

    draw();

    window.addEventListener("keydown", event =>{
        if (key.indexOf(event.code) > -1){
            direction = event.code;
        }
    });

    interval = setInterval(function(){
        move();
        draw();
    }, 500)
}

function move() {
    switch(direction) {
    case 'ArrowLeft':
        snake[0].y -= 1
        break;
    case 'ArrowRight':
        snake[0].y += 1
        break;
    case 'ArrowUp':
        snake[0].x -= 1
        break;
    case 'ArrowDown':
        snake[0].x += 1
        break;
    default:
        // TODO: Play a fart sound.
        break;
    }
}

function draw(){

    for (let x = 0; x < config.x; x ++){
        for (let y = 0;y < config.y; y ++){
            document.getElementById(`${x}_${y}`).style.backgroundColor = "black";

        }
    }

    snake.forEach(p => {
        document.getElementById(`${p.x}_${p.y}`).style.backgroundColor = "blue";
    })

}

const config = {
    x: 30,
    y: 60
};

run(config);

内容的提问来源于stack exchange,提问作者Lorenzo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 13:03:15