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