Workshop › Tetris-style Blocks › Step 17 of 32
Instead of always the T, spawn() puts a copy of a random shape at the top of the well, centred.
```js
let piece
function randomShape() {
return SHAPES[Math.floor(Math.random() * SHAPES.length)].map((row) => [...row])
}
function spawn() {
const shape = randomShape()
piece = { shape, x: Math.floor((COLS - shape.length) / 2), y: 0 }
}
spawn()
requestAnimationFrame(loop)
```Math.random() gives a number from 0 up to (not including) 1; times 7 and rounded down with Math.floor, it is a
whole number 0 to 6: a random index into SHAPES.(COLS - shape.length) / 2 centres the matrix; Math.floor rounds it down to a whole column.{ shape, x, y } is short for { shape: shape, ... }.spawn() at the bottom makes the first piece.let piece = ... to just let piece.// Clockwise... comment write randomShape and spawn.spawn() above requestAnimationFrame(loop).Skills: Game states
← Falling by itself Land and lock →