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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  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<Tuple<PlayerType, uint>> spectatorList = new List<Tuple<PlayerType, uint>>();
  32. public int TeamCount => options.TeamCount;
  33. protected long[,] communicationToGameID; // 通信用的ID映射到游戏内的ID,[i,j]表示team:i,player:j的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. bool gameState = game.StartGame((int)options.GameTimeInSecond * 1000);
  80. var waitHandle = new SemaphoreSlim(gameState == true ? 1 : 0); // 注意修改
  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. new Thread(() =>
  107. {
  108. waitHandle.Wait();
  109. this.endGameSem.Release();
  110. })
  111. { IsBackground = true }.Start();
  112. }
  113. public void WaitForEnd()
  114. {
  115. this.endGameSem.Wait();
  116. mwr?.Dispose();
  117. }
  118. private void OnGameEnd()
  119. {
  120. game.ClearAllLists();
  121. mwr?.Flush();
  122. //if (options.ResultFileName != DefaultArgumentOptions.FileName)
  123. //SaveGameResult(options.ResultFileName + ".json");
  124. //SendGameResult();
  125. endGameInfoSema.Release();
  126. }
  127. public void ReportGame(GameState gameState, bool requiredGaming = true)
  128. {
  129. var gameObjList = game.GetGameObj();
  130. lock (messageToAllClientsLock)
  131. {
  132. //currentGameInfo.MapMessage = (Messa(game.GameMap));
  133. switch (gameState)
  134. {
  135. case GameState.GameRunning:
  136. case GameState.GameStart:
  137. case GameState.GameEnd:
  138. foreach (GameObj gameObj in gameObjList)
  139. {
  140. currentGameInfo.ObjMessage.Add(CopyInfo.Auto(gameObj));
  141. }
  142. currentGameInfo.GameState = gameState;
  143. mwr?.WriteOne(currentGameInfo);
  144. break;
  145. default:
  146. break;
  147. }
  148. }
  149. foreach (var kvp in semaDict)
  150. {
  151. kvp.Value.Item1.Release();
  152. }
  153. foreach (var kvp in semaDict)
  154. {
  155. kvp.Value.Item2.Wait();
  156. }
  157. }
  158. private int PlayerTypeToTeamID(PlayerType playerType)
  159. {
  160. if (playerType == PlayerType.StudentPlayer) return 0;
  161. if (playerType == PlayerType.TrickerPlayer) return 1;
  162. return -1;
  163. }
  164. private uint GetBirthPointIdx(PlayerType playerType, long playerID) // 获取出生点位置
  165. {
  166. return (uint)((PlayerTypeToTeamID(playerType) * options.PlayerCountPerTeam) + playerID + 1);
  167. }
  168. private bool ValidPlayerTypeAndPlayerID(PlayerType playerType, long playerID)
  169. {
  170. if (playerType == PlayerType.StudentPlayer && 0 <= playerID && playerID < options.PlayerCountPerTeam)
  171. return true; // 人数待修改
  172. if (playerType == PlayerType.TrickerPlayer && 0 <= playerID && playerID < options.PlayerCountPerTeam)
  173. return true;
  174. return false;
  175. }
  176. private MessageOfMap MapMsg(Map map)
  177. {
  178. MessageOfMap msgOfMap = new MessageOfMap();
  179. for (int i = 0; i < GameData.rows; i++)
  180. {
  181. msgOfMap.Row.Add(new MessageOfMap.Types.Row());
  182. for (int j = 0; j < GameData.cols; j++)
  183. {
  184. //msgOfMap.Row[i].Col.Add((int)map.ProtoGameMap[i, j]); int转placetype
  185. }
  186. }
  187. return msgOfMap;
  188. }
  189. public override Task<BoolRes> TryConnection(IDMsg request, ServerCallContext context)
  190. {
  191. Console.WriteLine($"TryConnection ID: {request.PlayerId}");
  192. var onConnection = new BoolRes();
  193. lock (gameLock)
  194. {
  195. if (0 <= request.PlayerId && request.PlayerId < playerNum) // 注意修改
  196. {
  197. onConnection.ActSuccess = true;
  198. Console.WriteLine(onConnection.ActSuccess);
  199. return Task.FromResult(onConnection);
  200. }
  201. }
  202. onConnection.ActSuccess = false;
  203. return Task.FromResult(onConnection);
  204. }
  205. protected readonly object addPlayerLock = new();
  206. public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter<MessageToClient> responseStream, ServerCallContext context)
  207. {
  208. Console.WriteLine($"AddPlayer: {request.PlayerId}");
  209. if (request.PlayerId >= spectatorMinPlayerID && request.PlayerType == PlayerType.NullPlayerType)
  210. {
  211. // 观战模式
  212. Tuple<PlayerType, uint> tp = new Tuple<PlayerType, uint>(request.PlayerType, (uint)request.PlayerId);
  213. if (!spectatorList.Contains(tp))
  214. {
  215. spectatorList.Add(tp);
  216. Console.WriteLine("A new spectator comes to watch this game.");
  217. }
  218. return;
  219. }
  220. if (game.GameMap.Timer.IsGaming)
  221. return;
  222. if (!ValidPlayerTypeAndPlayerID(request.PlayerType, request.PlayerId)) //玩家id是否正确
  223. return;
  224. //if (communicationToGameID[PlayerTypeToTeamID(request.PlayerType), request.PlayerId] != GameObj.invalidID) //是否已经添加了该玩家
  225. //return;
  226. Preparation.Utility.CharacterType characterType = Preparation.Utility.CharacterType.Athlete; // 待修改
  227. lock (addPlayerLock)
  228. {
  229. Game.PlayerInitInfo playerInitInfo = new(GetBirthPointIdx(request.PlayerType, request.PlayerId), PlayerTypeToTeamID(request.PlayerType), request.PlayerId, characterType);
  230. long newPlayerID = game.AddPlayer(playerInitInfo);
  231. if (newPlayerID == GameObj.invalidID)
  232. return;
  233. communicationToGameID[PlayerTypeToTeamID(request.PlayerType), request.PlayerId] = newPlayerID;
  234. // 内容待修改
  235. var temp = (new SemaphoreSlim(0, 1), new SemaphoreSlim(0, 1));
  236. bool start = false;
  237. Console.WriteLine($"PlayerType: {request.PlayerType} Id: {request.PlayerId} joins.");
  238. lock (semaDict)
  239. {
  240. semaDict.Add(request.PlayerId, temp);
  241. start = semaDict.Count == playerNum; // 之后补上CheckStart函数
  242. }
  243. if (start)
  244. {
  245. Console.WriteLine("Game starts!");
  246. StartGame();
  247. }
  248. }
  249. do
  250. {
  251. semaDict[request.PlayerId].Item1.Wait();
  252. if (currentGameInfo != null)
  253. {
  254. await responseStream.WriteAsync(currentGameInfo);
  255. Console.WriteLine("Send!");
  256. }
  257. semaDict[request.PlayerId].Item2.Release();
  258. } while (game.GameMap.Timer.IsGaming);
  259. }
  260. public override Task<BoolRes> Attack(AttackMsg request, ServerCallContext context)
  261. {
  262. game.Attack(request.PlayerId, request.Angle);
  263. BoolRes boolRes = new();
  264. boolRes.ActSuccess = true;
  265. return Task.FromResult(boolRes);
  266. }
  267. public override Task GetMessage(IDMsg request, IServerStreamWriter<MsgRes> responseStream, ServerCallContext context)
  268. {
  269. return base.GetMessage(request, responseStream, context);
  270. }
  271. public override Task<MoveRes> Move(MoveMsg request, ServerCallContext context)
  272. {
  273. Console.WriteLine($"SetPos ID: {request.PlayerId}, TimeInMilliseconds: {request.TimeInMilliseconds}");
  274. var gameID = communicationToGameID[PlayerTypeToTeamID(request.PlayerType), request.PlayerId];
  275. game.MovePlayer(gameID, (int)request.TimeInMilliseconds, request.Angle);
  276. // 之后game.MovePlayer可能改为bool类型
  277. MoveRes moveRes = new();
  278. moveRes.ActSuccess = true;
  279. return Task.FromResult(moveRes);
  280. }
  281. public override Task<BoolRes> PickProp(PropMsg request, ServerCallContext context)
  282. {
  283. BoolRes boolRes = new();
  284. if (request.PropType == Protobuf.PropType.NullPropType)
  285. boolRes.ActSuccess = game.PickProp(request.PlayerId, Preparation.Utility.PropType.Null);
  286. return Task.FromResult(boolRes);
  287. }
  288. public override Task<BoolRes> SendMessage(SendMsg request, ServerCallContext context)
  289. {
  290. return base.SendMessage(request, context);
  291. }
  292. public override Task<BoolRes> UseProp(PropMsg request, ServerCallContext context)
  293. {
  294. return base.UseProp(request, context);
  295. }
  296. public override Task<BoolRes> UseSkill(SkillMsg request, ServerCallContext context)
  297. {
  298. return base.UseSkill(request, context);
  299. }
  300. public override Task<BoolRes> Graduate(IDMsg request, ServerCallContext context)
  301. {
  302. return base.Graduate(request, context);
  303. }
  304. public override Task<BoolRes> StartRescueMate(IDMsg request, ServerCallContext context)
  305. {
  306. return base.StartRescueMate(request, context);
  307. }
  308. public override Task<BoolRes> StartTreatMate(IDMsg request, ServerCallContext context)
  309. {
  310. return base.StartTreatMate(request, context);
  311. }
  312. public override Task<BoolRes> StartLearning(IDMsg request, ServerCallContext context)
  313. {
  314. return base.StartLearning(request, context);
  315. }
  316. public GameServer(ArgumentOptions options)
  317. {
  318. this.options = options;
  319. //if (options.mapResource == DefaultArgumentOptions.MapResource)
  320. // this.game = new Game(MapInfo.defaultMap, options.TeamCount);
  321. //else
  322. {
  323. uint[,] map = new uint[GameData.rows, GameData.cols];
  324. try
  325. {
  326. string? line;
  327. int i = 0, j = 0;
  328. using (StreamReader sr = new StreamReader(options.mapResource))
  329. {
  330. while (!sr.EndOfStream && i < GameData.rows)
  331. {
  332. if ((line = sr.ReadLine()) != null)
  333. {
  334. string[] nums = line.Split(' ');
  335. foreach (string item in nums)
  336. {
  337. if (item.Length > 1)//以兼容原方案
  338. {
  339. map[i, j] = (uint)int.Parse(item);
  340. }
  341. else
  342. {
  343. //2022-04-22 by LHR 十六进制编码地图方案(防止地图编辑员瞎眼x
  344. map[i, j] = (uint)Preparation.Utility.MapEncoder.Hex2Dec(char.Parse(item));
  345. }
  346. j++;
  347. if (j >= GameData.cols)
  348. {
  349. j = 0;
  350. break;
  351. }
  352. }
  353. i++;
  354. }
  355. }
  356. }
  357. }
  358. catch
  359. {
  360. map = MapInfo.defaultMap;
  361. }
  362. finally { this.game = new Game(map, options.TeamCount); }
  363. }
  364. communicationToGameID = new long[options.TeamCount, options.PlayerCountPerTeam];
  365. //创建server时先设定待加入人物都是invalid
  366. for (int i = 0; i < communicationToGameID.GetLength(0); i++)
  367. {
  368. for (int j = 0; j < communicationToGameID.GetLength(1); j++)
  369. {
  370. communicationToGameID[i, j] = GameObj.invalidID;
  371. }
  372. }
  373. if (options.FileName != DefaultArgumentOptions.FileName)
  374. {
  375. try
  376. {
  377. mwr = new MessageWriter(options.FileName, options.TeamCount, options.PlayerCountPerTeam);
  378. }
  379. catch
  380. {
  381. Console.WriteLine($"Error: Cannot create the playback file: {options.FileName}!");
  382. }
  383. }
  384. if (options.Url != DefaultArgumentOptions.Url && options.Token != DefaultArgumentOptions.Token)
  385. {
  386. //this.httpSender = new HttpSender(options.Url, options.Token, "PUT");
  387. }
  388. }
  389. }
  390. }