A stealth-based 2D platformer where you don't have to kill anyone unless you want to. https://www.semicolin.games
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

53 lines
1.5 KiB

  1. using System;
  2. namespace SemiColinGames {
  3. // A History is a queue of fixed length N that records the N most recent items Add()ed to it.
  4. // The mostly-recently-added item is found at index 0; the least-recently-added item is at index
  5. // N-1. Items older than the History's size are automatically dropped. The underlying
  6. // implementation is a fixed-size circular array; insertion and access are O(1).
  7. //
  8. // Example:
  9. // h = new History<int>(3);
  10. // h.Add(2); h.Add(3); h.Add(5);
  11. // Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 5 3 2
  12. // h.Add(7);
  13. // Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 7 5 3
  14. // h.Add(11); h.Add(13);
  15. // Console.WriteLine("{0} {1} {2}", h[0], h[1], h[2]); // 13 11 7
  16. public class History<T> {
  17. // Backing store for the History's items.
  18. private readonly T[] items;
  19. // Points at the most-recently-inserted item.
  20. private int idx = 0;
  21. public History(int length) {
  22. items = new T[length];
  23. }
  24. public void Add(T item) {
  25. idx++;
  26. if (idx >= items.Length) {
  27. idx -= items.Length;
  28. }
  29. items[idx] = item;
  30. }
  31. public int Length {
  32. get => items.Length;
  33. }
  34. public T this[int age] {
  35. get {
  36. if (age < 0 || age >= items.Length) {
  37. throw new IndexOutOfRangeException();
  38. }
  39. int lookup = idx - age;
  40. if (lookup < 0) {
  41. lookup += items.Length;
  42. }
  43. return items[lookup];
  44. }
  45. }
  46. }
  47. }