在JavaScript俄罗斯方块中绘制新的tetrominos

时间:2014-03-25 08:08:48

标签: javascript arrays canvas tetris

我正在尝试用JavaScript绘制tetrominos,我遇到了一些麻烦。我认为我的代码,this.blocks = i.blocks [b] [c],是不正确的,但可能更多。既然我的眼睛已经开始受伤了,我决定寻求帮助。 this.blocks = i.blocks [b] [c]不起作用,因为this.blocks无法存储数组吗?还是有另一个问题。谢谢您的帮助。

这是jsfiddle链接:http://jsfiddle.net/8aS9E/

以下是代码:

var canvas = document.getElementById("canvas");
        var ctx = canvas.getContext("2d");
        canvas.height = window.innerHeight;
        canvas.width = window.innerWidth;
        var h = canvas.height;
        var w = canvas.width;
        var gridWidth = w / 4;
        var gridHeight = h;
        var cols = gridWidth / 10; //width, columns
        var rows = cols; //height, rows
        window.addEventListener("keydown", test, true); 
        var b = 0;
        var c = 0;

    var gravity = 0;

    var id;
    var type = 2;
    var color; 
    var x = gridWidth * 2;
    var y = -30;
    var position;
    var velocityY;
    var tetrominoId = 0;
  var i = { id: 'i', size: 4, 
                blocks: [[0, 1, 0, 0],
                [0, 1, 0, 0],
                [0, 1, 0, 0],
                [0, 1, 0, 0]], 
                color: 'cyan'   };

function tetromino(id, type, color, position, y, velocityY){
    this.id = i.id;
    this.blocks = i.blocks[b][c];
    this.color = i.color;
    this.x = x;
    this.y = y;
    this.velocityY = 1;
}

var tetrominoList = [];

function addTetromino(type, color, position, x, y, velocityY){
tetrominoList[tetrominoId] = new tetromino(tetrominoId, type, color, x, y, velocityY);
tetrominoId++;

}

function tetrominoDraw(){

        tetrominoList.forEach(function(tetromino){

        for(b = 0; b < 4; b++){

            for(c = 0; c < 4; c++){



                    ctx.fillStyle = tetromino.color;
                    ctx.fillRect(
                        gridWidth * 2 + tetromino.blocks[b][c] * 
                        b * cols, tetromino.blocks[b][c] * c * rows + gravity + y,
                        cols, rows
                        );
                    ctx.fill();
                }   
            }
        }   
        });

        }

谢谢!

1 个答案:

答案 0 :(得分:1)

tetromino.blocks不是一个数组,而是一个整数,因为它等于第一个i.blocks数组的第一个元素的值(i.blocks [0] [0],因为两者都是b和c变量在初始化时定义为零。

您要做的就是摆脱tetromino声明中的数组地址:

function tetromino(id, type, color, position, y, velocityY) {
    this.id = i.id;
    this.blocks = i.blocks;
    this.color = i.color;
    this.x = x;
    this.y = y;
    this.velocityY = 1;
}

我已经更新了你的小提琴: http://jsfiddle.net/8aS9E/1/