Robot.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Security.Policy;
  6. using System.Xml;
  7. using Sfs2X;
  8. using Sfs2X.Core;
  9. using Sfs2X.Entities;
  10. using Sfs2X.Entities.Data;
  11. using Sfs2X.Requests;
  12. using Sfs2X.Util;
  13. using UnityEngine;
  14. using Random = UnityEngine.Random;
  15. public class Robot
  16. {
  17. #region Config
  18. private static Vector2 LeftDownBorder; //todo
  19. private static Vector2 RightTop; //todo
  20. private static Camera Camera; //todo
  21. private static bool Initialized;
  22. private static int MinChestValue;
  23. private static int MaxChestValue;
  24. private static float MinLifetime;
  25. private static float MaxLifetime;
  26. private static float CreateChestRate;
  27. private static float ColorChestRate;
  28. private static float DigitChestRate;
  29. private static float MinMoveTime;
  30. private static float MaxMoveTime;
  31. private static float MinRobotCreateTime;
  32. private static float MaxRobotCreateTime;
  33. private static string MaxRobotAmtFml;
  34. private static string ConfigName = "robot_config";
  35. private static string RootNodeName = "data";
  36. private static string DataNodeName = "item";
  37. private string Nickname;
  38. private Vector3 Position;
  39. private PlayerDirection Direction;
  40. private User User;
  41. private SmartFox SmartFox;
  42. private List<int> DressdataIDs = new List<int>();
  43. private List<string> DressdataNames = new List<string>();
  44. #endregion
  45. public static void Initialize()
  46. {
  47. if (Initialized)
  48. {
  49. Initialized = true;
  50. return;
  51. }
  52. LeftDownBorder = ManaReso.Get("PlayerLeftDownBorder").position;
  53. RightTop = ManaReso.Get("PlayerRightTopBorder").position;
  54. Camera = ManaReso.Get<Camera>("MainCamera");
  55. XmlDocument document = ManaData.GetXmlDocument(ConfigName);
  56. XmlNode dataNode = document.SelectSingleNode(RootNodeName).SelectSingleNode(DataNodeName);
  57. XmlAttributeCollection attributes = dataNode.Attributes;
  58. int index = 1;
  59. List<int> ints = Auxiliary.IntListParse(',', attributes[index++].Value, null);
  60. MinRobotCreateTime = ints[0];
  61. MaxRobotCreateTime = ints[1];
  62. MaxRobotAmtFml = attributes[index++].Value;
  63. DigitChestRate = float.Parse(attributes[index++].Value);
  64. ColorChestRate = float.Parse(attributes[index++].Value);
  65. ints = Auxiliary.IntListParse(',', attributes[index++].Value, null);
  66. MinMoveTime = ints[0];
  67. MaxMoveTime = ints[1];
  68. CreateChestRate = float.Parse(attributes[index++].Value);
  69. ints = Auxiliary.IntListParse(',', attributes[index++].Value, null);
  70. MinChestValue = ints[0];
  71. MaxChestValue = ints[1];
  72. ints = Auxiliary.IntListParse(',', attributes[index++].Value, null);
  73. MinLifetime = ints[0];
  74. MaxLifetime = ints[1];
  75. //Debug.Log($"RobotConfig {MinRobotCreateTime}");
  76. //Debug.Log($"RobotConfig {MaxRobotCreateTime}");
  77. //Debug.Log($"RobotConfig {MaxRobotAmtFml}");
  78. //Debug.Log($"RobotConfig {DigitChestRate}");
  79. //Debug.Log($"RobotConfig {ColorChestRate}");
  80. //Debug.Log($"RobotConfig {MinMoveTime}");
  81. //Debug.Log($"RobotConfig {MaxMoveTime}");
  82. //Debug.Log($"RobotConfig {CreateChestRate}");
  83. //Debug.Log($"RobotConfig {MinChestValue}");
  84. //Debug.Log($"RobotConfig {MaxChestValue}");
  85. //Debug.Log($"RobotConfig {MinLifetime}");
  86. //Debug.Log($"RobotConfig {MaxLifetime}");
  87. }
  88. public Robot(Vector3 position, PlayerDirection direction)
  89. {
  90. Position = position;
  91. Direction = direction;
  92. }
  93. public void Connect(int sfsRoomID, int maxRobot)
  94. {
  95. Debug.LogWarning("Robot connect");
  96. SmartFox = new SmartFox();
  97. SmartFox.AddEventListener(SFSEvent.CONNECTION, OnConnectReturn);
  98. SmartFox.AddEventListener(SFSEvent.CONNECTION_LOST, (evt) => Deactivate(false));
  99. SmartFox.AddEventListener(SFSEvent.LOGIN, evt => { Mark(evt, sfsRoomID, maxRobot); });
  100. SmartFox.AddEventListener(SFSEvent.LOGIN_ERROR, (evt) => Deactivate(false));
  101. SmartFox.AddEventListener(SFSEvent.LOGOUT, (evt) => Deactivate(false));
  102. SmartFox.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
  103. ConfigData configData = new ConfigData
  104. {
  105. Host = BaseConnector.Host,
  106. Port = BaseConnector.TcpPort,
  107. Zone = BaseConnector.Zone,
  108. };
  109. SmartFox.Connect(configData);
  110. }
  111. private void Login()
  112. {
  113. Debug.LogWarning("Robot login");
  114. string userName = Random.Range(0f, 1000f).ToString();
  115. SmartFox.Send(new LoginRequest(userName, ""));
  116. }
  117. private void Mark(BaseEvent evt, int sfsRoomID, int maxRobot)
  118. {
  119. Debug.LogWarning("Robot mark");
  120. User = (User) evt.Params["user"];
  121. SFSObject arg = new SFSObject();
  122. arg.PutInt(Label.CommandID, PlazaRoomReq.MarkAsRobot.GetHashCode());
  123. arg.PutInt(Label.RoomID, sfsRoomID);
  124. arg.PutInt(Label.Data, maxRobot);
  125. SendRequest(arg);
  126. }
  127. private void SendRequest(SFSObject arg)
  128. {
  129. arg = GardenSmartFox.WrapIntoArray(new List<SFSObject> {arg});
  130. SmartFox.Send(new ExtensionRequest(HandlerID.PlazaRoom.GetHashString(), arg));
  131. }
  132. private void SendInstantiateRequest(int receiver)
  133. {
  134. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.SendInstantiateRequset(User.Id, DressdataIDs.ToArray(), Position, Direction, Nickname, receiver);
  135. }
  136. private void OnConnectReturn(BaseEvent evt)
  137. {
  138. if ((bool) evt.Params["success"])
  139. {
  140. Debug.LogWarning("Robot connect succeed");
  141. Login();
  142. }
  143. else
  144. {
  145. Debug.LogWarning("Robot connect failed");
  146. Deactivate(false);
  147. }
  148. }
  149. private void OnExtensionResponse(BaseEvent evt)
  150. {
  151. string cmd = evt.Params["cmd"].ToString();
  152. if (cmd == PlazaRoomRep.JoinRoomSucceed.GetHashString())
  153. {
  154. Activate(evt);
  155. }
  156. else if (cmd == PlazaRoomRep.MarkRobotError.GetHashString())
  157. {
  158. Deactivate(false);
  159. }
  160. else if (cmd == PlazaRoomRep.OtherEnterRoom.GetHashString()) //todo
  161. {
  162. OnOtherEnterRoom(evt);
  163. }
  164. }
  165. private void OnOtherEnterRoom(BaseEvent evt)
  166. {
  167. ISFSObject arg = (ISFSObject) evt.Params["params"];
  168. int userID = arg.GetInt(Label.UserID);
  169. if (userID != User.Id)
  170. {
  171. SendInstantiateRequest(userID);
  172. }
  173. }
  174. public bool Update()
  175. {
  176. if (SmartFox != null)
  177. {
  178. SmartFox.ProcessEvents();
  179. }
  180. return Behaviour();
  181. }
  182. private bool Activated;
  183. private void Activate(BaseEvent evt)
  184. {
  185. if (!SFSManager.GardenSmartFox.PlazaRoomManager.InPlazaRoom)
  186. {
  187. Deactivate(false);
  188. }
  189. Debug.LogWarning("Robot Activate");
  190. Activated = true;
  191. MoveTime = Random.Range(MinMoveTime, MaxMoveTime);
  192. LifetimeTime = Random.Range(MinLifetime, MaxLifetime);
  193. CreateChestTime = Random.Range(0, LifetimeTime);
  194. try
  195. {
  196. ISFSObject arg = evt.Params["params"] as ISFSObject;
  197. Nickname = arg.GetUtfString(Label.Data);
  198. DressdataNames = arg.GetUtfStringArray(Label.DataArray).ToList();
  199. DressdataIDs = ManaData.GetDressDataIDs(DressdataNames);
  200. SendInstantiateRequest(-1);
  201. }
  202. catch (Exception e)
  203. {
  204. Debug.LogWarning(e);
  205. Deactivate(false);
  206. }
  207. }
  208. private bool Behaviour()
  209. {
  210. if (!Activated)
  211. {
  212. return false;
  213. }
  214. //if (LifetimeBehaviour())
  215. //{
  216. // return true;
  217. //}
  218. //MoveBehaviour();
  219. //CreateChestBehaviour();
  220. //GetChestAwardBehaviour();
  221. return false;
  222. }
  223. private float MoveTime;
  224. private float MoveTimer;
  225. private void MoveBehaviour()
  226. {
  227. MoveTimer += Time.deltaTime;
  228. if (MoveTimer >= MoveTime)
  229. {
  230. MoveTimer = 0;
  231. Debug.LogWarning("Robot move");
  232. Raycast();
  233. }
  234. }
  235. private void Raycast() //todo
  236. {
  237. Vector3 origin = new Vector3(Random.Range(LeftDownBorder.x, RightTop.x), Random.Range(LeftDownBorder.y, RightTop.y), Camera.transform.position.z);
  238. Ray ray = new Ray(origin, Vector3.forward);
  239. RaycastHit hitInfo;
  240. if (Physics.Raycast(ray, out hitInfo))
  241. {
  242. Vector3 destination = PlazaRoom.HitPositionToDestination(hitInfo.point);
  243. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.SendSynchronizeDestination(User.Id, destination);
  244. Position = destination;
  245. }
  246. else
  247. {
  248. Debug.LogWarning("射线检测失败");
  249. }
  250. }
  251. private float LifetimeTime;
  252. private float LifetimeTimer;
  253. private bool LifetimeBehaviour()
  254. {
  255. LifetimeTimer += Time.deltaTime;
  256. if (LifetimeTimer >= LifetimeTime)
  257. {
  258. Debug.LogWarning("Robot lifetime over");
  259. return true;
  260. }
  261. else
  262. {
  263. return false;
  264. }
  265. }
  266. private bool CreateChestLock;
  267. private float CreateChestTime;
  268. private float CreateChestTimer;
  269. private void CreateChestBehaviour() //todo
  270. {
  271. if (CreateChestLock)
  272. {
  273. return;
  274. }
  275. CreateChestTimer += Time.deltaTime;
  276. if (CreateChestTimer >= CreateChestTime)
  277. {
  278. CreateChestLock = true;
  279. if (Random.Range(0f, 1f) >= CreateChestRate)
  280. {
  281. Debug.LogWarning("create chest ran out of luck");
  282. return;
  283. }
  284. Debug.LogWarning("Robot create a chest");
  285. RoomData roomData = SFSManager.GardenSmartFox.PlazaRoomManager.CurrentRoomData;
  286. int round = Random.Range(1, roomData.MaxPlayer + 1);
  287. int value = Random.Range(MinChestValue, MaxChestValue);
  288. Vector3 position = ChestMge.PlayerPosToChestPos(Position);
  289. ChestType type = (ChestType) Random.Range(1, 4);
  290. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.CreateChest(round, value, type, roomData.ID, -1, position);
  291. }
  292. }
  293. private float GetChestTime = 3;
  294. private float GetChestTimer;
  295. private float MaxChestDistance = 8; //todo
  296. private List<long> OperatedChestIDs = new List<long>();
  297. private void GetChestAwardBehaviour() //todo
  298. {
  299. GetChestTimer += Time.deltaTime;
  300. if (GetChestTimer >= GetChestTime)
  301. {
  302. GetChestTimer = 0;
  303. Debug.LogWarning("Robot try get some chests");
  304. List<PlazaRoomChest> chests = DetectChest();
  305. Debug.LogWarning($"{chests.Count} chest/chests is available");
  306. for (int i = 0; i < chests.Count; i++)
  307. {
  308. TryGetChestAward(chests[i]);
  309. }
  310. }
  311. //Debug.LogWarning("robot get a chest");
  312. }
  313. private List<PlazaRoomChest> DetectChest()
  314. {
  315. List<PlazaRoomChest> chests = new List<PlazaRoomChest>();
  316. for (int i = 0; i < ChestMge.PlazaRoomChests.Count; i++)
  317. {
  318. if (Mathf.Abs(ChestMge.PlazaRoomChests[i].transform.position.x - Position.x) <= MaxChestDistance)
  319. {
  320. if (OperatedChestIDs.Contains(ChestMge.PlazaRoomChests[i].ChestData.ID))
  321. {
  322. Debug.LogWarning("this chest has been operated");
  323. }
  324. else
  325. {
  326. chests.Add(ChestMge.PlazaRoomChests[i]);
  327. }
  328. }
  329. else
  330. {
  331. Debug.LogWarning("this chest is too far");
  332. }
  333. }
  334. return chests;
  335. }
  336. private void TryGetChestAward(PlazaRoomChest chest)
  337. {
  338. float rate = Random.Range(0f, 1f);
  339. bool get = false;
  340. if (chest.ChestData.ChestType == ChestType.GuessColor)
  341. {
  342. if (rate < ColorChestRate)
  343. {
  344. get = true;
  345. }
  346. else
  347. {
  348. get = false;
  349. }
  350. }
  351. else if (chest.ChestData.ChestType == ChestType.GuessNumber)
  352. {
  353. if (rate < DigitChestRate)
  354. {
  355. get = true;
  356. }
  357. else
  358. {
  359. get = false;
  360. }
  361. }
  362. else
  363. {
  364. get = true;
  365. }
  366. OperatedChestIDs.Add(chest.ChestData.ID);
  367. if (get)
  368. {
  369. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.GetChestAward(chest.ChestData.ID);
  370. }
  371. else
  372. {
  373. Debug.LogWarning("get chest ran out of luck");
  374. }
  375. }
  376. private static float MinDelayTime = 3f;
  377. private static float MaxDelayTime = 10f;
  378. public void Deactivate(bool delay)
  379. {
  380. Debug.LogWarning("Robot disconnect");
  381. Activated = false;
  382. if (delay)
  383. {
  384. DelayCall.Call(Random.Range(MinDelayTime, MaxDelayTime), Remove);
  385. }
  386. else
  387. {
  388. Remove();
  389. }
  390. }
  391. private void Remove()
  392. {
  393. RobotManager.Robots.Remove(this);
  394. SmartFox.Disconnect();
  395. }
  396. }