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