C#C
C#3y ago
3 replies
Sherbert Lemon

❔ How do I refactor this?

I am working with a grid of tiles, each tile has an int, which is made up of 4 bytes which represent what value in an enum each side of the tile is in.

This means I have a lot of things that need to run after a few calculations are done in a loop of adjacent tiles

here is most of the repeated code
for (int i = 0; i < Adjacency.Length; i++)
{
  Vector2Int curr = Adjacency[i];
                
  Vector2Int position = curr + _tile;
                
  if (position.x >= width || position.y >= height || position.x < 0 || position.y < 0)
    continue;

  byte adjacentTileType = (byte)(_tiledata & (byte.MaxValue << (i * 8)));
                
  int oppositeSide = i + 2;
  oppositeSide = oppositeSide > 3 ? oppositeSide - 4 : oppositeSide;

  uint shiftedAdjacentTile = (uint)((int)adjacentTileType << (oppositeSide * 8));
  uint shiftedMask = (uint)(byte.MaxValue << (oppositeSide * 8));
                
  // one function would have stuff to update tiles based on these calculations, another to check if they are valid, some other ones will be added 
}


This seems like a problem that would be solved with a functional language, but how would I allow for a few functions reuse this portion of code, adding a new bit on the end without copying and pasting all the starting stuff
Was this page helpful?