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