C
C#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
}
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
SL
Sherbert Lemon397d ago
I could pass a func into it, which it runs in there, but I don't know if it would be that clean to do so I should have really simplified it to this so it is easier to read
// do a few lines of starter stuff which is always the same

for (;;)
{
// do calculations which are always the same

// do stuff which changes from function to function
}
// do a few lines of starter stuff which is always the same

for (;;)
{
// do calculations which are always the same

// do stuff which changes from function to function
}
A
Accord396d ago
Looks like nothing has happened here. I will mark this as stale and this post will be archived until there is new activity.