WasteAgent.cs 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace MultiAgentSystemPCL
  5. {
  6. public class WasteAgent : ObjectInWorld
  7. {
  8. protected const double STEP = 3;
  9. protected const double CHANGE_DIRECTION_PROB = 0.05;
  10. protected Waste load = null;
  11. protected double speedX;
  12. protected double speedY;
  13. protected WasteEnvironment env;
  14. protected bool busy = false;
  15. public WasteAgent(double _posX, double _posY, WasteEnvironment _env)
  16. {
  17. PosX = _posX;
  18. PosY = _posY;
  19. env = _env;
  20. speedX = env.randomGenerator.NextDouble() - 0.5;
  21. speedY = env.randomGenerator.NextDouble() - 0.5;
  22. Normalize();
  23. }
  24. private void Normalize()
  25. {
  26. double length = Math.Sqrt(speedX * speedX + speedY * speedY);
  27. speedX = speedX / length;
  28. speedY = speedY / length;
  29. }
  30. public void UpdatePosition(double _maxWidth, double _maxHeight) {
  31. PosX += STEP * speedX;
  32. PosY += STEP * speedY;
  33. if (PosX < 0)
  34. {
  35. PosX = 0;
  36. }
  37. if (PosY < 0)
  38. {
  39. PosY = 0;
  40. }
  41. if (PosX > _maxWidth)
  42. {
  43. PosX = _maxWidth;
  44. }
  45. if (PosY > _maxHeight)
  46. {
  47. PosY = _maxHeight;
  48. }
  49. }
  50. internal void UpdateDirection(List<Waste> _wasteList)
  51. {
  52. // Où aller ?
  53. List<Waste> inZone = _wasteList.Where(x => DistanceTo(x) < x.Zone).OrderBy(x => DistanceTo(x)).ToList();
  54. Waste goal;
  55. if (load == null)
  56. {
  57. goal = inZone.FirstOrDefault();
  58. }
  59. else
  60. {
  61. goal = inZone.Where(x => x.Type == load.Type).FirstOrDefault();
  62. }
  63. // Avons-nous un but ?
  64. if (goal == null || busy)
  65. {
  66. // Pas de but, se déplacer aléatoirement
  67. if (env.randomGenerator.NextDouble() < CHANGE_DIRECTION_PROB)
  68. {
  69. speedX = env.randomGenerator.NextDouble() - 0.5;
  70. speedY = env.randomGenerator.NextDouble() - 0.5;
  71. }
  72. if (busy && goal == null)
  73. {
  74. busy = false;
  75. }
  76. }
  77. else
  78. {
  79. // Aller au but
  80. speedX = goal.PosX - PosX;
  81. speedY = goal.PosY - PosY;
  82. // But atteint ? Prendre ou déposer une charge
  83. if (DistanceTo(goal) < STEP)
  84. {
  85. if (load == null)
  86. {
  87. if (env.randomGenerator.NextDouble() < goal.ProbaToTake())
  88. {
  89. load = env.TakeWaste(goal);
  90. }
  91. }
  92. else
  93. {
  94. env.SetWaste(goal);
  95. load = null;
  96. }
  97. busy = true;
  98. }
  99. }
  100. Normalize();
  101. }
  102. public bool isLoaded()
  103. {
  104. return load != null;
  105. }
  106. }
  107. }