无法读取未定义的属性“ x”-蛇[已解决]

时间:2019-03-26 19:06:10

标签: javascript

-编辑-

问题出在绘制函数中 我打电话给player.update(); 但我应该打电话给player.update(apple);  感谢您的帮助

我从头开始编写蛇的代码,我认为问题出在蛇的部分。但是我看不到。 我已经尝试过三次重写代码 这是我第一次尝试过类似的方法,所以我对问题可能没有帮助。 -如果要使用此链接而不是此处的代码,则为程序的链接,以查看发生了什么 https://www.khanacademy.org/computer-programming/snakeprototype/4797370687356928 感谢您的任何帮助〜谢谢

var gameSpeed = 10;

// Declare Functions
var Player;
var Part;
var UpdateParts;
var Apple;

/*
KeyCode functions

*/

var parts = [];

var Part = function(x, y)
{
    this.x = x;
    this.y = y;
    this.pX = this.x;
    this.pY = this.y;
};

var Player = function()
{
    parts[0] = new Part(200, 200);
    parts[1] = new Part(200, 210);
    parts[2] = new Part(200, 220);

    this.update = function(apple)
    {
        if (parts[0].x === apple.x && parts[0].y === apple.y)
        {
            apple.newApple();
        }
        // Square
        fill(27, 168, 36);
        rect(parts[0].x, parts[0].y, 10, 10);
        /*
        Change Directions
        */

        if (frameCount % gameSpeed === 0)
        {
            //move
            if (this.direction === "up") 
            {
                parts[0].y-=this.speed;
            }
            if (this.direction === "down") 
            {
                parts[0].y+=this.speed;
            }
            if (this.direction === "left") 
            {
                parts[0].x-=this.speed;
            }        
            if (this.direction === "right") 
            {
                parts[0].x+=this.speed;
            }
        }
    };
};

var UpdateParts = function()
{
    for (var i = 1; i < parts.length; i++)
    {
        if (frameCount % gameSpeed === 0)
        {
             parts[i].pX = parts[i].x;
             parts[i].pY = parts[i].y;
             parts[i].x = parts[i-1].pX;
             parts[i].y = parts[i-1].pY;
        }
    }
};

/*
Apple function

*/

var apple = new Apple();
var player = new Player();

0 个答案:

没有答案