Skip to content
TheChatArchiveThe Chat Archive
o1-mini-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

using System.Collections; using System.Collections.Generic; using UnityEngine; using…

  1. User

    using System.Collections; using System.Collections.Generic; using UnityEngine; using TMPro; using UnityEngine.UI;

    public class TetrisBlock : MonoBehaviour { public Vector3 rotationPoint; private float previousTime; public float fallTime = 0.8f; public static int height = 23; public static int width = 10; private static Transform[,] grid = new Transform[width, height]; public TMP_Text Lines_Cleared; public static int LinesCleared;

    public int linesPerLevel = 10;
    public float fallTimeDecrease = 0.2f;
    public float minFallTime = 0.1f;
    private int level = 0;
    
    
    void Start()
    {
    
    
    }
    
    void Update()
    {
        LevelUp();
        if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
        {
            transform.position += new Vector3(-1, 0, 0);
            if(!ValidMove())
                transform.position -= new Vector3(-1, 0, 0);
        }
        else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
        {
            transform.position += new Vector3(1, 0, 0);
            if (!ValidMove())
                transform.position -= new Vector3(1, 0, 0);
        }
        else if (Input.GetKeyDown(KeyCode.X))
        {
            transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0,0,1), 90);
            if (!ValidMove())
                transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0, 0, 1), -90);
        }
    
    
        if (Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S) ? fallTime / 10 : fallTime))
        {
            transform.position += new Vector3(0, -1, 0);
            if (!ValidMove())
            {
                transform.position -= new Vector3(0, -1, 0);
                AddToGrid();
                CheckForLines();
    
                this.enabled = false;
                FindObjectOfType<SpawnTetromino>().NewTetromino();
    
            }
            previousTime = Time.time;
        }
    }
    
    void CheckForLines()
    {
        for (int i = height-1; i >= 0; i--)
        {
            if(HasLine(i))
            {
                LinesCleared++;
                DeleteLine(i);
                RowDown(i);
                UpdateUi();
            }
        }
    }
    
    bool HasLine(int i)
    {
        for(int j = 0; j< width; j++)
        {
            if (grid[j, i] == null)
                return false;
        }
    
        return true;
    }
    
    void DeleteLine(int i)
    {
        for (int j = 0; j < width; j++)
        {
            Destroy(grid[j, i].gameObject);
            grid[j, i] = null;
        }
    }
    
    void RowDown(int i)
    {
        for (int y = i; y < height; y++)
        {
            for (int j = 0; j < width; j++)
            {
                if(grid[j,y] != null)
                {
                    grid[j, y - 1] = grid[j, y];
                    grid[j, y] = null;
                    grid[j, y - 1].transform.position -= new Vector3(0, 1, 0);
                }
            }
        }
    }
    
    
    
    
    void AddToGrid()
    {
        foreach (Transform children in transform)
        {
            int roundedX = Mathf.RoundToInt(children.transform.position.x);
            int roundedY = Mathf.RoundToInt(children.transform.position.y);
    
            grid[roundedX, roundedY] = children;
        }
    }
    
    bool ValidMove()
    {
        foreach (Transform children in transform)
        {
            int roundedX = Mathf.RoundToInt(children.transform.position.x);
            int roundedY = Mathf.RoundToInt(children.transform.position.y);
    
            if(roundedX < 0 || roundedX >= width || roundedY < 0 ||roundedY >= height)
            {
                return false;
            }
    
            if (grid[roundedX, roundedY] != null)
                return false;
        }
    
        return true;
    }
    
    public static void UpdateUi()
    {
        TMP_Text linesClearedText = GameObject.Find("Lines_Cleared").GetComponent<TextMeshProUGUI>();
        linesClearedText.text = "Lines Cleared: " + LinesCleared.ToString();
        Debug.Log(linesClearedText.text);
    }
    
    void LevelUp()
    {
        int newLevel = LinesCleared / linesPerLevel;
        
        if (newLevel > level)
        {
            level = newLevel;
            
            fallTime = Mathf.Max(fallTime - fallTimeDecrease, minFallTime);
    
            Debug.Log("Level Up! Level: " + level + " | New Fall Time: " + fallTime);
        }
    }
    

    }

    
    fix the issue where it changes speed only after clearing 10 lines and when reaching the next 10 lines cleared it doesn't decrease the speed by 0.2f
    
  2. Assistant

    The issue you're encountering stems from the order in which the LevelUp() method is called relative to when LinesCleared is updated. Currently, LevelUp() is invoked at the beginning of the Update() method, which means it checks the level before any new lines have been cleared and LinesCleared has been incremented. As a result, the level only updates after the first set of lines is cleared and doesn't respond to subsequent multiples of 10 lines.

    To fix this, you should call LevelUp() after LinesCleared has been updated. This ensures the level is checked and updated after new lines are cleared, allowing the game to respond appropriately as more lines are cleared (e.g., 10, 20, 30, etc.).

    Here's how you can implement this fix:

    Step-by-Step Solution

    1. Remove LevelUp() from the Update() Method:

      Currently, LevelUp() is called at the start of the Update() method. Remove this call to prevent it from checking the level before any new lines are cleared.

      void Update()
      {
          // Remove or comment out the LevelUp() call here
          // LevelUp();
      
          // ... rest of your existing Update logic
      }
      
    2. Call LevelUp() After Clearing Lines:

      Move the LevelUp() call to after the CheckForLines() method within the Update() method. This ensures that the level is checked after lines have been cleared and LinesCleared has been incremented.

      void Update()
      {
          // ... existing input and movement handling
      
          if (Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S) ? fallTime / 10 : fallTime))
          {
              transform.position += new Vector3(0, -1, 0);
              if (!ValidMove())
              {
                  transform.position -= new Vector3(0, -1, 0);
                  AddToGrid();
                  CheckForLines();
      
                  // Call LevelUp() here after lines have been checked and cleared
                  LevelUp();
      
                  this.enabled = false;
                  FindObjectOfType<SpawnTetromino>().NewTetromino();
              }
              previousTime = Time.time;
          }
      }
      
    3. Optionally, Move LevelUp() Inside CheckForLines():

      For better encapsulation and to ensure that LevelUp() is always called whenever lines are checked and potentially cleared, you can move the LevelUp() call directly inside the CheckForLines() method.

      void CheckForLines()
      {
          for (int i = height - 1; i >= 0; i--)
          {
              if (HasLine(i))
              {
                  LinesCleared++;
                  DeleteLine(i);
                  RowDown(i);
                  UpdateUi();
      
                  // Call LevelUp() after incrementing LinesCleared
                  LevelUp();
              }
          }
      }
      

      If you choose this approach, ensure that you remove the LevelUp() call from the Update() method as well to avoid redundant calls.

    4. Ensure LevelUp() Handles Multiple Level Increments:

      The current LevelUp() method calculates newLevel based on the total LinesCleared. This means if multiple levels are cleared at once (e.g., going from level 1 to level 3 by clearing 20 lines), LevelUp() should correctly handle it. However, ensure that the logic inside LevelUp() is robust enough to handle such scenarios.

      void LevelUp()
      {
          int newLevel = LinesCleared / linesPerLevel;
      
          if (newLevel > level)
          {
              level = newLevel;
      
              // Decrease fallTime appropriately, ensuring it doesn't go below minFallTime
              fallTime = Mathf.Max(fallTime - fallTimeDecrease * (newLevel - level), minFallTime);
      
              Debug.Log("Level Up! Level: " + level + " | New Fall Time: " + fallTime);
          }
      }
      

      Note: The current implementation decreases fallTime by a fixed fallTimeDecrease value each time a new level is reached. If you want to account for multiple levels being skipped at once, you might need to adjust the decrement accordingly.

    Final Updated Script

    Here's the updated version of your script with the recommended changes:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using TMPro;
    using UnityEngine.UI;
    
    public class TetrisBlock : MonoBehaviour
    {
        public Vector3 rotationPoint;
        private float previousTime;
        public float fallTime = 0.8f;
        public static int height = 23;
        public static int width = 10;
        private static Transform[,] grid = new Transform[width, height];
        public TMP_Text Lines_Cleared;
        public static int LinesCleared;
    
        public int linesPerLevel = 10;
        public float fallTimeDecrease = 0.2f;
        public float minFallTime = 0.1f;
        private int level = 0;
    
    
        void Start()
        {
    
    
        }
    
        void Update()
        {
            // Removed LevelUp() from here
    
            if(Input.GetKeyDown(KeyCode.LeftArrow) || Input.GetKeyDown(KeyCode.A))
            {
                transform.position += new Vector3(-1, 0, 0);
                if(!ValidMove())
                    transform.position -= new Vector3(-1, 0, 0);
            }
            else if (Input.GetKeyDown(KeyCode.RightArrow) || Input.GetKeyDown(KeyCode.D))
            {
                transform.position += new Vector3(1, 0, 0);
                if (!ValidMove())
                    transform.position -= new Vector3(1, 0, 0);
            }
            else if (Input.GetKeyDown(KeyCode.X))
            {
                transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0,0,1), 90);
                if (!ValidMove())
                    transform.RotateAround(transform.TransformPoint(rotationPoint), new Vector3(0, 0, 1), -90);
            }
    
    
            if (Time.time - previousTime > (Input.GetKey(KeyCode.DownArrow) || Input.GetKeyDown(KeyCode.S) ? fallTime / 10 : fallTime))
            {
                transform.position += new Vector3(0, -1, 0);
                if (!ValidMove())
                {
                    transform.position -= new Vector3(0, -1, 0);
                    AddToGrid();
                    CheckForLines();
    
                    // Call LevelUp() after lines are checked and potentially cleared
                    LevelUp();
    
                    this.enabled = false;
                    FindObjectOfType<SpawnTetromino>().NewTetromino();
    
                }
                previousTime = Time.time;
            }
        }
    
        void CheckForLines()
        {
            for (int i = height-1; i >= 0; i--)
            {
                if(HasLine(i))
                {
                    LinesCleared++;
                    DeleteLine(i);
                    RowDown(i);
                    UpdateUi();
    
                    // Optionally, call LevelUp() here instead of in Update
                    // LevelUp();
                }
            }
        }
    
        bool HasLine(int i)
        {
            for(int j = 0; j< width; j++)
            {
                if (grid[j, i] == null)
                    return false;
            }
    
            return true;
        }
    
        void DeleteLine(int i)
        {
            for (int j = 0; j < width; j++)
            {
                Destroy(grid[j, i].gameObject);
                grid[j, i] = null;
            }
        }
    
        void RowDown(int i)
        {
            for (int y = i; y < height; y++)
            {
                for (int j = 0; j < width; j++)
                {
                    if(grid[j,y] != null)
                    {
                        grid[j, y - 1] = grid[j, y];
                        grid[j, y] = null;
                        grid[j, y - 1].transform.position -= new Vector3(0, 1, 0);
                    }
                }
            }
        }
    
    
    
        void AddToGrid()
        {
            foreach (Transform children in transform)
            {
                int roundedX = Mathf.RoundToInt(children.transform.position.x);
                int roundedY = Mathf.RoundToInt(children.transform.position.y);
    
                grid[roundedX, roundedY] = children;
            }
        }
    
        bool ValidMove()
        {
            foreach (Transform children in transform)
            {
                int roundedX = Mathf.RoundToInt(children.transform.position.x);
                int roundedY = Mathf.RoundToInt(children.transform.position.y);
    
                if(roundedX < 0 || roundedX >= width || roundedY < 0 ||roundedY >= height)
                {
                    return false;
                }
    
                if (grid[roundedX, roundedY] != null)
                    return false;
            }
    
            return true;
        }
    
        public static void UpdateUi()
        {
            TMP_Text linesClearedText = GameObject.Find("Lines_Cleared").GetComponent<TextMeshProUGUI>();
            linesClearedText.text = "Lines Cleared: " + LinesCleared.ToString();
            Debug.Log(linesClearedText.text);
        }
    
        void LevelUp()
        {
            int newLevel = LinesCleared / linesPerLevel;
            
            if (newLevel > level)
            {
                level = newLevel;
                
                fallTime = Mathf.Max(fallTime - fallTimeDecrease, minFallTime);
    
                Debug.Log("Level Up! Level: " + level + " | New Fall Time: " + fallTime);
            }
        }
    }
    

    Additional Recommendations

    • Optimize UI Updates: Continuously using GameObject.Find in UpdateUi() can be inefficient. Consider caching the reference to Lines_Cleared in the Start() method to improve performance.

      private TMP_Text linesClearedText;
      
      void Start()
      {
          linesClearedText = GameObject.Find("Lines_Cleared").GetComponent<TextMeshProUGUI>();
      }
      
      public static void UpdateUi()
      {
          // If 'linesClearedText' is not static, adjust accordingly
          // For example, make UpdateUi non-static or pass the reference
          // Here's a non-static approach:
          linesClearedText.text = "Lines Cleared: " + LinesCleared.ToString();
          Debug.Log(linesClearedText.text);
      }
      
    • Handle Multiple Line Clears: If multiple lines are cleared at once, ensure that LevelUp() handles multiple level increments correctly. The current implementation should handle it gracefully as it calculates newLevel based on the total LinesCleared.

    • Ensure Thread Safety: If your game becomes more complex, consider thread safety, especially when dealing with static variables like LinesCleared.

    By making these adjustments, your Tetris game should correctly decrease the fallTime by 0.2f each time another set of 10 lines is cleared, allowing the game to increase in speed progressively as the player clears more lines.