You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

Game.cs 3.4 kB

3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using Grpc.Core;
  2. using Protobuf;
  3. using System.Threading;
  4. using Timothy.FrameRateTask;
  5. using System;
  6. using System.Net.Http.Headers;
  7. namespace Server
  8. {
  9. public class Game
  10. {
  11. private const int gameTime = 3000;
  12. public int GameTime => gameTime;
  13. private MessageToClient gameInfo = new();
  14. private object gameInfoLock = new();
  15. private int isGaming = 0;
  16. public bool IsGaming
  17. {
  18. get => Interlocked.CompareExchange(ref isGaming, 0, 0) != 0;
  19. set => Interlocked.Exchange(ref isGaming, value ? 1 : 0);
  20. }
  21. public MessageToClient GetCopiedGameInfo()
  22. {
  23. lock (gameInfoLock)
  24. {
  25. return gameInfo.Clone();
  26. }
  27. }
  28. public void AddPlayer(PlayerMsg player)
  29. {
  30. lock (gameInfoLock)
  31. {
  32. if (player.PlayerType == PlayerType.NullPlayerType)
  33. return;
  34. if (player.PlayerType == PlayerType.HumanPlayer)
  35. {
  36. gameInfo.HumanMessage.Add(new MessageOfHuman()
  37. {
  38. PlayerId = player.PlayerId
  39. });
  40. return;
  41. }
  42. if (player.PlayerType == PlayerType.ButcherPlayer)
  43. {
  44. gameInfo.ButcherMessage.Add(new MessageOfButcher()
  45. {
  46. PlayerID = player.PlayerId
  47. });
  48. return;
  49. }
  50. }
  51. }
  52. public SemaphoreSlim StartGame()
  53. {
  54. IsGaming = true;
  55. var waitHandle = new SemaphoreSlim(0);
  56. new Thread
  57. (
  58. () =>
  59. {
  60. new FrameRateTaskExecutor<int>
  61. (
  62. () => IsGaming,
  63. () =>
  64. {
  65. lock (gameInfo)
  66. {
  67. for (int i = 0; i < gameInfo.HumanMessage.Count; i++)
  68. {
  69. if (gameInfo.HumanMessage[i] != null)
  70. {
  71. gameInfo.HumanMessage[i].X++;
  72. gameInfo.HumanMessage[i].Y--;
  73. }
  74. }
  75. for (int i = 0; i < gameInfo.ButcherMessage.Count; i++)
  76. {
  77. if (gameInfo.ButcherMessage[i] != null)
  78. {
  79. gameInfo.ButcherMessage[i].X--;
  80. gameInfo.ButcherMessage[i].Y++;
  81. }
  82. }
  83. }
  84. },
  85. 100,
  86. () =>
  87. {
  88. IsGaming = false;
  89. waitHandle.Release();
  90. return 0;
  91. },
  92. gameTime
  93. ).Start();
  94. }
  95. )
  96. { IsBackground = true }.Start();
  97. return waitHandle;
  98. }
  99. }
  100. }