using System; using System.Collections; using System.Collections.Generic; namespace Gameboard.ShogiUI.BoardState { public class Array2D : IEnumerable { /// False to stop iterating. public delegate void ForEachDelegate(T element, int x, int y); private readonly T[] array; private readonly int width; private readonly int height; public Array2D(int width, int height) { this.width = width; this.height = height; array = new T[width * height]; } public T this[int x, int y] { get => array[y * width + x]; set => array[y * width + x] = value; } public void ForEach(ForEachDelegate callback) { for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { callback(this[x, y], x, y); } } } public void ForEachNotNull(ForEachDelegate callback) { for (var x = 0; x < width; x++) { for (var y = 0; y < height; y++) { if (this[x, y] != null) callback(this[x, y], x, y); } } } // TODO: Figure out a better return type, or make this class specific to ShogiBoard. public BoardVector IndexOf(Predicate predicate) { for (var x = 0; x < width; x++) for (var y = 0; y < height; y++) { if (this[x, y] != null && predicate(this[x, y])) { return new BoardVector(x, y); } } return null; } public IEnumerator GetEnumerator() { foreach (var item in array) yield return item; } IEnumerator IEnumerable.GetEnumerator() => array.GetEnumerator(); } }