Robot.cs 14 KB

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