6

我有一个附加到正在运行的窗口的事件keydown。我想通过一个例程(每个间隔)以编程方式敲击键盘上的一个键来测试这一点。以下代码不起作用 - 但如果我实际按下键盘上的键,则可以正常工作。

我最初尝试过:

var evt = document.createEvent("KeyboardEvent"); 
setInterval(function() {
    evt.initKeyEvent("keydown", true, true, window, false, false, false, false, 13, 13);
}, 500);

这是我目前的keydown活动:

window.addEventListener('keydown', function(k) {
    switch(k.keyCode) {
        case 38: //up
            if (Game.Area[Game.Player.x][Game.Player.y-1].type !== 0 && Game.Player.y > 0) {
                Game.Player.y--;
            }
            Game.Player.d = 0;
            break;
        case 40: //down
            if (Game.Area[Game.Player.x][Game.Player.y+1].type !== 0 && Game.Player.y < Game.Area[0].length-1) {
                Game.Player.y++;
            }
            Game.Player.d = 1;
            break;
        case 37: //left
            if (Game.Area[Game.Player.x-1][Game.Player.y].type !== 0 && Game.Player.x > 0) {
                Game.Player.x--;
            }
            Game.Player.d = 2;
            break;
        case 39: //right
            if (Game.Area[Game.Player.x+1][Game.Player.y].type !== 0 && Game.Player.y < Game.Area.length-1) {
                Game.Player.x++;
            }
            Game.Player.d = 3;
            break;
        case 66:
            if (Game.Player.d === 0 && Game.Player.y > 0) { //up
                Game.Area[Game.Player.x][Game.Player.y-1].type = 60;
            } else if (Game.Player.d === 1 && Game.Player.y < Game.Area.length) { //down
                Game.Area[Game.Player.x][Game.Player.y+1].type = 60;
            } else if (Game.Player.d === 2 && Game.Player.x > 0) { //left
                Game.Area[Game.Player.x-1][Game.Player.y].type = 60;
            } else if (Game.Player.d === 3 && Game.Player.x < Game.Area.length) { //right
                Game.Area[Game.Player.x+1][Game.Player.y].type = 60;
            }
            break;
        default:
            break;
    }
    Game.MoveZeds();

    for (var z = 0; z < Game.Zeds.length; z++) {
        if (Game.Player.x === Game.Zeds[z].x && Game.Player.y === Game.Zeds[z].y) {
            alert("Ouch!");
        }
    }
});
4

1 回答 1

0

我相信

evt.initKeyEvent();

实际上应该是

evt.initKeyboardEvent();
于 2013-08-12T15:33:44.310 回答