Tetris Piece Rotation Algorithm

前端 未结 15 783
傲寒
傲寒 2020-11-30 17:57

What are the best algorithms (and explanations) for representing and rotating the pieces of a tetris game? I always find the piece rotation and representation schemes confu

相关标签:
15条回答
  • 2020-11-30 18:05

    for 3x3 sized tetris pieces flip x and y of your piece then swap the outer columns that's what I figured out some time

    0 讨论(0)
  • 2020-11-30 18:07

    Since there are only 4 possible orientations for each shape, why not use an array of states for the shape and rotating CW or CCW simply increments or decrements the index of the shape state (with wraparound for the index)? I would think that might be quicker than performing rotation calculations and whatnot.

    0 讨论(0)
  • 2020-11-30 18:09

    You can rotate a matrix only by applying mathematical operations to it. If you have a matrix, say:

    Mat A = [1,1,1]
            [0,0,1]
            [0,0,0]
    

    To rotate it, multiply it by its transpose and then by this matrix ([I]dentity [H]orizontaly [M]irrored):

    IHM(A) = [0,0,1]
             [0,1,0]
             [1,0,0]
    

    Then you'll have:

    Mat Rotation = Trn(A)*IHM(A) = [1,0,0]*[0,0,1] = [0,0,1]
                                   [1,0,0] [0,1,0] = [0,0,1]
                                   [1,1,0] [1,0,0] = [0,1,1]
    

    Note: Center of rotation will be the center of the matrix, in this case at (2,2).

    0 讨论(0)
  • 2020-11-30 18:10

    In Ruby, at least, you can actually use matrices. Represent your piece shapes as nested arrays of arrays like [[0,1],[0,2],[0,3]]

    require 'matrix'
    shape = shape.map{|arr|(Matrix[arr] * Matrix[[0,-1],[1,0]]).to_a.flatten}
    

    However, I agree that hard-coding the shapes is feasible since there are 7 shapes and 4 states for each = 28 lines and it will never be any more than that.

    For more on this see my blog post at https://content.pivotal.io/blog/the-simplest-thing-that-could-possibly-work-in-tetris and a completely working implementation (with minor bugs) at https://github.com/andrewfader/Tetronimo

    0 讨论(0)
  • 2020-11-30 18:12

    Personally I've always just represented the rotations by hand - with very few shapes, it's easy to code that way. Basically I had (as pseudo-code)

    class Shape
    {
        Color color;
        ShapeRotation[] rotations;
    }
    
    class ShapeRotation
    {
        Point[4] points;
    }
    
    class Point
    {
        int x, y;
    }
    

    At least conceptually - a multi-dimensional array of points directly in shape would do the trick too :)

    0 讨论(0)
  • 2020-11-30 18:12

    If you're doing this in python, cell-based instead of coordinate pairs it's very simple to rotate a nested list.

    rotate = lambda tetrad: zip(*tetrad[::-1])
    
    # S Tetrad
    tetrad = rotate([[0,0,0,0], [0,0,0,0], [0,1,1,0], [1,1,0,0]])
    
    0 讨论(0)
提交回复
热议问题