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 18 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
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
3 years ago
3 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466
  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. namespace Server
  14. {
  15. public class GameServer : AvailableService.AvailableServiceBase
  16. {
  17. private Dictionary<long, (SemaphoreSlim, SemaphoreSlim)> semaDict = new();
  18. protected readonly ArgumentOptions options;
  19. private HttpSender? httpSender;
  20. private object gameLock = new();
  21. private object[] teamCommunicationLock;
  22. private const int playerNum = 1; // 注意修改
  23. private MessageToClient currentGameInfo = new();
  24. private MessageOfMap currentMapMsg = new();
  25. private Queue<MsgRes>[] teamCommunicatonMsg;
  26. private SemaphoreSlim endGameSem = new(0);
  27. protected readonly Game game;
  28. private uint spectatorMinPlayerID = 2022;
  29. private List<uint> spectatorList = new List<uint>();
  30. public int TeamCount => options.TeamCount;
  31. protected long[] communicationToGameID; // 通信用的ID映射到游戏内的ID,通信中0-3为Student,4为Tricker
  32. private readonly object messageToAllClientsLock = new();
  33. public static readonly long SendMessageToClientIntervalInMilliseconds = 50;
  34. private readonly Semaphore endGameInfoSema = new(0, 1);
  35. private MessageWriter? mwr = null;
  36. public void StartGame()
  37. {
  38. if (game.GameMap.Timer.IsGaming) return;
  39. /*foreach (var id in communicationToGameID)
  40. {
  41. if (id == GameObj.invalidID) return; //如果有未初始化的玩家,不开始游戏
  42. }*/ //测试时人数不够
  43. Console.WriteLine("Game starts!");
  44. game.StartGame((int)options.GameTimeInSecond * 1000);
  45. Thread.Sleep(1);
  46. new Thread(() =>
  47. {
  48. bool flag = true;
  49. new FrameRateTaskExecutor<int>
  50. (
  51. () => game.GameMap.Timer.IsGaming,
  52. () =>
  53. {
  54. if (flag == true)
  55. {
  56. ReportGame(GameState.GameStart);
  57. flag = false;
  58. }
  59. else ReportGame(GameState.GameRunning);
  60. },
  61. SendMessageToClientIntervalInMilliseconds,
  62. () =>
  63. {
  64. ReportGame(GameState.GameEnd); // 最后发一次消息,唤醒发消息的线程,防止发消息的线程由于有概率处在 Wait 状态而卡住
  65. OnGameEnd();
  66. return 0;
  67. }
  68. ).Start();
  69. })
  70. { IsBackground = true }.Start();
  71. }
  72. public void WaitForEnd()
  73. {
  74. this.endGameSem.Wait();
  75. mwr?.Dispose();
  76. }
  77. private void SaveGameResult(string path)
  78. {
  79. Dictionary<string, int> result = new Dictionary<string, int>();
  80. for (int i = 0; i < TeamCount; i++)
  81. {
  82. result.Add("Team" + i.ToString(), GetTeamScore(i)); //Team待修改
  83. }
  84. JsonSerializer serializer = new JsonSerializer();
  85. using (StreamWriter sw = new StreamWriter(path))
  86. {
  87. using (JsonWriter writer = new JsonTextWriter(sw))
  88. {
  89. serializer.Serialize(writer, result);
  90. }
  91. }
  92. }
  93. protected virtual void SendGameResult() // 天梯的 Server 给网站发消息记录比赛结果
  94. {
  95. var scores = new JObject[options.TeamCount];
  96. for (ushort i = 0; i < options.TeamCount; ++i)
  97. {
  98. scores[i] = new JObject { ["team_id"] = i.ToString(), ["score"] = GetTeamScore(i) };
  99. } // Team待修改
  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. endGameInfoSema.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. //currentGameInfo.MapMessage = (Message(game.GameMap));
  124. switch (gameState)
  125. {
  126. case GameState.GameRunning:
  127. case GameState.GameStart:
  128. case GameState.GameEnd:
  129. foreach (GameObj gameObj in gameObjList)
  130. {
  131. currentGameInfo.ObjMessage.Add(CopyInfo.Auto(gameObj));
  132. }
  133. currentGameInfo.GameState = gameState;
  134. currentGameInfo.AllMessage = new(); // 还没写
  135. mwr?.WriteOne(currentGameInfo);
  136. break;
  137. default:
  138. break;
  139. }
  140. }
  141. foreach (var kvp in semaDict)
  142. {
  143. kvp.Value.Item1.Release();
  144. }
  145. foreach (var kvp in semaDict)
  146. {
  147. kvp.Value.Item2.Wait();
  148. }
  149. }
  150. public int GetTeamScore(long teamID)
  151. {
  152. return game.GetTeamScore(teamID);
  153. }
  154. private int PlayerIDToTeamID(long playerID)
  155. {
  156. if (0 <= playerID && playerID < options.PlayerCountPerTeam) return 0;
  157. if (playerID == options.PlayerCountPerTeam) return 1;
  158. return -1;
  159. }
  160. private uint GetBirthPointIdx(long playerID) // 获取出生点位置
  161. {
  162. return (uint)(playerID + 1); // ID从0-4,出生点从1-5
  163. }
  164. private bool ValidPlayerID(long playerID)
  165. {
  166. if (0 <= playerID && playerID < options.PlayerCountPerTeam + 1)
  167. return true;
  168. return false;
  169. }
  170. private Protobuf.PlaceType IntToPlaceType(uint n)
  171. {
  172. switch (n)
  173. {
  174. case 0: return Protobuf.PlaceType.Land;
  175. case 6: return Protobuf.PlaceType.Wall;
  176. case 7: return Protobuf.PlaceType.Grass;
  177. case 8: return Protobuf.PlaceType.Classroom;
  178. case 9: return Protobuf.PlaceType.Gate;
  179. case 10: return Protobuf.PlaceType.HiddenGate;
  180. case 11: return Protobuf.PlaceType.Window;
  181. case 12: return Protobuf.PlaceType.Door;
  182. case 13: return Protobuf.PlaceType.Chest;
  183. default: return Protobuf.PlaceType.NullPlaceType;
  184. }
  185. }
  186. private MessageOfMap MapMsg(uint[,] map)
  187. {
  188. MessageOfMap msgOfMap = new MessageOfMap();
  189. for (int i = 0; i < GameData.rows; i++)
  190. {
  191. msgOfMap.Row.Add(new MessageOfMap.Types.Row());
  192. for (int j = 0; j < GameData.cols; j++)
  193. {
  194. msgOfMap.Row[i].Col.Add(IntToPlaceType(map[i, j]));
  195. }
  196. }
  197. return msgOfMap;
  198. }
  199. public override Task<BoolRes> TryConnection(IDMsg request, ServerCallContext context)
  200. {
  201. Console.WriteLine($"TryConnection ID: {request.PlayerId}");
  202. var onConnection = new BoolRes();
  203. lock (gameLock)
  204. {
  205. if (0 <= request.PlayerId && request.PlayerId < playerNum) // 注意修改
  206. {
  207. onConnection.ActSuccess = true;
  208. Console.WriteLine(onConnection.ActSuccess);
  209. return Task.FromResult(onConnection);
  210. }
  211. }
  212. onConnection.ActSuccess = false;
  213. return Task.FromResult(onConnection);
  214. }
  215. protected readonly object addPlayerLock = new();
  216. public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter<MessageToClient> responseStream, ServerCallContext context)
  217. {
  218. Console.WriteLine($"AddPlayer: {request.PlayerId}");
  219. if (request.PlayerId >= spectatorMinPlayerID)
  220. {
  221. // 观战模式
  222. uint tp = (uint)request.PlayerId;
  223. if (!spectatorList.Contains(tp))
  224. {
  225. spectatorList.Add(tp);
  226. Console.WriteLine("A new spectator comes to watch this game.");
  227. }
  228. return;
  229. }
  230. if (game.GameMap.Timer.IsGaming)
  231. return;
  232. if (!ValidPlayerID(request.PlayerId)) //玩家id是否正确
  233. return;
  234. if (communicationToGameID[request.PlayerId] != GameObj.invalidID) //是否已经添加了该玩家
  235. return;
  236. Preparation.Utility.CharacterType characterType = Preparation.Utility.CharacterType.Athlete; // 待修改
  237. lock (addPlayerLock)
  238. {
  239. Game.PlayerInitInfo playerInitInfo = new(GetBirthPointIdx(request.PlayerId), PlayerIDToTeamID(request.PlayerId), request.PlayerId, characterType);
  240. long newPlayerID = game.AddPlayer(playerInitInfo);
  241. if (newPlayerID == GameObj.invalidID)
  242. return;
  243. communicationToGameID[request.PlayerId] = newPlayerID;
  244. // 内容待修改
  245. var temp = (new SemaphoreSlim(0, 1), new SemaphoreSlim(0, 1));
  246. bool start = false;
  247. Console.WriteLine($"Id: {request.PlayerId} joins.");
  248. lock (semaDict)
  249. {
  250. semaDict.Add(request.PlayerId, temp);
  251. start = semaDict.Count == playerNum;
  252. }
  253. if (start) StartGame();
  254. }
  255. do
  256. {
  257. semaDict[request.PlayerId].Item1.Wait();
  258. if (currentGameInfo != null)
  259. {
  260. await responseStream.WriteAsync(currentGameInfo);
  261. //Console.WriteLine("Send!");
  262. }
  263. semaDict[request.PlayerId].Item2.Release();
  264. } while (game.GameMap.Timer.IsGaming);
  265. }
  266. public override Task<BoolRes> Attack(AttackMsg request, ServerCallContext context)
  267. {
  268. var gameID = communicationToGameID[request.PlayerId];
  269. game.Attack(gameID, request.Angle);
  270. BoolRes boolRes = new();
  271. boolRes.ActSuccess = true;
  272. return Task.FromResult(boolRes);
  273. }
  274. public override Task<MoveRes> Move(MoveMsg request, ServerCallContext context)
  275. {
  276. #if DEBUG
  277. Console.WriteLine($"Move ID: {request.PlayerId}, TimeInMilliseconds: {request.TimeInMilliseconds}");
  278. #endif
  279. var gameID = communicationToGameID[request.PlayerId];
  280. game.MovePlayer(gameID, (int)request.TimeInMilliseconds, request.Angle);
  281. // 之后game.MovePlayer可能改为bool类型
  282. MoveRes moveRes = new();
  283. moveRes.ActSuccess = true;
  284. return Task.FromResult(moveRes);
  285. }
  286. public override Task<BoolRes> PickProp(PropMsg request, ServerCallContext context)
  287. {
  288. BoolRes boolRes = new();
  289. if (request.PropType == Protobuf.PropType.NullPropType)
  290. boolRes.ActSuccess = game.PickProp(request.PlayerId, Preparation.Utility.PropType.Null);
  291. // 待修改
  292. return Task.FromResult(boolRes);
  293. }
  294. public override Task<BoolRes> SendMessage(SendMsg request, ServerCallContext context)
  295. {
  296. var boolRes = new BoolRes();
  297. if (!ValidPlayerID(request.PlayerId) || !ValidPlayerID(request.ToPlayerId)
  298. || PlayerIDToTeamID(request.PlayerId) != PlayerIDToTeamID(request.ToPlayerId) || request.PlayerId == request.ToPlayerId)
  299. {
  300. boolRes.ActSuccess = false;
  301. return Task.FromResult(boolRes);
  302. }
  303. MsgRes msg = new();
  304. msg.HaveMessage = false;
  305. if (request.Message.Length > 256)
  306. {
  307. #if DEBUG
  308. Console.WriteLine("Message string is too long!");
  309. #endif
  310. boolRes.ActSuccess = false;
  311. return Task.FromResult(boolRes);
  312. }
  313. else
  314. {
  315. msg.HaveMessage = true;
  316. msg.FromPlayerId = request.PlayerId;
  317. msg.MessageReceived = request.Message;
  318. #if DEBUG
  319. Console.WriteLine(msg);
  320. #endif
  321. teamCommunicatonMsg[request.ToPlayerId].Enqueue(msg);
  322. }
  323. boolRes.ActSuccess = true;
  324. return Task.FromResult(boolRes);
  325. }
  326. public override Task GetMessage(IDMsg request, IServerStreamWriter<MsgRes> responseStream, ServerCallContext context)
  327. {
  328. if (!game.GameMap.Timer.IsGaming) return Task.CompletedTask;
  329. lock (teamCommunicationLock[request.PlayerId])
  330. {
  331. while (teamCommunicatonMsg[request.PlayerId].Count > 0)
  332. {
  333. responseStream.WriteAsync(teamCommunicatonMsg[request.PlayerId].Dequeue());
  334. }
  335. }
  336. return Task.CompletedTask;
  337. }
  338. public override Task<BoolRes> UseProp(PropMsg request, ServerCallContext context)
  339. {
  340. return base.UseProp(request, context);
  341. }
  342. public override Task<BoolRes> UseSkill(SkillMsg request, ServerCallContext context)
  343. {
  344. return base.UseSkill(request, context);
  345. }
  346. public override Task<BoolRes> Graduate(IDMsg request, ServerCallContext context)
  347. {
  348. return base.Graduate(request, context);
  349. }
  350. public override Task<BoolRes> StartRescueMate(IDMsg request, ServerCallContext context)
  351. {
  352. return base.StartRescueMate(request, context);
  353. }
  354. public override Task<BoolRes> StartTreatMate(IDMsg request, ServerCallContext context)
  355. {
  356. return base.StartTreatMate(request, context);
  357. }
  358. public override Task<BoolRes> StartLearning(IDMsg request, ServerCallContext context)
  359. {
  360. #if DEBUG
  361. Console.WriteLine($"StartLearning ID: {request.PlayerId}");
  362. #endif
  363. BoolRes boolRes = new();
  364. var gameID = communicationToGameID[request.PlayerId];
  365. boolRes.ActSuccess = game.Fix(gameID);
  366. return Task.FromResult(boolRes);
  367. }
  368. public GameServer(ArgumentOptions options)
  369. {
  370. this.options = options;
  371. //if (options.mapResource == DefaultArgumentOptions.MapResource)
  372. // this.game = new Game(MapInfo.defaultMap, options.TeamCount);
  373. //else
  374. {
  375. uint[,] map = new uint[GameData.rows, GameData.cols];
  376. try
  377. {
  378. string? line;
  379. int i = 0, j = 0;
  380. using (StreamReader sr = new StreamReader(options.mapResource))
  381. {
  382. while (!sr.EndOfStream && i < GameData.rows)
  383. {
  384. if ((line = sr.ReadLine()) != null)
  385. {
  386. string[] nums = line.Split(' ');
  387. foreach (string item in nums)
  388. {
  389. if (item.Length > 1)//以兼容原方案
  390. {
  391. map[i, j] = (uint)int.Parse(item);
  392. }
  393. else
  394. {
  395. //2022-04-22 by LHR 十六进制编码地图方案(防止地图编辑员瞎眼x
  396. map[i, j] = (uint)Preparation.Utility.MapEncoder.Hex2Dec(char.Parse(item));
  397. }
  398. j++;
  399. if (j >= GameData.cols)
  400. {
  401. j = 0;
  402. break;
  403. }
  404. }
  405. i++;
  406. }
  407. }
  408. }
  409. }
  410. catch
  411. {
  412. map = MapInfo.defaultMap;
  413. }
  414. finally { this.game = new Game(map, options.TeamCount); }
  415. }
  416. communicationToGameID = new long[options.PlayerCountPerTeam + 1];
  417. teamCommunicatonMsg = new Queue<MsgRes>[options.PlayerCountPerTeam + 1];
  418. teamCommunicationLock = new object[options.PlayerCountPerTeam + 1];
  419. //创建server时先设定待加入人物都是invalid
  420. for (int i = 0; i < communicationToGameID.GetLength(0); i++)
  421. {
  422. communicationToGameID[i] = GameObj.invalidID;
  423. }
  424. if (options.FileName != DefaultArgumentOptions.FileName)
  425. {
  426. try
  427. {
  428. mwr = new MessageWriter(options.FileName, options.TeamCount, options.PlayerCountPerTeam);
  429. }
  430. catch
  431. {
  432. Console.WriteLine($"Error: Cannot create the playback file: {options.FileName}!");
  433. }
  434. }
  435. if (options.Url != DefaultArgumentOptions.Url && options.Token != DefaultArgumentOptions.Token)
  436. {
  437. //this.httpSender = new HttpSender(options.Url, options.Token, "PUT");
  438. }
  439. }
  440. }
  441. }