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.

GameServer.cs 14 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
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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. using Gaming;
  8. using GameClass.GameObj;
  9. using Preparation.Utility;
  10. using Playback;
  11. using Newtonsoft.Json;
  12. using Newtonsoft.Json.Linq;
  13. using Preparation.Interface;
  14. namespace Server
  15. {
  16. public partial class GameServer : AvailableService.AvailableServiceBase
  17. {
  18. private Dictionary<long, (SemaphoreSlim, SemaphoreSlim)> semaDict = new();
  19. private object semaDictLock = new();
  20. protected readonly ArgumentOptions options;
  21. private HttpSender? httpSender;
  22. private object gameLock = new();
  23. private MessageToClient currentGameInfo = new();
  24. private MessageOfObj currentMapMsg = new();
  25. private object newsLock = new();
  26. private List<MessageOfNews> currentNews = new();
  27. private SemaphoreSlim endGameSem = new(0);
  28. protected readonly Game game;
  29. private uint spectatorMinPlayerID = 2023;
  30. private List<uint> spectatorList = new List<uint>();
  31. public int playerNum;
  32. public int TeamCount => options.TeamCount;
  33. protected long[] communicationToGameID; // 通信用的ID映射到游戏内的ID,通信中0-3为Student,4为Tricker
  34. private readonly object messageToAllClientsLock = new();
  35. public static readonly long SendMessageToClientIntervalInMilliseconds = 50;
  36. private MessageWriter? mwr = null;
  37. public void StartGame()
  38. {
  39. if (game.GameMap.Timer.IsGaming) return;
  40. /*foreach (var id in communicationToGameID)
  41. {
  42. if (id == GameObj.invalidID) return; //如果有未初始化的玩家,不开始游戏
  43. }*/ //测试时人数不够
  44. Console.WriteLine("Game starts!");
  45. game.StartGame((int)options.GameTimeInSecond * 1000);
  46. Thread.Sleep(1);
  47. new Thread(() =>
  48. {
  49. bool flag = true;
  50. new FrameRateTaskExecutor<int>
  51. (
  52. () => game.GameMap.Timer.IsGaming,
  53. () =>
  54. {
  55. if (flag == true)
  56. {
  57. game.AllPlayerUsePassiveSkill();
  58. ReportGame(GameState.GameStart);
  59. flag = false;
  60. }
  61. else ReportGame(GameState.GameRunning);
  62. },
  63. SendMessageToClientIntervalInMilliseconds,
  64. () =>
  65. {
  66. ReportGame(GameState.GameEnd); // 最后发一次消息,唤醒发消息的线程,防止发消息的线程由于有概率处在 Wait 状态而卡住
  67. OnGameEnd();
  68. return 0;
  69. }
  70. ).Start();
  71. })
  72. { IsBackground = true }.Start();
  73. }
  74. public void WaitForEnd()
  75. {
  76. this.endGameSem.Wait();
  77. mwr?.Dispose();
  78. }
  79. private void SaveGameResult(string path)
  80. {
  81. Dictionary<string, int> result = new Dictionary<string, int>();
  82. int[] score = GetScore();
  83. result.Add("Student", score[0]);
  84. result.Add("Tricker", score[1]);
  85. JsonSerializer serializer = new JsonSerializer();
  86. using (StreamWriter sw = new StreamWriter(path))
  87. {
  88. using (JsonWriter writer = new JsonTextWriter(sw))
  89. {
  90. serializer.Serialize(writer, result);
  91. }
  92. }
  93. }
  94. protected virtual void SendGameResult() // 天梯的 Server 给网站发消息记录比赛结果
  95. {
  96. var scores = new JObject[options.TeamCount];
  97. int[] score = GetScore();
  98. scores[0] = new JObject { ["team_name"] = "Student", ["score"] = score[0] };
  99. scores[1] = new JObject { ["team_name"] = "Tricker", ["score"] = score[1] };
  100. httpSender?.SendHttpRequest
  101. (
  102. new JObject
  103. {
  104. ["result"] = new JArray(scores)
  105. }
  106. );
  107. }
  108. private void OnGameEnd()
  109. {
  110. game.ClearAllLists();
  111. mwr?.Flush();
  112. if (options.ResultFileName != DefaultArgumentOptions.FileName)
  113. SaveGameResult(options.ResultFileName + ".json");
  114. SendGameResult();
  115. this.endGameSem.Release();
  116. }
  117. public void ReportGame(GameState gameState, bool requiredGaming = true)
  118. {
  119. var gameObjList = game.GetGameObj();
  120. currentGameInfo = new();
  121. lock (messageToAllClientsLock)
  122. {
  123. switch (gameState)
  124. {
  125. case GameState.GameRunning:
  126. case GameState.GameEnd:
  127. case GameState.GameStart:
  128. if (gameState == GameState.GameStart || IsSpectatorJoin)
  129. {
  130. currentGameInfo.ObjMessage.Add(currentMapMsg);
  131. IsSpectatorJoin = false;
  132. }
  133. foreach (GameObj gameObj in gameObjList)
  134. {
  135. MessageOfObj? msg = CopyInfo.Auto(gameObj);
  136. if (msg != null) currentGameInfo.ObjMessage.Add(CopyInfo.Auto(gameObj));
  137. }
  138. lock (newsLock)
  139. {
  140. foreach (var news in currentNews)
  141. {
  142. MessageOfObj? msg = CopyInfo.Auto(news);
  143. if (msg != null) currentGameInfo.ObjMessage.Add(CopyInfo.Auto(news));
  144. }
  145. currentNews.Clear();
  146. }
  147. currentGameInfo.GameState = gameState;
  148. currentGameInfo.AllMessage = GetMessageOfAll();
  149. mwr?.WriteOne(currentGameInfo);
  150. break;
  151. default:
  152. break;
  153. }
  154. }
  155. foreach (var kvp in semaDict)
  156. {
  157. kvp.Value.Item1.Release();
  158. }
  159. foreach (var kvp in semaDict)
  160. {
  161. kvp.Value.Item2.Wait();
  162. }
  163. }
  164. public int[] GetScore()
  165. {
  166. int[] score = new int[2]; // 0代表Student,1代表Tricker
  167. game.GameMap.GameObjLockDict[GameObjType.Character].EnterReadLock();
  168. try
  169. {
  170. foreach (Character character in game.GameMap.GameObjDict[GameObjType.Character])
  171. {
  172. if (!character.IsGhost()) score[0] += character.Score;
  173. else score[1] += character.Score;
  174. }
  175. }
  176. finally
  177. {
  178. game.GameMap.GameObjLockDict[GameObjType.Character].ExitReadLock();
  179. }
  180. return score;
  181. }
  182. private int PlayerIDToTeamID(long playerID)
  183. {
  184. if (0 <= playerID && playerID < options.StudentCount) return 0;
  185. if (options.MaxStudentCount <= playerID && playerID < options.MaxStudentCount + options.TrickerCount) return 1;
  186. return -1;
  187. }
  188. private int PlayerTypeToTeamID(Protobuf.PlayerType playerType)
  189. {
  190. if (playerType == PlayerType.StudentPlayer) return 0;
  191. if (playerType == PlayerType.TrickerPlayer) return 1;
  192. return -1;
  193. }
  194. private uint GetBirthPointIdx(long playerID) // 获取出生点位置
  195. {
  196. return (uint)playerID + 1; // ID从0-4,出生点从1-5
  197. }
  198. private bool ValidPlayerID(long playerID)
  199. {
  200. if ((0 <= playerID && playerID < options.StudentCount) || (options.MaxStudentCount <= playerID && playerID < options.MaxStudentCount + options.TrickerCount))
  201. return true;
  202. return false;
  203. }
  204. private MessageOfAll GetMessageOfAll()
  205. {
  206. MessageOfAll msg = new MessageOfAll();
  207. msg.GameTime = game.GameMap.Timer.nowTime();
  208. msg.SubjectFinished = (int)game.GameMap.NumOfRepairedGenerators;
  209. msg.StudentGraduated = (int)game.GameMap.NumOfEscapedStudent;
  210. msg.StudentQuited = (int)game.GameMap.NumOfDeceasedStudent;
  211. int[] score = GetScore();
  212. msg.StudentScore = score[0];
  213. msg.TrickerScore = score[1];
  214. //msg.GateOpened
  215. //msg.HiddenGateRefreshed
  216. //msg.HiddenGateOpened
  217. return msg;
  218. }
  219. private Protobuf.PlaceType IntToPlaceType(uint n)
  220. {
  221. switch (n)
  222. {
  223. case 0:
  224. case 1:
  225. case 2:
  226. case 3:
  227. case 4:
  228. case 5:
  229. return Protobuf.PlaceType.Land;
  230. case 6: return Protobuf.PlaceType.Wall;
  231. case 7: return Protobuf.PlaceType.Grass;
  232. case 8: return Protobuf.PlaceType.Classroom;
  233. case 9: return Protobuf.PlaceType.Gate;
  234. case 10: return Protobuf.PlaceType.HiddenGate;
  235. case 11: return Protobuf.PlaceType.Window;
  236. case 12: return Protobuf.PlaceType.Door3;
  237. case 13: return Protobuf.PlaceType.Door5;
  238. case 14: return Protobuf.PlaceType.Door6;
  239. case 15: return Protobuf.PlaceType.Chest;
  240. default: return Protobuf.PlaceType.NullPlaceType;
  241. }
  242. }
  243. private MessageOfObj MapMsg(uint[,] map)
  244. {
  245. MessageOfObj msgOfMap = new();
  246. msgOfMap.MapMessage = new();
  247. for (int i = 0; i < GameData.rows; i++)
  248. {
  249. msgOfMap.MapMessage.Row.Add(new MessageOfMap.Types.Row());
  250. for (int j = 0; j < GameData.cols; j++)
  251. {
  252. msgOfMap.MapMessage.Row[i].Col.Add(IntToPlaceType(map[i, j]));
  253. }
  254. }
  255. return msgOfMap;
  256. }
  257. public GameServer(ArgumentOptions options)
  258. {
  259. this.options = options;
  260. if (options.mapResource == DefaultArgumentOptions.MapResource)
  261. this.game = new Game(MapInfo.defaultMap, options.TeamCount);
  262. else
  263. {
  264. uint[,] map = new uint[GameData.rows, GameData.cols];
  265. try
  266. {
  267. string? line;
  268. int i = 0, j = 0;
  269. using (StreamReader sr = new StreamReader(options.mapResource))
  270. {
  271. while (!sr.EndOfStream && i < GameData.rows)
  272. {
  273. if ((line = sr.ReadLine()) != null)
  274. {
  275. string[] nums = line.Split(' ');
  276. foreach (string item in nums)
  277. {
  278. if (item.Length > 1)//以兼容原方案
  279. {
  280. map[i, j] = (uint)int.Parse(item);
  281. }
  282. else
  283. {
  284. //2022-04-22 by LHR 十六进制编码地图方案(防止地图编辑员瞎眼x
  285. map[i, j] = (uint)Preparation.Utility.MapEncoder.Hex2Dec(char.Parse(item));
  286. }
  287. j++;
  288. if (j >= GameData.cols)
  289. {
  290. j = 0;
  291. break;
  292. }
  293. }
  294. i++;
  295. }
  296. }
  297. }
  298. }
  299. catch
  300. {
  301. map = MapInfo.defaultMap;
  302. }
  303. finally { this.game = new Game(map, options.TeamCount); }
  304. }
  305. playerNum = options.StudentCount + options.TrickerCount;
  306. currentMapMsg = MapMsg(game.GameMap.ProtoGameMap);
  307. communicationToGameID = new long[options.MaxStudentCount + options.TrickerCount];
  308. //创建server时先设定待加入人物都是invalid
  309. for (int i = 0; i < communicationToGameID.GetLength(0); i++)
  310. {
  311. communicationToGameID[i] = GameObj.invalidID;
  312. }
  313. if (options.FileName != DefaultArgumentOptions.FileName)
  314. {
  315. try
  316. {
  317. mwr = new MessageWriter(options.FileName, options.TeamCount, options.StudentCount);
  318. }
  319. catch
  320. {
  321. Console.WriteLine($"Error: Cannot create the playback file: {options.FileName}!");
  322. }
  323. }
  324. if (options.Url != DefaultArgumentOptions.Url && options.Token != DefaultArgumentOptions.Token)
  325. {
  326. this.httpSender = new HttpSender(options.Url, options.Token, "PUT");
  327. }
  328. }
  329. }
  330. }