Robot.cs 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  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, int maxRobotAmt)
  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, maxRobotAmt); });
  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, int maxRobotAmt)
  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.Data, maxRobotAmt);
  147. arg.PutInt(Label.RoomID, sfsRoomID);
  148. arg.PutLong(Label.UserID, RobotConfigID);
  149. SendRequest(arg);
  150. }
  151. private void SendRequest(SFSObject arg)
  152. {
  153. arg = GardenSmartFox.WrapIntoArray(new List<SFSObject> {arg});
  154. SmartFox.Send(new ExtensionRequest(HandlerID.PlazaRoom.GetHashString(), arg));
  155. }
  156. private void SendChestAwardRequest(long chestID)
  157. {
  158. SFSObject arg = PlazaRoomEvent.WrapChestAwardArg(chestID);
  159. SendRequest(arg);
  160. }
  161. private void SendInstantiateRequest(int receiver)
  162. {
  163. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.SendInstantiateRequset(User.Id, DressdataIDs.ToArray(), Position, Direction, Nickname, receiver);
  164. }
  165. private void OnConnectReturn(BaseEvent evt)
  166. {
  167. if ((bool) evt.Params["success"])
  168. {
  169. //Debug.LogWarning("Robot connect succeed");
  170. Login();
  171. }
  172. else
  173. {
  174. //Debug.LogWarning("Robot connect failed");
  175. Deactivate(false);
  176. }
  177. }
  178. private void OnExtensionResponse(BaseEvent evt)
  179. {
  180. string cmd = evt.Params["cmd"].ToString();
  181. if (cmd == PlazaRoomRep.JoinRoomSucceed.GetHashString())
  182. {
  183. Activate(evt);
  184. }
  185. else if (cmd == PlazaRoomRep.MarkRobotError.GetHashString())
  186. {
  187. Deactivate(false);
  188. }
  189. else if (cmd == PlazaRoomRep.OtherEnterRoom.GetHashString())
  190. {
  191. OnOtherEnterRoom(evt);
  192. }
  193. }
  194. private void OnOtherEnterRoom(BaseEvent evt)
  195. {
  196. ISFSObject arg = (ISFSObject) evt.Params["params"];
  197. int userID = arg.GetInt(Label.UserID);
  198. if (userID != User.Id)
  199. {
  200. SendInstantiateRequest(userID);
  201. }
  202. }
  203. public bool Update()
  204. {
  205. if (SmartFox != null)
  206. {
  207. SmartFox.ProcessEvents();
  208. }
  209. return Behaviour();
  210. }
  211. private bool Activated;
  212. private void Activate(BaseEvent evt)
  213. {
  214. //Debug.LogWarning("Robot Activate");
  215. Activated = true;
  216. MoveTime = Random.Range(MinMoveTime, MaxMoveTime);
  217. LifetimeTime = Random.Range(MinLifetime, MaxLifetime);
  218. CreateChestTime = Random.Range(0, LifetimeTime);
  219. SendInstantiateRequest(-1);
  220. }
  221. private bool Behaviour()
  222. {
  223. if (!Activated)
  224. {
  225. return false;
  226. }
  227. if (!SFSManager.GardenSmartFox.PlazaRoomManager.JoinedPlazaRoom)
  228. {
  229. return false;
  230. }
  231. if (LifetimeBehaviour())
  232. {
  233. return true;
  234. }
  235. MoveBehaviour();
  236. CreateChestBehaviour();
  237. GetChestAwardBehaviour();
  238. return false;
  239. }
  240. private float MoveTime;
  241. private float MoveTimer;
  242. private void MoveBehaviour()
  243. {
  244. MoveTimer += Time.deltaTime;
  245. if (MoveTimer >= MoveTime)
  246. {
  247. MoveTimer = 0;
  248. //Debug.LogWarning("Robot move");
  249. Vector3? pos = Raycast();
  250. if (pos != null)
  251. {
  252. Position = pos.Value;
  253. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.SendSynchronizeDestination(User.Id, Position);
  254. }
  255. }
  256. }
  257. private Vector3? Raycast()
  258. {
  259. Vector3 origin = new Vector3(Random.Range(LeftDownBorder.x, RightTop.x), Random.Range(LeftDownBorder.y, RightTop.y), Camera.transform.position.z);
  260. Ray ray = new Ray(origin, Vector3.forward);
  261. RaycastHit hitInfo;
  262. if (Physics.Raycast(ray, out hitInfo))
  263. {
  264. if (hitInfo.collider.tag == Tags.PlazaChestTag)
  265. {
  266. //Debug.LogWarning("射线被箱子阻挡");
  267. return null;
  268. }
  269. else
  270. {
  271. Vector3 destination = PlazaRoom.HitPositionToDestination(hitInfo.point);
  272. return destination;
  273. }
  274. }
  275. else
  276. {
  277. //Debug.LogWarning("射线检测失败");
  278. return null;
  279. }
  280. }
  281. private float LifetimeTime;
  282. private float LifetimeTimer;
  283. private bool LifetimeBehaviour()
  284. {
  285. LifetimeTimer += Time.deltaTime;
  286. if (LifetimeTimer >= LifetimeTime)
  287. {
  288. //Debug.LogWarning("Robot lifetime over");
  289. return true;
  290. }
  291. else
  292. {
  293. return false;
  294. }
  295. }
  296. private bool CreateChestLock;
  297. private float CreateChestTime;
  298. private float CreateChestTimer;
  299. private void CreateChestBehaviour()
  300. {
  301. if (CreateChestLock)
  302. {
  303. return;
  304. }
  305. CreateChestTimer += Time.deltaTime;
  306. if (CreateChestTimer >= CreateChestTime)
  307. {
  308. CreateChestLock = true;
  309. if (Random.Range(0f, 1f) >= CreateChestRate)
  310. {
  311. //Debug.LogWarning("create chest ran out of luck");
  312. return;
  313. }
  314. //Debug.LogWarning("Robot create a chest");
  315. RoomData roomData = SFSManager.GardenSmartFox.PlazaRoomManager.CurrentRoomData;
  316. int round = Random.Range(1, roomData.MaxPlayer + 1);
  317. int value = Random.Range(MinChestValue, MaxChestValue);
  318. Vector3 playerPos = SFSManager.GardenSmartFox.PlazaRoomManager.UserInstanceDictionary[User.Id].Player.transform.position;
  319. Vector3 chestPos = ChestMge.PlayerPosToChestPos(playerPos);
  320. ChestType type = (ChestType) Random.Range(1, 4);
  321. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.CreateChest(round, value, type, roomData.ID, -2, chestPos);
  322. }
  323. }
  324. private float GetChestTime = 3;
  325. private float GetChestTimer;
  326. private float MaxChestDistance = 8;
  327. private List<long> OperatedChestIDs = new List<long>();
  328. private void GetChestAwardBehaviour()
  329. {
  330. GetChestTimer += Time.deltaTime;
  331. if (GetChestTimer >= GetChestTime)
  332. {
  333. GetChestTimer = 0;
  334. //Debug.LogWarning("Robot try get some chests");
  335. List<PlazaRoomChest> chests = DetectChest();
  336. //Debug.LogWarning($"{chests.Count} chest/chests is available");
  337. for (int i = 0; i < chests.Count; i++)
  338. {
  339. TryGetChestAward(chests[i]);
  340. }
  341. }
  342. }
  343. private List<PlazaRoomChest> DetectChest()
  344. {
  345. List<PlazaRoomChest> chests = new List<PlazaRoomChest>();
  346. for (int i = 0; i < ChestMge.PlazaRoomChests.Count; i++)
  347. {
  348. if (Mathf.Abs(ChestMge.PlazaRoomChests[i].transform.position.x - Position.x) <= MaxChestDistance)
  349. {
  350. if (OperatedChestIDs.Contains(ChestMge.PlazaRoomChests[i].ChestData.ID))
  351. {
  352. //Debug.LogWarning("this chest has been operated");
  353. }
  354. else
  355. {
  356. chests.Add(ChestMge.PlazaRoomChests[i]);
  357. }
  358. }
  359. else
  360. {
  361. //Debug.LogWarning("this chest is too far");
  362. //Debug.LogWarning(Mathf.Abs(ChestMge.PlazaRoomChests[i].transform.position.x - Position.x));
  363. }
  364. }
  365. return chests;
  366. }
  367. private void TryGetChestAward(PlazaRoomChest chest)
  368. {
  369. float rate = Random.Range(0f, 1f);
  370. bool get = false;
  371. if (chest.ChestData.ChestType == ChestType.GuessColor)
  372. {
  373. if (rate < ColorChestRate)
  374. {
  375. get = true;
  376. }
  377. else
  378. {
  379. get = false;
  380. }
  381. }
  382. else if (chest.ChestData.ChestType == ChestType.GuessNumber)
  383. {
  384. if (rate < DigitChestRate)
  385. {
  386. get = true;
  387. }
  388. else
  389. {
  390. get = false;
  391. }
  392. }
  393. else if (chest.ChestData.ChestType == ChestType.System)
  394. {
  395. if (chest.IsActive)
  396. {
  397. get = true;
  398. }
  399. else
  400. {
  401. get = false;
  402. }
  403. }
  404. else
  405. {
  406. get = true;
  407. }
  408. OperatedChestIDs.Add(chest.ChestData.ID);
  409. if (get)
  410. {
  411. SendChestAwardRequest(chest.ChestData.ID);
  412. //Debug.LogWarning("get a chest");
  413. }
  414. else
  415. {
  416. //Debug.LogWarning("get chest ran out of luck");
  417. }
  418. }
  419. private static float MinDelayTime = 3f;
  420. private static float MaxDelayTime = 10f;
  421. public void Deactivate(bool delay)
  422. {
  423. //Debug.LogWarning("Robot disconnect " + delay);
  424. Activated = false;
  425. if (delay)
  426. {
  427. DelayCall.Call(Random.Range(MinDelayTime, MaxDelayTime), Remove);
  428. }
  429. else
  430. {
  431. Remove();
  432. }
  433. }
  434. private void Remove()
  435. {
  436. RobotManager.Robots.Remove(this);
  437. SmartFox.Disconnect();
  438. }
  439. }