using System; using System.Collections.Generic; using UnityEngine; namespace DiamondArrow { internal static class EndlessLevels { static readonly Vector2Int[] Directions = { Vector2Int.right, Vector2Int.up, Vector2Int.left, Vector2Int.down }; public static LevelData Generate(int number, LevelData lastConfigured) { var random = new System.Random(unchecked(number * 16777619)); int size = lastConfigured.size; var arrows = BuildBoard(size, random); // A second layout helps keep sparse boards near the density of the campaign. if (arrows.Length < size * size / 4) { var alternate = BuildBoard(size, random); if (alternate.Length > arrows.Length) arrows = alternate; } int seconds = Mathf.RoundToInt((float)lastConfigured.seconds * arrows.Length / lastConfigured.arrows.Length); return new LevelData { number = number, size = size, seconds = Math.Max(30, seconds), arrows = arrows }; } static ArrowData[] BuildBoard(int size, System.Random random) { var occupied = new bool[size, size]; var arrows = new List(); // Each candidate encodes one head cell and facing. Newly placed arrows can // only block earlier ones, so reverse placement order always solves the board. var candidates = new int[size * size * Directions.Length]; for (int i = 0; i < candidates.Length; i++) candidates[i] = i; for (int count = candidates.Length; count > 0; count--) { int pick = random.Next(count); int candidate = candidates[pick]; candidates[pick] = candidates[count - 1]; int cell = candidate / 4; var head = new Vector2Int(cell % size, cell / size); int facing = candidate % 4; var direction = Directions[facing]; var tail = head - direction; if (occupied[head.x, head.y] || !Inside(tail, size) || occupied[tail.x, tail.y]) continue; if (!ClearExit(head, direction, size, occupied)) continue; var path = new List { new Cell(head.x, head.y), new Cell(tail.x, tail.y) }; occupied[head.x, head.y] = occupied[tail.x, tail.y] = true; int length = random.Next(2, 6); while (path.Count < length) { int start = random.Next(4); bool extended = false; for (int d = 0; d < 4; d++) { var next = tail + Directions[(start + d) % 4]; if (!Inside(next, size) || occupied[next.x, next.y]) continue; if ((next.x - head.x) * direction.x + (next.y - head.y) * direction.y > 0) continue; occupied[next.x, next.y] = true; path.Add(new Cell(next.x, next.y)); tail = next; extended = true; break; } if (!extended) break; } path.Reverse(); arrows.Add(new ArrowData { cells = path.ToArray() }); } return arrows.ToArray(); } static bool Inside(Vector2Int p, int size) => p.x >= 0 && p.x < size && p.y >= 0 && p.y < size; static bool ClearExit(Vector2Int head, Vector2Int direction, int size, bool[,] occupied) { for (var p = head + direction; Inside(p, size); p += direction) if (occupied[p.x, p.y]) return false; return true; } } }