Files
Shogi/PathFinding/PlanarCollection.cs

62 lines
1.5 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
namespace PathFinding
{
// TODO: Get rid of this thing in favor of T[,] multi-dimensional array with extension methods.
public class PlanarCollection<T> : IPlanarCollection<T>, IEnumerable<T> where T : IPlanarElement
{
public delegate void ForEachDelegate(T element, int x, int y);
private readonly T?[] array;
private readonly int width;
private readonly int height;
public PlanarCollection(int width, int height)
{
this.width = width;
this.height = height;
array = new T[width * height];
}
public T? this[int y, int x]
{
get => array[y * width + x];
set => array[y * width + x] = value;
}
public T? this[float y, float x]
{
get => array[(int)y * width + (int)x];
set => array[(int)y * width + (int)x] = value;
}
public int GetLength(int dimension) => dimension switch
{
0 => height,
1 => width,
_ => throw new IndexOutOfRangeException()
};
public void ForEachNotNull(ForEachDelegate callback)
{
for (var x = 0; x < width; x++)
{
for (var y = 0; y < height; y++)
{
var elem = this[y, x];
if (elem != null)
callback(elem, x, y);
}
}
}
public IEnumerator<T> GetEnumerator()
{
foreach (var item in array)
if (item != null) yield return item;
}
IEnumerator IEnumerable.GetEnumerator() => array.GetEnumerator();
}
}