0

I am making Tetris in Java. I am having difficulty having my blocks shift down, once a row has been removed (because it filled up). My code is throwing an arrayIndexOutOfBounds error. The rest of the code works, where it finds which row is full and sets that row to 0. But in the if statement near the bottom, that's where it doesn't work. Thanks ! :)

// Removes any rows that are filled 
public static int removeRows() 
{
    // Variables
    int numOfRows = tetrisGrid.getNumOfRows(); 
    int numOfCols = tetrisGrid.getNumOfCols();
    int numRowsRemoved = 0;
    int [][] grid = tetrisGrid.getGrid();

    // Finds the number of rows that are filled 
    for (int row = 0; row < numOfRows; row++)
    {
      for (int col = 0; col < numOfCols; col++)
      {
        int blockValue = tetrisGrid.getBlockValue(row, col);

        if (blockValue == 0) 
        {
          break;
        }

        if (col == numOfCols - 1) 
        {
          numRowsRemoved++;

          // Sets the rows filled to zero
          for (int change = 0; change < numOfCols; change++)
          {
            grid [row][change] = 0; 
          }   

          // Shifts everything down until it hits blocks below
          for (int shiftRow = 0; shiftRow < 2; shiftRow++)
          {
            for (int shiftCol = 0; shiftCol < numOfCols; shiftCol++)
            {
              if (blockValue == 1)
              {
                grid [row][col] = 0;
                row++;
                col++;
                grid [row][col] = 1;   
                row--;
                col--; 
              }
              else if (blockValue == 0)
                break;

            }
          }

          // TAKE OUT -------------------------
          System.out.println ("--------"); 
          tetrisGrid.printGrid(); 
          System.out.println ("--------");
          // -------------------------
        } 
      }
    }  
    tetrisGrid.setGrid(grid);
    return numRowsRemoved; 
  } 
sara
  • 1
  • 2
    Have you tried using a debugger? – Tim Biegeleisen May 29 '17 at 03:32
  • When you write `row++;` then `col++;`, you could be moving those indices outside of the grid. It's no surprise that `grid [row][col] = 1;` would then throw an exception. – Dawood ibn Kareem May 29 '17 at 03:34
  • Can you explain this line: shiftRow < 2; in for loop why 2? – Fady Saad May 29 '17 at 03:36
  • When I played with Tetris, I didn't use a 2D Array. Instead I used an ArrayList to hold a 1D Array. Then when you remove a row, you just remove the row from the ArrayList and add an empty row at the start of the ArrayList. This way you don't have to worry about shifting all the data every time a row is removed. For a basic working example you can check out: https://stackoverflow.com/questions/42517544/adding-additional-shapes-in-a-tetris-project-loop-logic-assistance/42518798#42518798 – camickr May 29 '17 at 03:42

0 Answers0