2014-03-25 63 views
2

我試圖在JavaScript中繪製tetrominos,並且遇到了一些麻煩。我認爲我的代碼this.blocks = i.blocks [b] [c]是不正確的,但它可能更多。現在我的眼睛開始受傷了,我決定尋求幫助。是否this.blocks = i.blocks [b] [c]不起作用,因爲this.blocks不能存儲數組?或者還有另一個問題。感謝您的幫助。在JavaScript中繪製新的tetromin俄羅斯方塊

這裏的的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

tetromino.blocks不是一個數組,而是一個整數,因爲它等於i.blocks(i.blocks [0] [0])的第一個數組的第一個元素的值,因爲b和c變量都是在其初始化中定義爲零)。

所有你需要做的就是擺脫在四格拼板聲明數組地址:

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/