Search⌘ K
AI Features

Randomizers

Explore how to use JavaScript's Math methods to build randomizers for tetromino selection in Tetris. Understand basic randomization, history checks, the TGM randomizer, and the 7-bag method to reduce piece repetition and improve gameplay fairness. This lesson helps you implement various randomizer strategies to enhance your game's logic and unpredictability.

To have more colors than only a blue tetromino in our game, we need to add more pieces to our code.

Following the Super Rotation System, we can take the first position of the pieces and add them to the constants and their colors:

Javascript (babel-node)
const COLORS = [
'cyan',
'blue',
'orange',
'yellow',
'green',
'purple',
'red'
];
const SHAPES = [
[
[0, 0, 0, 0],
[1, 1, 1, 1],
[0, 0, 0, 0],
[0, 0, 0, 0]
],
[
[2, 0, 0],
[2, 2, 2],
[0, 0, 0]
],
// And so on
];

Basic randomizer

To randomly pick one of the tetrominoes, we can use Math, a built-in object in JavaScript that includes a couple of static methods to help us with our calculations:

  • Math.random() returns a floating-point number in the range 0 to less than 1
...