UnitComponent.cs 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using Common.Base;
  5. using MongoDB.Bson;
  6. namespace Model
  7. {
  8. public class UnitComponent: Component<World>
  9. {
  10. private readonly Dictionary<ObjectId, Unit> units = new Dictionary<ObjectId, Unit>();
  11. private readonly Dictionary<int, Dictionary<ObjectId, Unit>> typeUnits =
  12. new Dictionary<int, Dictionary<ObjectId, Unit>>();
  13. public void Add(Unit unit)
  14. {
  15. this.units.Add(unit.Id, unit);
  16. if (!this.typeUnits.ContainsKey(unit.Config.Type))
  17. {
  18. this.typeUnits.Add(unit.Config.Type, new Dictionary<ObjectId, Unit>());
  19. }
  20. this.typeUnits[unit.Config.Type].Add(unit.Id, unit);
  21. }
  22. public Unit Get(ObjectId id)
  23. {
  24. Unit unit = null;
  25. this.units.TryGetValue(id, out unit);
  26. return unit;
  27. }
  28. public Unit[] GetOneType(int type)
  29. {
  30. Dictionary<ObjectId, Unit> oneTypeUnits = null;
  31. if (!this.typeUnits.TryGetValue(type, out oneTypeUnits))
  32. {
  33. return new Unit[0];
  34. }
  35. return oneTypeUnits.Values.ToArray();
  36. }
  37. public bool Remove(Unit unit)
  38. {
  39. if (unit == null)
  40. {
  41. throw new ArgumentNullException(nameof(unit));
  42. }
  43. if (!this.units.Remove(unit.Id))
  44. {
  45. return false;
  46. }
  47. if (!this.typeUnits[unit.Config.Type].Remove(unit.Id))
  48. {
  49. return false;
  50. }
  51. return true;
  52. }
  53. public bool Remove(ObjectId id)
  54. {
  55. Unit unit = this.Get(id);
  56. if (unit == null)
  57. {
  58. return false;
  59. }
  60. return this.Remove(unit);
  61. }
  62. }
  63. }