Workshop › Tetris-style Blocks › Step 28 of 32
Fully random pieces are fair on average but not in the moment: sometimes the long I does not come for 30 turns. The 7-bag deals each of the seven pieces once, in a shuffled order, then shuffles a new bag.
```js
let bag
bag = []
// The "7-bag": deal all seven pieces in a random order, then shuffle a new bag.
function takeFromBag() {
if (bag.length === 0) {
bag = [0, 1, 2, 3, 4, 5, 6]
for (let i = bag.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[bag[i], bag[j]] = [bag[j], bag[i]]
}
}
return SHAPES[bag.pop()].map((row) => [...row])
}
const shape = takeFromBag()
```[a, b] = [b, a] swaps two values. The ; at the start keeps it from being read as part of the line above.bag.pop() takes the last number out of the bag; we return a copy of that shape.let piece write let bag; in newGame, under the board line, write bag = [].randomShape with the comment and takeFromBag.spawn, call takeFromBag() instead of randomShape().Skills: Arrays and objects, Game states
← Faster every level The next piece →