Why updating sand simulation in grid doesn't work?

I want to make a falling sand simulation using cellular automata, but when I update it, nothing happens, and when I want to do a line of diffrent material using lineDrawing() this material appear in random cells. This is update code:


void update()
{
  for (int i = verticalNumberOfCells - 1; i > 0; i--)
  {
    for (int j = 0; j < horizontalNumberOfCells; j++)
    {
      world[j][i].update(false);
    }
  }
 
  for (int y = verticalNumberOfCells - 1; y > 0; y--)
  {
    for (int x = 0; x < horizontalNumberOfCells; x++)
    {
      if (world[x][y].hasMoved) continue;
      if (world[x][y].state == 0 && world[x][y].state == 1) continue;
 
      if (canMove(world[x][y].state, x, y + 1)) 
      {
        move(x, y, x, y + 1);
      }
    }
  }
}

The auxiliary functions that I use to check if the contents of a cell can change and to change the contents of a cell look like this:


boolean canMove(int state, int positionX, int positionY)
{
  if (positionX < 0 || positionX >= horizontalNumberOfCells || positionY < 0 || positionY >= verticalNumberOfCells) return false;

  int otherSubstance = world[positionX][positionY].state;

  if (state == 5) return (otherSubstance == 4);

  if (otherSubstance == 0) return true;

  if (state == 2 && otherSubstance == 3 && random(1f) < 0.5f) return true;

  return false;
}

void move(int fromX, int fromY, int toX, int toY) 
{
  Cells otherSubstance = world[toX][toY];

  world[toX][toY] = world[fromX][fromY];
  world[fromX][fromY] = otherSubstance;
  world[fromX][fromY].hasMoved = true;
  world[toX][toY].hasMoved = true;

  world[fromX][fromY].velocityX = 0;
  world[fromX][fromY].velocityY = 0;

  if (toX > fromX) 
  { 
    world[toX][toY].velocityX = 1;
  } else if (toX < fromX) 
  { 
    world[toX][toY].velocityX = -1;
  } else 
  { 
    world[toX][toY].velocityX = 0;
  }

  if (toY > fromY) 
  { 
    world[toX][toY].velocityY = 1;
  } else if (toY < fromY) 
  { 
    world[toX][toY].velocityY = -1;
  } else 
  { 
    world[toX][toY].velocityY = 0;
  }
}

I don’t know what’s wrong or why nothing works.

Sounds like an interesting project, but could you post the entire code so people can try and find problems? Also you should elaborate a bit more on what you mean by “nothing happens” (does the window open / does anything show up on the canvas) and what is the expected result.

I was able to fix this problem. The thing was, copying a cell in the move function didn’t work. Here is the wrong version of the code:

  Cells otherSubstance = world[toX][toY];

  world[toX][toY] = world[fromX][fromY];
  world[fromX][fromY] = otherSubstance;

and here is right version of the code:

  int oldState = world[toX][toY].state;

  world[toX][toY].state = world[fromX][fromY].state;
  world[fromX][fromY].state = oldState;