我正在编写蛇游戏,但我有一个问题
var ctx = document.getElementById('ctx').getContext('2d');
var canvas = document.getElementById('ctx');
var y = [240, 230, 220];
var x = [240, 240, 240];
var xSpeed = 0;
var ySpeed = 0;
function load() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (p = 0; p < x.length; p++) {
ctx.fillStyle = "black";
ctx.fillRect(x[p], y[p], 10, 10);
}
}
function keyDown() {
var key = event.keyCode; /*getting keyCode of pressed key*/
ctx.fillStyle = "black"; /*color of rectangle*/
switch (key) {
case 39: //RIGHT
xSpeed = 10;
ySpeed = 0;
break;
case 37: //LEFT
xSpeed = -10;
ySpeed = 0;
break;
case 38: //UP
xSpeed = 0;
ySpeed = -10;
break;
case 40: //DOWN
xSpeed = 0;
ySpeed = 10;
break;
}
}
function update() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
if (x[0] >= 490) {
xSpeed = 0;
} else if (y[0] >= 490) {
ySpeed = 0;
}
console.clear();
y[0] += ySpeed;
x[0] += xSpeed;
for (i = x.length; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}
for (i = 0; i < x.length; i++) {
ctx.fillStyle = "black";
ctx.fillRect(x[i], y[i], 10, 10);
//console.log("y= " + y[i]);
//console.log("x= " + x[i]);
}
//console.log(xSpeed);
//console.log(ySpeed);
}
setInterval(update, 500);
<!DOCTYPE html>
<html>
<head>
<link rel="shortcut icon" href="#">
<title>The Snake Game</title>
</head>
<style>
#ctx {
position: absolute;
/*it can be fixed too*/
left: 0;
right: 0;
top: 0;
bottom: 0;
margin: auto;
/*this to solve "the content will not be cut when the window is smaller than the content":*/
max-width: 100%;
max-height: 100%;
overflow: auto;
}
</style>
<body onkeydown="keyDown()" onload="load()">
<center><canvas id="ctx" width="500" height="500" style="border:1px solid black"></canvas></center>
</body>
<script src="script.js"></script>
</html>
如果运行上面的代码,你会发现for循环中的迭代器的值增加而不是减少。我认为错误是在循环的某个地方,但我看不到它。
for (i = x.length; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}
提前谢谢你。
答案 0 :(得分:1)
for (i = x.length; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}
i=0
尝试抓取索引-1
i
设置为数组的长度为3,但索引为0-2
,因此您超出界限,因此它将在每次运行时添加新值< / strong>因为它会将它作为数组末尾的新值数组索引是:(数组索引基于0)
[0] = ...
[1] = ...
[2] = ...
但长度为3
答案 1 :(得分:1)
x.length
没有y或x的位置for (i = x.length-1; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}
答案 2 :(得分:1)
用
for (i = x.length; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}
您在元素x.length
上迭代开始迭代,这是array +1
中的顶级索引。然后你迭代到0.所以你第一次x[i] = x[i-1]
时它会为你的数组添加一个元素。
这应该解决它:
for (i = x.length-1; i >= 0; i--) {
y[i] = y[i - 1];
x[i] = x[i - 1];
console.log(i);
}