有tetris块落在JavaScript中

时间:2014-08-12 02:34:29

标签: javascript

我想知道如何制作俄罗斯方块片,我已经完成了一些教程并制作了完整的游戏,但我对他们实际上是如何让这些片段掉落以及它们是如何制作它们感到有点困惑2d阵列变成实际的块,有人可以指导我在正确的方向吗?我只是想更好地学习这个过程,这一切都是在画布上完成的。

例如,这是lpiece

function LPiece(){
//the pieces are represented in arrays shaped like the pieces, for example, here is an L.
//each state is a form the piece takes on, so each state after this.state1 is this.state1 rotated.
//each state is individual so we can call out which state to use depending on the option selected.
this.state1 = [ [1, 0],
                [1, 0],
                [1, 1]];
//and heres a different piece
this.state2 = [ [0, 0, 1],
                [1, 1, 1]];

this.state3 = [
                [1,1],
                [0,1],
                [0,1]];
this.state4 = [
                [1, 1, 1],
                [1, 0, 0]];

//and now we tie them all to one

this.states = [this.state1, this.state2, this.state3, this.state4];
//reference to the state the piece is currently in.
this.curState = 0;
//color of piece
this.color = 0;
//tracking pieces of grid of x and y coords, this is set at 4, -3 so it isn't initially visable.
this.gridx = 4;
this.gridy = -3;
}

    piece.color = Math.floor(Math.random() *8);

我添加了评论,试图让我最初理解 这是他们用于每个块的图像,每个块是一种颜色 http://i.imgur.com/Mh5jMox.png

那么他如何将数组转换为实际的块,然后让它从板上掉下来,我无休止地搜索,我只是感到困惑,就像他将gridx和gridy设置为x和y坐标一样没有说过this.y =网格或类似的东西?有没有人对这里做什么有任何建议?感谢

这里是他如何绘制这件作品我猜,我仍然不明白他是如何将x和y连接到该棋子的gridx和y,而实际上并没有说x和y是网格x和y。

function drawPiece(p){
//connecting the y and x coords or pieces to draw using the arrays to pieces we defined earlier.
var drawX = p.gridx;
var drawY = p.gridy;
var state = p.curState;

//looping through to get a pieces currentstate, and drawing it to the board.
//rows, the p.state is deciding the length by the currentstate(the block width)
for(var r = 0, len = p.states[state].length; r < len; r++){
    //columns the p.state is deciding the length by the currentstate(the block width)

    for(var c = 0, len2 = p.states[state][r].length; c < len2; c++){
        //detecting if there is a block to draw depending on size of value returned.
        if(p.states[state][r][c] == 1 && drawY >= 0){
            ctx.drawImage(blockImg, p.color * SIZE, 0, SIZE, SIZE, drawX * SIZE, drawY * SIZE, SIZE, SIZE);
        }


        drawX += 1;
    }
    //resetting the gridx
    drawX = p.gridx;
    //incrementing gridy to get the second layer of arrays from the block states.
    drawY += 1;
}
}

1 个答案:

答案 0 :(得分:1)

他转换为ctx.drawImage中的画布像素单位,这里是简化版

var canvasX = drawX * SIZE;
var canvasY = drawY * SIZE;
ctx.drawImage(blockImg, p.color * SIZE, 0, SIZE, SIZE, canvasX, canvasY, SIZE, SIZE);

https://developer.mozilla.org/en/docs/Web/API/CanvasRenderingContext2D#drawImage()