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