PossibleCombinationBuilder.cs 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using UnityEngine;
  5. using UnityEngine.Assertions;
  6. namespace JTFold
  7. {
  8. [RequireComponent(typeof(Paper))]
  9. public class PossibleCombinationBuilder : MonoBehaviour
  10. {
  11. [SerializeField] private CombinationSequence[] _sequence;
  12. public bool Used => _sequence.Length != 0;
  13. private void OnValidate()
  14. {
  15. GetComponent<Paper>().Builder = this;
  16. }
  17. public bool IsCorrect(IEnumerable<Folding> combination)
  18. {
  19. var from = 0;
  20. foreach (CombinationSequence sequence in _sequence)
  21. {
  22. var researched = combination.Skip(from).Take(sequence.Length);
  23. from += sequence.Length;
  24. switch (sequence.Type)
  25. {
  26. case MatchType.Sequentially:
  27. if (MatchSequentially(sequence, researched) == false)
  28. return false;
  29. break;
  30. case MatchType.AnyOrder:
  31. if (MatchAnyOrder(sequence, researched) == false)
  32. return false;
  33. break;
  34. }
  35. }
  36. return true;
  37. }
  38. private bool MatchAnyOrder(CombinationSequence expected, IEnumerable<Folding> actual)
  39. {
  40. Assert.AreEqual(expected.Length, actual.Count());
  41. var actualFoldings = new List<Folding>(actual);
  42. foreach (var expectedFolding in expected.Foldings)
  43. {
  44. if (actualFoldings.Contains(expectedFolding) == false)
  45. {
  46. return false;
  47. }
  48. actualFoldings.Remove(expectedFolding);
  49. }
  50. return true;
  51. }
  52. private bool MatchSequentially(CombinationSequence expected, IEnumerable<Folding> actual)
  53. {
  54. Assert.AreEqual(expected.Length, actual.Count());
  55. var expectedArray = expected.Foldings.ToArray();
  56. var actualArray = actual.ToArray();
  57. for (int i = 0; i < expected.Length; i++)
  58. {
  59. if (expectedArray[i] != actualArray[i])
  60. {
  61. return false;
  62. }
  63. }
  64. return true;
  65. }
  66. }
  67. [Serializable]
  68. public class CombinationSequence
  69. {
  70. public MatchType Type;
  71. public Folding[] Foldings;
  72. public int Length => Foldings.Length;
  73. }
  74. public enum MatchType
  75. {
  76. AnyOrder,
  77. Sequentially
  78. }
  79. }