From 1c5a6a462afef130b31129ad8f8786831899290d Mon Sep 17 00:00:00 2001 From: Kaj Forney Date: Mon, 1 Nov 2021 02:39:09 -0600 Subject: [PATCH] Better algorithm for randomizing tetromino shapes. --- Assets/Scripts/tetrominoSpawnManager.cs | 65 ++++++++++++++----------- 1 file changed, 37 insertions(+), 28 deletions(-) diff --git a/Assets/Scripts/tetrominoSpawnManager.cs b/Assets/Scripts/tetrominoSpawnManager.cs index 1e69997..aace34a 100644 --- a/Assets/Scripts/tetrominoSpawnManager.cs +++ b/Assets/Scripts/tetrominoSpawnManager.cs @@ -1,3 +1,4 @@ +using System; using UnityEngine; using Random = UnityEngine.Random; @@ -15,38 +16,46 @@ public class tetrominoSpawnManager : MonoBehaviour private int nextTetromino = 0; private GameObject nextTetrominoObject; + private GameObject[] nextTetrominoSequence = new GameObject[14]; + + public void Start() + { + nextTetrominoSequence = new GameObject[14] + { + tetrominoL, tetrominoL, + tetrominoLine, tetrominoLine, + tetrominoR, tetrominoR, + tetrominoS, tetrominoS, + tetrominoSquare, tetrominoSquare, + tetrominoT, tetrominoT, + tetrominoZ, tetrominoZ + }; + + Shuffle(nextTetrominoSequence); + } + public void spawnTetromino() { - nextTetromino = Random.Range(1, 7); - switch (nextTetromino) + Instantiate(nextTetrominoSequence[nextTetromino], spawnPoint, Quaternion.identity); + + nextTetromino++; + + if (nextTetromino == 14) { - case 0: //Square - nextTetrominoObject = tetrominoSquare; - break; - case 1: //Line - nextTetrominoObject = tetrominoLine; - break; - case 2: //T-piece - nextTetrominoObject = tetrominoT; - break; - case 3: //L-piece - nextTetrominoObject = tetrominoL; - break; - case 4: //R-piece - nextTetrominoObject = tetrominoR; - break; - case 5: //S-piece - nextTetrominoObject = tetrominoS; - break; - case 6: //Z-piece - nextTetrominoObject = tetrominoZ; - break; - default: //if it's not a piece I have a prefab for yet, default to square - nextTetrominoObject = tetrominoSquare; - break; + nextTetromino = 0; + Shuffle(nextTetrominoSequence); } - Instantiate(nextTetrominoObject, spawnPoint, Quaternion.identity); - + } + + //an algorithm for shuffling arrays, taken from https://stackoverflow.com/questions/36702548/shuffle-array-in-unity + void Shuffle(GameObject[] array) + { + int p = array.Length; + for (int n = p - 1; n > 0; n--) + { + int r = Random.Range(0, n); + (array[r], array[n]) = (array[n], array[r]); + } } }