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