Just some helper method on the GridLevel
that would take in some delgate method and traverse the grid and apply the method that was handed to it?
You could do that if you want, why not? I wrote an IterateGrid
method in the GridSystem
class that yields the grid objects for me
public IEnumerable<(GridPosition position, TGridObject obj)> IterateGrid()
{
for (var x = 0; x < Width; x++)
{
for(var y = 0; y < Height; y++)
{
var position = new GridPosition(x, y);
yield return (position: position, obj: GetGridObject(position));
}
}
}
You could do something similar, but pass in a delegate and return nothing.
(PS: I wrote this on the fly. I can’t find the code where I did this, but it’s something like that)
Indeed, having some iterator could work just as well
You mean something like JavaScript’s map function?
In GridSystem.cs
public void Map(System.Action<TGridObject> action)
{
foreach (TGridObject gridObject in gridObjectArray)
{
if(gridObject==null) continue;
action?.Invoke(gridObject);
}
}
Since Arrays implement iterators even if they are 2 (or even 3) dimensional, you can iterate over them with foreach just like a one dimensional array. The above example takes in a method with the appropriate object that was used for the generic… so in the case of Pathfinding, Pathfinding’s GridSystem.Map would take in any method that had Pathnode as the parameter.
Useage example: (in Pathfinding.cs)
private void ClearPathNodeInformation()
{
// for (int x = 0; x < gridSystem.GetWidth(); x++)
// {
// for (int z = 0; z < gridSystem.GetHeight(); z++)
// {
// GridPosition gridPosition = new GridPosition(x, z);
// PathNode pathNode = gridSystem.GetGridObject(gridPosition);
//
// pathNode.SetGCost(int.MaxValue);
// pathNode.SetHCost(0);
// pathNode.CalculateFCost();
// pathNode.ResetCameFromPathNode();
// }
// }
gridSystem.Map(node =>
{
node.SetGCost(int.MaxValue);
node.SetHCost(0);
node.CalculateFCost();
node.ResetCameFromPathNode();
});
}
I left the original to show that we’re doing the same thing in Map as we would be with the nested for loop. I made the method anonymous, but the compilier implicitly makes this anonymous method an action that takes in a PathNode, which of course is that node just before the =>.
Actually, map
for currying functions is way older than JavaScript
I know, it was the first one that came to mind. It’s actually surprising that Map isn’t built into the language.
Of course, there are ways of doing this via Linq as well.
With some slight adjustment, you could actually rewrite that Map function to work on any collection as an extension method.
This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.