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