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.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. using Microsoft.Extensions.Options;
  2. using System.IO.Pipes;
  3. using System.Threading;
  4. using uqac_ia_aspirobot.Extensions;
  5. using uqac_ia_aspirobot.Interfaces;
  6. namespace uqac_ia_aspirobot.Common
  7. {
  8. public class ArServer
  9. {
  10. private readonly IEnvironment _environment;
  11. public enum ArCommands
  12. {
  13. EnvGetWidth,
  14. EnvGetHeight,
  15. RoomGetState,
  16. RoomRemoveDust,
  17. RoomRemoveJewel
  18. }
  19. private readonly ArConfig _options;
  20. private Thread[] _servers;
  21. public ArServer(IOptions<ArConfig> options, IEnvironment environment)
  22. {
  23. _environment = environment;
  24. _options = options.Value;
  25. }
  26. public void Setup()
  27. {
  28. _servers = new Thread[_options.ServerThreadCount];
  29. for (var i = 0; i < _servers.Length; i++)
  30. {
  31. _servers[i] = new Thread(ServerThread)
  32. {
  33. Name = $"ArServer-{i}"
  34. };
  35. _servers[i].Start();
  36. }
  37. }
  38. private void ServerThread()
  39. {
  40. var server = new NamedPipeServerStream(_options.PipeName, PipeDirection.InOut, _servers.Length);
  41. server.WaitForConnection();
  42. var stream = new ArStreamString(server);
  43. while (true)
  44. {
  45. var command = stream.ReadEnum<ArCommands>();
  46. if (command == ArCommands.EnvGetWidth)
  47. {
  48. stream.Write(_environment.GetWidth());
  49. }
  50. else if (command == ArCommands.EnvGetHeight)
  51. {
  52. stream.Write(_environment.GetHeight());
  53. }
  54. else if (command == ArCommands.RoomGetState)
  55. {
  56. var x = stream.ReadInt();
  57. var y = stream.ReadInt();
  58. stream.Write(_environment.GetRoomState(x, y));
  59. }
  60. else if (command == ArCommands.RoomRemoveDust)
  61. {
  62. var x = stream.ReadInt();
  63. var y = stream.ReadInt();
  64. _environment.GetRoom(x, y).RemoveDust();
  65. }
  66. else if (command == ArCommands.RoomRemoveJewel)
  67. {
  68. var x = stream.ReadInt();
  69. var y = stream.ReadInt();
  70. _environment.GetRoom(x, y).RemoveJewel();
  71. }
  72. }
  73. }
  74. }
  75. }