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