Javascript 如何防止两个画布对象出现在同一位置
我正在制作一款蛇形街机游戏,虽然游戏已经启动并且运行良好,但我正在尝试调整游戏,以便苹果永远不会出现在与蛇片段相同的位置(对于那些不认识蛇的人来说,这是一款经典的街机游戏,蛇在屏幕上滑动,吃着随机出现的苹果,试图避免撞到自己或墙壁上,每次吃苹果都会变长)。下面是在屏幕上移动苹果的代码:Javascript 如何防止两个画布对象出现在同一位置,javascript,oop,canvas,Javascript,Oop,Canvas,我正在制作一款蛇形街机游戏,虽然游戏已经启动并且运行良好,但我正在尝试调整游戏,以便苹果永远不会出现在与蛇片段相同的位置(对于那些不认识蛇的人来说,这是一款经典的街机游戏,蛇在屏幕上滑动,吃着随机出现的苹果,试图避免撞到自己或墙壁上,每次吃苹果都会变长)。下面是在屏幕上移动苹果的代码: Apple.prototype.move = function() { var randomCol = Math.floor(Math.random()*(widthInBlocks-2)) +1; va
Apple.prototype.move = function() {
var randomCol = Math.floor(Math.random()*(widthInBlocks-2)) +1;
var randomRow = Math.floor(Math.random()*(heightInBlocks-2)) +1;
this.position = new Block(randomCol, randomRow);
for (i = 0; i < Snake.segments; i++) {
if (this.position === Snake.segments[i].col && Snake.segments[i].row) {
this.move();
};
};
}
画蛇的代码如下:
var Snake = function() {
this.segments = [
new Block(7, 5),
new Block(6, 5),
new Block(5, 5)
];
this.direction = "right";
this.nextDirection = "right";
};
//function to toggle the colour of the snake's segments
function alternateColour(i) {
var colours = ["limegreen", "yellow"];
if (i % 2 === 0) {
return colours[0];
} else {
return colours[1];
};
};
//draw snake method
Snake.prototype.draw = function() {
this.segments[0].drawSquare("blue"); //snake head will always be blue
for (i = 1; i < this.segments.length; i++) {
this.segments[i].drawSquare(alternateColour(i));
};
};
谢谢。在检查苹果位置是否与蛇段冲突时,您的
Apple.prototype.move
功能似乎有错误
您正在计算苹果位置(randomCol
,randomRow
),但在检查每个蛇段时不使用这些值
另外,当您预计会遇到冲突时,可以调用this.move()
。但是在该函数返回后,您将继续在前面的for
循环中完成所有剩余的迭代
通过以下更改可以解决这些问题:
for (i = 0; i < Snake.segments; i++) {
if (randomCol === Snake.segments[i].col && randomRow === Snake.segments[i].row) {
return this.move();
};
};
for(i=0;i
谢谢。我曾经尝试过这一点,只是没有返回move()
方法,我只是简单地调用了它。非常感谢您的输入!
for (i = 0; i < Snake.segments; i++) {
if (randomCol === Snake.segments[i].col && randomRow === Snake.segments[i].row) {
return this.move();
};
};