Java Tetris rotation

て烟熏妆下的殇ゞ 提交于 2019-12-05 21:03:24

I would recommend defining four states for each block-group.

enum ROTATION {
    UP, DOWN, LEFT, RIGHT;

    ROTATION rotateLeft() {
        switch(this) {
             case UP: return LEFT;
             case LEFT: return DOWN;
             case DOWN: return RIGHT;
             case RIGHT: return UP;
        }
        return null; // wont happen;
    }

    ROTATION rotateRight() {
        ROTATION r = this;
         // wow I'm lazy, but I've actually seen this in production code!
        return r.rotateLeft().rotateLeft().rotateLeft();
    }
}

abstract class Brick {
    Point centerPos;
    ROTATION rot;
    abstract List<Point> pointsOccupied();
}

class TBrick extends Brick {

    List<Point> pointsOccupied() {
        int x = centerPos.x();
        int y = centerPos.y();
        List<Point> points = new LinkedList<Point>();
        switch(rot) {
            case UP: points.add(new Point(x-1,y);
                     points.add(new Point(x,y);
                     points.add(new Point(x+1,y);
                     points.add(new Point(x, y+1);
                break;
            case Down: points.add(new Point(x-1,y);
                       points.add(new Point(x,y);
                       points.add(new Point(x+1,y);
                       points.add(new Point(x, y-1);
                break;
            // finish the cases
        }

   }

}

You can use a rotation matrix.

You will need to set the origin of your rotation appropriately, which may mean translating the location of the piece with respect to the playing field (such that the origin is in the centre, for example), applying the rotation matrix and then translating it back to its correct location on the playing field coordinates.

The easiest and computational fastest way to do this, would to use precompute them.

That means a tetris piece will look like

class TetrisBlock {

   String position[4];

   int curPos = 0;

   void rotateLeft() {
      curPos++;
      if (curPos > 3)
        curPos = 0;
   }
....
}

And then you could define something like

class TetrisTBlock extends TetrisBlock { 

...

// in constructor
position={"....\n.T..\nTTT.\n....",
          ".T..\nTT..\n.T..\n.....", 
// I guess you get the idea

...

You do this for every type of block and then you can also add members for adding/removing them from the board.

If you optimize you would go away from the chars....

I think the best way is to hard-code it. Take into consideration that each figure is different and each of the figure's rotation phase is also different. And for each rotation phase - determine which parts of the grid you need to be free (avoid collision). For a visual representation check this

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!