Robot.cs 14 KB

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