我是JavaScript的新手,并且有一个崩溃的应用程序。我不知道是什么会导致崩溃。
以下是代码:
vertex_weight(source_vertex)
答案 0 :(得分:2)
如果你把自己全部写完,那对初学者来说还不错。
你的问题在于keydown事件。每次勾选时,您都在创建一个新的处理程序。这将导致崩溃。您只需要为页面创建一次事件处理程序,它将保持活动状态,直到您离开页面。
要解决您的问题,请将keyDown侦听器添加到函数Start的正上方,如下所示。
var snake = [];
document.addEventListener("keydown", function (evt) {
keystate = evt.keyCode; // checks key presses
});
function start(){
init();
Tick();
}
也只是因为对我而言看起来很奇怪。 true和false不是你不需要在它们周围加上引号的字符串。虽然将它们用作字符串仍然有效。
你有
function setFood() { //WE ARE RUNNING OUT OF FOOD WE NEED NEW PROVISIONS
var next = "true"
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = "false"
}
}
} while (next == "false")
draw();
}
将更好地编写如下
function setFood() {
var next = true; // removed the qoutes
do {
foodX = Math.floor((Math.random() * Rows));
foodY = Math.floor((Math.random() * Col));
for (var i = 0; i < snake.length; i++) {
if (snake[i].x == foodX && snake[i].y == foodY) {
next = false; // removed the quotes.
// no point continuing the for loop as you know you need to
// reposition the food so use the break token
break; // breaks out of the closest loop
}
}
} while ( !next ) // removed next == "false" and replaced with
// ! next. "!" means "Not". do while next not true
// you have the draw here but you draw every tick so it would be best if
// you removed it as the next draw is less than 1/3 of a second away anyways
// draw(); // removed needless draw
}
干得好。希望你能得到一个好的标记。