📜 ⬆️ ⬇️

Javascript Tetris (in 30+ lines)

I decided to support the topic!
image
Tetris in 30+ lines of js code.

jsfiddle link

Principle of operation.

1. Get the figures
All figures are stored in the variable fs = "1111: 01 | 01 | 01 | 01 * 011 | 110: 010 | 011 | 001 * ..." as a string. To get an array of figures, we do split ('*'), then each figure has from 1st (for "stick") to 4 (for L, T and "pyramid") states (so that they can be turned over) - they are separated by ":" - respectively, to get one state - split (':'). Suppose we received a “pyramid” - “010 | 111”, here we do split ('|') - and we get the final two-dimensional array for one state of one shape. "0" - empty space (no need to draw), "1" - you need to draw.

2. All movement of the figures is done by two functions - “erase the figure” and “try to build.”
For any movement to the left or right or down, or even to reversing a figure, first erase the current displayed figure, then try to build a figure in a new place - if you build one of the squares, it climbs over the edge of the “glass”, or there is a filled square from the previous figures - we erase the “active figure”, and we stand at the previous place.
')
3. Movements are done from the keyboard. The timer simply calls the function that handles keystrokes from the keypad with the DOWN button code. With each timeout call, the time to the call decreases.

4. If you could not move the figure down - it means that it rested against the previous figures or the bottom. In this case, check if there are any filled rows, and draw a new shape at the top of the glass. If at the top of the glass to draw a figure failed - the game is over!

Source: https://habr.com/ru/post/202628/


All Articles