检测网格上的有界正方形

时间:2015-07-28 10:55:26

标签: javascript

我正在阅读一个教程,显然我想要得到这个。但我在编码部分找不到错误,我也会一步一步走。我什么也没做,但在我从上面摔下来之前。显然我想要得到类似的东西 what i'm suppose to be geting at http://i58.tinypic.com/2vc6zhd.jpg

var WIDTH = 300,
    HEIGHT = 400,
    c = document.getElementById('canvas'),
    ctx = c.getContext('2d');

setInterval(function() {
    clearCanvas();
    generateNextSquare();
    updatePosition();
    drawOnCanvas();
}, 1000 / 50);

var clearCanvas = function() {
    ctx.fillStyle = 'White';
    ctx.beginPath();
    ctx.rect(0, 0, WIDTH, HEIGHT);
    ctx.closePath();
    ctx.fill();
}

var drawLine = function() {
    ctx.beginPath();
    ctx.moveTo(200, 0);
    ctx.lineTo(200, 400);
    ctx.stroke();
}

var updatePosition = function() {
    _square.fall();
}

var drawOnCanvas = function() {
    drawLine();
    _square.draw();
}
var squareLength = 20;
var speedLevels = [20, 16, 12, 10, 8],
    currSpeed = speedLevels[0];

var gameGrid = [
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
    [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
];


var Square = function(speed) {
    var self = this;
    self.color = "Black";
    self.vPosition = 0;
    self.hPosition = 4;
    self.speed = speed;
    self.current = 0 ;
    self.temp = 0;

    self.fall = function() {
        if (self.counter >= self.speed) {
            if (self.checkFalling()) {
                self.vPosition++;
            } else {
                gameGrid[self.vPosition][self.hPosition] = 1;
                self.active = false;
            }
            self.counter = 0;
        }
        self.counter++;
    }
    self.checkFalling = function() {
        if (gameGrid[self.vPosition + 1][self.hPosition] == 1)
            return false;
        else
            return true;
    }
}
return self;
}


var drawFixedSquares = function() {
    for (var i = 0; i < 20; i++) {
        for (var j = 0; j < 10; j++) {
            if (gameGrid[i][j] == 1) {
                ctx.fillStyle = "Black";
                ctx.fillRect(j * squareLength, i * squareLength, squareLength, squareLength);
            }
        }
    }
}
var generateNextSquare = function() {
    if (!_square.active)
        _square = new Square(currSpeed);
}
var _square = new Square(currSpeed);

0 个答案:

没有答案