The task of arranging the figures in the Tetris game

    I decided to give the Habrasociety a small task in finding and implementing a better algorithm. Everyone knows the Tetris game. Imagine that a computer is playing this game in your place. So, the task will be to describe an algorithm that will correctly place the figures, so that there are no empty spaces. I made a simple UI on JSFiddle to test the algorithm. All you need to do is implement one function. But wait, I’ll explain the rules first.

    I decided so far not to make a full analog of Tetris, since I need to start small, then perhaps more people will be able to test themselves. So, simplifications of our tetris:

    • Only 2 figures: 1x4 and 2x2
    • Field Size: 10x20
    • 2 positions - vertical and horizontal
    • You can not rotate the figures
    • Figures appear randomly, randomly rotated. You need to find the best place for her


    There is one empty function in the code (more precisely, now it returns some random number) - getColumnNumberForLeftFigureSquare (w, h). You will need to implement it. w is the width of the new figure, h is the height. In total, you can use 3 variables: w, h and cols. cols is an array of 10 elements. Each element is a column, the value is the occupied column height. The function must return an integer from 1 to 10 inclusive. This will be the number of the column into which the leftmost cell of the figure will fall.

    In total, there are 200 cells in this tetris, i.e. you can test your algorithm by the number of remaining to be filled (displayed in the UI)

    Fork the forddle and post in the comments. Any attempt will be appreciated. Ideally, the solution should be as efficient and productive as possible. Then we can improve the tetris to the original.

    Once again, a link to JSFiddle

    PS If you see errors in the UI itself - let me know.

    Also popular now: