|
| 1 | +/** |
| 2 | + * These functions are responsible for generating "fair" "random" tetrominos. |
| 3 | + * It is making sure that an 'I' tetromino comes at least every 12th round and |
| 4 | + * that a maximum of four 'S' and 'Z' tetriminos can be spawned consecutively. |
| 5 | + */ |
| 6 | + |
| 7 | +var g_numTetros = []; |
| 8 | +var g_prevQueue = []; |
| 9 | + |
| 10 | +resetRandomSystem(); |
| 11 | + |
| 12 | +/** |
| 13 | + * Resets the queue and tetromino count array. |
| 14 | + */ |
| 15 | +function resetRandomSystem() { |
| 16 | + g_numTetros = [0, 0, 0, 0, 0, 0, 0]; |
| 17 | + g_prevQueue.splice(0, g_prevQueue.length); |
| 18 | +} |
| 19 | + |
| 20 | +/** |
| 21 | + * Returns a new "random" tetromino and updates the queue. |
| 22 | + */ |
| 23 | +function getRandomTetromino() { |
| 24 | + var newTetromino; |
| 25 | + var len = g_prevQueue.length; |
| 26 | + |
| 27 | + if (g_numTetros[0] == 0 && len == 12) { |
| 28 | + // Make sure that we at least get one I each 12th time. |
| 29 | + newTetromino = 0; |
| 30 | + } else if (len >= 4 |
| 31 | + && g_prevQueue[len-1] == g_prevQueue[len-2] |
| 32 | + && g_prevQueue[len-2] == g_prevQueue[len-3] |
| 33 | + && g_prevQueue[len-3] == g_prevQueue[len-4] |
| 34 | + && g_prevQueue[len-4] >= 5) { |
| 35 | + // If the four last tetriminos were 'S' or 'Z', spawn something else. |
| 36 | + newTetromino = Math.floor(Math.random() * 5); |
| 37 | + } else { |
| 38 | + newTetromino = Math.floor(Math.random() * 7); |
| 39 | + } |
| 40 | + pushTetromino(newTetromino); |
| 41 | + return newTetromino; |
| 42 | +} |
| 43 | + |
| 44 | +/** |
| 45 | + * Pushes a tetromino into the queue and updates g_numTetros to hold the |
| 46 | + * correct number of instances of the tetromino in the queue. |
| 47 | + */ |
| 48 | +function pushTetromino(tetromino) { |
| 49 | + g_numTetros[tetromino]++; |
| 50 | + // If the array is larger than 12, we remove the oldest element. |
| 51 | + if (g_prevQueue.length == 12) { |
| 52 | + g_numTetros[g_prevQueue[0]]--; |
| 53 | + g_prevQueue.shift(); |
| 54 | + } |
| 55 | + g_prevQueue.push(tetromino); |
| 56 | +} |
0 commit comments