BattleHost.cs 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. using CommonAI.Zone.ZoneEditor;
  2. using CommonLang;
  3. namespace CommonTickBattle.Battle.Host
  4. {
  5. public class BattleHost : Battle
  6. {
  7. private HashMap<string, ISession> mPlayers = new HashMap<string, ISession>();
  8. public BattleHost(EditorTemplates data_root, TBConfig cfg)
  9. : base(data_root, cfg)
  10. {
  11. }
  12. protected override void OnDispose()
  13. {
  14. base.OnDispose();
  15. foreach (var player in mPlayers.Values)
  16. {
  17. player.OnReceived -= OnReceivedRequest;
  18. }
  19. mPlayers.Clear();
  20. }
  21. /// <summary>
  22. /// 增加一个玩家
  23. /// </summary>
  24. /// <param name="player"></param>
  25. public void BindSession(ISession player)
  26. {
  27. lock (this)
  28. {
  29. mPlayers.Add(player.PlayerUUID, player);
  30. player.OnReceived += OnReceivedRequest;
  31. }
  32. }
  33. /// <summary>
  34. /// 收到玩家操作消息
  35. /// </summary>
  36. /// <param name="player"></param>
  37. /// <param name="req"></param>
  38. protected virtual void OnReceivedRequest(ISession player, TBRequest req)
  39. {
  40. if (this.PushAction(req))
  41. {
  42. TBResponse rsp = new TBResponse();
  43. rsp.MessageID = req.MessageID;
  44. rsp.result = TBResponse.Result.OK;
  45. player.Send(rsp);
  46. TBNotify ntf = new TBNotify();
  47. ntf.action = req.action;
  48. ntf.action_tick = req.action_tick;
  49. ntf.player_uuid = player.PlayerUUID;
  50. this.Broadcast(ntf);
  51. }
  52. else
  53. {
  54. TBResponse rsp = new TBResponse();
  55. rsp.MessageID = req.MessageID;
  56. rsp.result = TBResponse.Result.TimeOut;
  57. player.Send(rsp);
  58. }
  59. }
  60. /// <summary>
  61. /// 广播操作消息
  62. /// </summary>
  63. /// <param name="ntf"></param>
  64. protected virtual void Broadcast(TBMessage ntf)
  65. {
  66. foreach (var p in mPlayers.Values)
  67. {
  68. p.Send(ntf);
  69. }
  70. }
  71. /// <summary>
  72. /// 想在未来某个时间点执行一个动作
  73. /// </summary>
  74. /// <param name="req"></param>
  75. /// <returns></returns>
  76. protected virtual bool PushAction(TBRequest req)
  77. {
  78. lock (this)
  79. {
  80. if (req.send_tick + this.RequestLaggingTick < this.CurrentTick)
  81. {
  82. //如果客户端时间+延迟时间小于本地时间,表示客户端上传请求已超时//
  83. log.ErrorFormat("客户端发送请求已超时 : CT={0} : {1}", req.send_tick, req.action);
  84. return false;
  85. }
  86. else if (req.action_tick < (this.CurrentTick + this.ResponseLaggingTick))
  87. {
  88. //如果执行动作时间,不够发送延迟时间,表示可能发送不成功,本次指令上传失败//
  89. log.ErrorFormat("客户端请求动作时间已超时 : AT={0} : {1}", req.action_tick, req.action);
  90. return false;
  91. }
  92. else
  93. {
  94. return base.PushAction(req.action, req.action_tick);
  95. }
  96. }
  97. }
  98. }
  99. }