I'm trying to draw tetrominos in JavaScript and I'm having some trouble. I think the code I have, this.blocks = i.blocks[b][c], is incorrect, but it may be more. Now that my eyes have started hurting, I've decided to ask for help. Does this.blocks = i.blocks[b][c] not work because this.blocks can't store an array? Or is there another problem. Thank you for your help.
Here's the jsfiddle link: http://jsfiddle.net/8aS9E/
Here's the code:
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();
}
}
}
});
}
Thank you!
tetromino.blocks isn't an array but an integer because it's equal to the value of the first element of the first array of i.blocks (i.blocks[0][0] because both b and c variables are defined as zeros in their initializations).
All you have to do is get rid of an array address in the tetromino declaration:
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;
}
I've updated your fiddle: http://jsfiddle.net/8aS9E/1/