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 14 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364
  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. foreach (var kvp in semaDict)
  110. {
  111. kvp.Value.Item1.Release();
  112. }
  113. foreach (var kvp in semaDict)
  114. {
  115. kvp.Value.Item2.Wait();
  116. }
  117. }
  118. private int PlayerTypeToTeamID(PlayerType playerType)
  119. {
  120. if (playerType == PlayerType.StudentPlayer) return 0;
  121. if (playerType == PlayerType.TrickerPlayer) return 1;
  122. return -1;
  123. }
  124. private uint GetBirthPointIdx(PlayerType playerType, long playerID) // 获取出生点位置
  125. {
  126. return (uint)((PlayerTypeToTeamID(playerType) * options.PlayerCountPerTeam) + playerID + 1);
  127. }
  128. private bool ValidPlayerTypeAndPlayerID(PlayerType playerType, long playerID)
  129. {
  130. if (playerType == PlayerType.StudentPlayer && 0 <= playerID && playerID < options.PlayerCountPerTeam)
  131. return true; // 人数待修改
  132. if (playerType == PlayerType.TrickerPlayer && 0 <= playerID && playerID < options.PlayerCountPerTeam)
  133. return true;
  134. return false;
  135. }
  136. public override Task<BoolRes> TryConnection(IDMsg request, ServerCallContext context)
  137. {
  138. Console.WriteLine($"TryConnection ID: {request.PlayerId}");
  139. var onConnection = new BoolRes();
  140. lock (gameLock)
  141. {
  142. if (0 <= request.PlayerId && request.PlayerId < playerNum) // 注意修改
  143. {
  144. onConnection.ActSuccess = true;
  145. Console.WriteLine(onConnection.ActSuccess);
  146. return Task.FromResult(onConnection);
  147. }
  148. }
  149. onConnection.ActSuccess = false;
  150. return Task.FromResult(onConnection);
  151. }
  152. protected readonly object addPlayerLock = new();
  153. public override async Task AddPlayer(PlayerMsg request, IServerStreamWriter<MessageToClient> responseStream, ServerCallContext context)
  154. {
  155. Console.WriteLine($"AddPlayer: {request.PlayerId}");
  156. if (request.PlayerId >= spectatorMinPlayerID && request.PlayerType == PlayerType.NullPlayerType)
  157. {
  158. // 观战模式
  159. Tuple<PlayerType, uint> tp = new Tuple<PlayerType, uint>(request.PlayerType, (uint)request.PlayerId);
  160. if (!spectatorList.Contains(tp))
  161. {
  162. spectatorList.Add(tp);
  163. Console.WriteLine("A new spectator comes to watch this game.");
  164. }
  165. return;
  166. }
  167. if (game.GameMap.Timer.IsGaming)
  168. return;
  169. if (!ValidPlayerTypeAndPlayerID(request.PlayerType, request.PlayerId)) //玩家id是否正确
  170. return;
  171. //if (communicationToGameID[PlayerTypeToTeamID(request.PlayerType), request.PlayerId] != GameObj.invalidID) //是否已经添加了该玩家
  172. //return;
  173. Preparation.Utility.CharacterType characterType = Preparation.Utility.CharacterType.Athlete; // 待修改
  174. lock (addPlayerLock)
  175. {
  176. Game.PlayerInitInfo playerInitInfo = new(GetBirthPointIdx(request.PlayerType, request.PlayerId), PlayerTypeToTeamID(request.PlayerType), request.PlayerId, characterType);
  177. long newPlayerID = game.AddPlayer(playerInitInfo);
  178. //if (newPlayerID == GameObj.invalidID)
  179. //return;
  180. // 内容待修改
  181. var temp = (new SemaphoreSlim(0, 1), new SemaphoreSlim(0, 1));
  182. bool start = false;
  183. Console.WriteLine($"PlayerType: {request.PlayerType} Id: {request.PlayerId} joins.");
  184. lock (semaDict)
  185. {
  186. semaDict.Add(request.PlayerId, temp);
  187. start = semaDict.Count == playerNum; // 之后补上CheckStart函数
  188. }
  189. if (start)
  190. {
  191. Console.WriteLine("Game starts!");
  192. StartGame();
  193. }
  194. }
  195. do
  196. {
  197. semaDict[request.PlayerId].Item1.Wait();
  198. if (currentGameInfo != null)
  199. {
  200. await responseStream.WriteAsync(currentGameInfo);
  201. Console.WriteLine("Send!");
  202. }
  203. semaDict[request.PlayerId].Item2.Release();
  204. } while (game.GameMap.Timer.IsGaming);
  205. }
  206. public override Task<BoolRes> Trick(TrickMsg request, ServerCallContext context)
  207. {
  208. game.Attack(request.PlayerId, request.Angle);
  209. BoolRes boolRes = new();
  210. boolRes.ActSuccess = true;
  211. return Task.FromResult(boolRes);
  212. }
  213. public override Task GetMessage(IDMsg request, IServerStreamWriter<MsgRes> responseStream, ServerCallContext context)
  214. {
  215. return base.GetMessage(request, responseStream, context);
  216. }
  217. public override Task<MoveRes> Move(MoveMsg request, ServerCallContext context)
  218. {
  219. Console.WriteLine($"Move ID: {request.PlayerId}, TimeInMilliseconds: {request.TimeInMilliseconds}");
  220. game.MovePlayer(request.PlayerId, (int)request.TimeInMilliseconds, request.Angle);
  221. // 之后game.MovePlayer可能改为bool类型
  222. MoveRes moveRes = new();
  223. moveRes.ActSuccess = true;
  224. return Task.FromResult(moveRes);
  225. }
  226. public override Task<BoolRes> PickProp(PickMsg request, ServerCallContext context)
  227. {
  228. BoolRes boolRes = new();
  229. if (request.PropType == Protobuf.PropType.NullPropType)
  230. boolRes.ActSuccess = game.PickProp(request.PlayerId, Preparation.Utility.PropType.Null);
  231. return Task.FromResult(boolRes);
  232. }
  233. public override Task<BoolRes> SendMessage(SendMsg request, ServerCallContext context)
  234. {
  235. return base.SendMessage(request, context);
  236. }
  237. public override Task<BoolRes> UseProp(IDMsg request, ServerCallContext context)
  238. {
  239. return base.UseProp(request, context);
  240. }
  241. public override Task<BoolRes> UseSkill(IDMsg request, ServerCallContext context)
  242. {
  243. return base.UseSkill(request, context);
  244. }
  245. public override Task<BoolRes> Graduate(IDMsg request, ServerCallContext context)
  246. {
  247. return base.Graduate(request, context);
  248. }
  249. public override Task<BoolRes> StartHealMate(IDMsg request, ServerCallContext context)
  250. {
  251. return base.StartHealMate(request, context);
  252. }
  253. public override Task<BoolRes> StartHelpMate(IDMsg request, ServerCallContext context)
  254. {
  255. return base.StartHelpMate(request, context);
  256. }
  257. public override Task<BoolRes> StartLearning(IDMsg request, ServerCallContext context)
  258. {
  259. return base.StartLearning(request, context);
  260. }
  261. public GameServer(ArgumentOptions options)
  262. {
  263. this.options = options;
  264. //if (options.mapResource == DefaultArgumentOptions.MapResource)
  265. // this.game = new Game(MapInfo.defaultMap, options.TeamCount);
  266. //else
  267. {
  268. uint[,] map = new uint[GameData.rows, GameData.cols];
  269. try
  270. {
  271. string? line;
  272. int i = 0, j = 0;
  273. using (StreamReader sr = new StreamReader(options.mapResource))
  274. {
  275. while (!sr.EndOfStream && i < GameData.rows)
  276. {
  277. if ((line = sr.ReadLine()) != null)
  278. {
  279. string[] nums = line.Split(' ');
  280. foreach (string item in nums)
  281. {
  282. if (item.Length > 1)//以兼容原方案
  283. {
  284. map[i, j] = (uint)int.Parse(item);
  285. }
  286. else
  287. {
  288. //2022-04-22 by LHR 十六进制编码地图方案(防止地图编辑员瞎眼x
  289. map[i, j] = (uint)Preparation.Utility.MapEncoder.Hex2Dec(char.Parse(item));
  290. }
  291. j++;
  292. if (j >= GameData.cols)
  293. {
  294. j = 0;
  295. break;
  296. }
  297. }
  298. i++;
  299. }
  300. }
  301. }
  302. }
  303. catch
  304. {
  305. map = MapInfo.defaultMap;
  306. }
  307. finally { this.game = new Game(map, options.TeamCount); }
  308. }
  309. communicationToGameID = new long[options.TeamCount, options.PlayerCountPerTeam];
  310. //创建server时先设定待加入人物都是invalid
  311. for (int i = 0; i < communicationToGameID.GetLength(0); i++)
  312. {
  313. for (int j = 0; j < communicationToGameID.GetLength(1); j++)
  314. {
  315. communicationToGameID[i, j] = GameObj.invalidID;
  316. }
  317. }
  318. if (options.FileName != DefaultArgumentOptions.FileName)
  319. {
  320. try
  321. {
  322. //mwr = new MessageWriter(options.FileName, options.TeamCount, options.PlayerCountPerTeam);
  323. }
  324. catch
  325. {
  326. Console.WriteLine($"Error: Cannot create the playback file: {options.FileName}!");
  327. }
  328. }
  329. if (options.Url != DefaultArgumentOptions.Url && options.Token != DefaultArgumentOptions.Token)
  330. {
  331. //this.httpSender = new HttpSender(options.Url, options.Token, "PUT");
  332. }
  333. }
  334. }
  335. }