Robot.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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 Inited;
  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 DateTime JoinedTime;
  36. private PlayerDirection Direction;
  37. private User User;
  38. private SmartFox SmartFox;
  39. private List<int> DressdataIDs = new List<int>();
  40. private List<string> DressdataNames = new List<string>();
  41. #endregion
  42. public static void Init()
  43. {
  44. if (Inited)
  45. {
  46. Inited = true;
  47. return;
  48. }
  49. LeftDownBorder = ResourceManager.Get(PlazaRoomLabel.PlayerLeftDownBorder).position;
  50. RightTop = ResourceManager.Get(PlazaRoomLabel.PlayerRightTopBorder).position;
  51. Camera = ResourceManager.Get<Camera>(ResourceLabel.MainCamera);
  52. XmlDocument document = ConfigManager.GetXmlDocument(ResourceLabel.RobotConfig);
  53. XmlNode dataNode = document.SelectSingleNode(ConfigLabel.RootNode).SelectSingleNode(ConfigLabel.ChildNode);
  54. XmlAttributeCollection attributes = dataNode.Attributes;
  55. int index = 1;
  56. MaxRobotAmtFml = attributes[index++].Value;
  57. DigitChestRate = float.Parse(attributes[index++].Value);
  58. ColorChestRate = float.Parse(attributes[index++].Value);
  59. List<int> ints = Auxiliary.StringToInts(',', attributes[index++].Value, null);
  60. MinMoveTime = ints[0];
  61. MaxMoveTime = ints[1];
  62. CreateChestRate = float.Parse(attributes[index++].Value);
  63. ints = Auxiliary.StringToInts(',', attributes[index++].Value, null);
  64. MinChestValue = ints[0];
  65. MaxChestValue = ints[1];
  66. ints = Auxiliary.StringToInts(',', attributes[index++].Value, null);
  67. MinLifetime = ints[0];
  68. MaxLifetime = ints[1];
  69. //Debug.Log($"RobotConfig {MinRobotCreateTime}");
  70. //Debug.Log($"RobotConfig {MaxRobotCreateTime}");
  71. //Debug.Log($"RobotConfig {MaxRobotAmtFml}");
  72. //Debug.Log($"RobotConfig {DigitChestRate}");
  73. //Debug.Log($"RobotConfig {ColorChestRate}");
  74. //Debug.Log($"RobotConfig {MinMoveTime}");
  75. //Debug.Log($"RobotConfig {MaxMoveTime}");
  76. //Debug.Log($"RobotConfig {CreateChestRate}");
  77. //Debug.Log($"RobotConfig {MinChestValue}");
  78. //Debug.Log($"RobotConfig {MaxChestValue}");
  79. //Debug.Log($"RobotConfig {MinLifetime}");
  80. //Debug.Log($"RobotConfig {MaxLifetime}");
  81. }
  82. public Robot(long robotConfigID, bool randomPos, string nickname, List<string> dressdatas)
  83. {
  84. //if (randomPos)
  85. //{
  86. // Vector3? pos;
  87. // while ((pos = Raycast()) == null);
  88. // Position = pos.Value;
  89. // Direction = (PlayerDirection) Random.Range(0, 2);
  90. //}
  91. //else
  92. //{
  93. // Position = SFSPlazaRoomManager.GetDefaultPosition();
  94. // Direction = SFSPlazaRoomManager.DefaultDirection;
  95. //}
  96. Position = PlazaRoomController.GetDefaultPosition();
  97. Direction = PlazaRoomController.DefaultDirection;
  98. try
  99. {
  100. RobotConfigID = robotConfigID;
  101. Nickname = nickname;
  102. DressdataNames = dressdatas;
  103. DressdataIDs = ConfigManager.GetDressDataIDs(DressdataNames);
  104. }
  105. catch (Exception e)
  106. {
  107. foreach (var DressdataName in DressdataNames)
  108. {
  109. Debug.LogWarning(DressdataName);
  110. }
  111. Debug.LogWarning(e);
  112. }
  113. }
  114. public void Connect(int sfsRoomID, int maxRobotAmt)
  115. {
  116. //Debug.LogWarning("Robot connect");
  117. SmartFox = new SmartFox();
  118. SmartFox.AddEventListener(SFSEvent.CONNECTION, OnConnectReturn);
  119. SmartFox.AddEventListener(SFSEvent.CONNECTION_LOST, (evt) => Deactivate(false));
  120. SmartFox.AddEventListener(SFSEvent.LOGIN, evt => { MarkAsRobot(evt, sfsRoomID, maxRobotAmt); });
  121. SmartFox.AddEventListener(SFSEvent.LOGIN_ERROR, (evt) => Deactivate(false));
  122. SmartFox.AddEventListener(SFSEvent.LOGOUT, (evt) => Deactivate(false));
  123. SmartFox.AddEventListener(SFSEvent.EXTENSION_RESPONSE, OnExtensionResponse);
  124. ConfigData configData = new ConfigData
  125. {
  126. Host = BaseConnector.Host,
  127. Port = BaseConnector.TcpPort,
  128. Zone = BaseConnector.Zone,
  129. };
  130. SmartFox.Connect(configData);
  131. }
  132. private void Login()
  133. {
  134. //Debug.LogWarning("Robot login");
  135. string userName = Loggor.GetRandomUsername();
  136. SmartFox.Send(new LoginRequest(userName, ""));
  137. }
  138. private void MarkAsRobot(BaseEvent evt, int sfsRoomID, int maxRobotAmt)
  139. {
  140. //Debug.LogWarning("Robot mark");
  141. User = (User) evt.Params[SFSLabel.DefaultUser];
  142. SFSObject arg = new SFSObject();
  143. arg.PutInt(SFSLabel.CommandID, PlazaRoomReq.MarkAsRobot.GetHashCode());
  144. arg.PutInt(SFSLabel.Data, maxRobotAmt);
  145. arg.PutInt(SFSLabel.RoomID, sfsRoomID);
  146. arg.PutLong(SFSLabel.UserID, RobotConfigID);
  147. SendRequest(arg);
  148. }
  149. private void SendRequest(SFSObject arg)
  150. {
  151. arg = GardenSmartFox.WrapIntoArray(new List<SFSObject> {arg});
  152. SmartFox.Send(new ExtensionRequest(HandlerID.PlazaRoom.GetHashString(), arg));
  153. }
  154. private void SendChestAwardRequest(long chestID)
  155. {
  156. SFSObject arg = PlazaRoomEvent.WrapChestAwardArg(chestID);
  157. SendRequest(arg);
  158. }
  159. private void SendInstantiateRequest(int receiver)
  160. {
  161. SFSManager.GardenSmartFox.EventManager.PlazaRoomEvent.SendInstantiateRequset(User.Id, DressdataIDs.ToArray(), RobotConfigID.ToString(), JoinedTime, Position, Direction, Nickname, receiver);
  162. }
  163. private void OnConnectReturn(BaseEvent evt)
  164. {
  165. if ((bool) evt.Params[SFSLabel.DefaultResult])
  166. {
  167. //Debug.LogWarning("Robot connect succeed");
  168. Login();
  169. }
  170. else
  171. {
  172. //Debug.LogWarning("Robot connect failed");
  173. Deactivate(false);
  174. }
  175. }
  176. private void OnExtensionResponse(BaseEvent evt)
  177. {
  178. string cmd = evt.Params[SFSLabel.DefaultCommand].ToString();
  179. if (cmd == PlazaRoomRep.JoinRoomSucceed.GetHashString())
  180. {
  181. Activate(evt);
  182. }
  183. else if (cmd == PlazaRoomRep.MarkRobotError.GetHashString())
  184. {
  185. Deactivate(false);
  186. }
  187. else if (cmd == PlazaRoomRep.OtherEnterRoom.GetHashString())
  188. {
  189. OnOtherEnterRoom(evt);
  190. }
  191. }
  192. private void OnOtherEnterRoom(BaseEvent evt)
  193. {
  194. ISFSObject arg = (ISFSObject) evt.Params[SFSLabel.DefaultParams];
  195. int userID = arg.GetInt(SFSLabel.UserID);
  196. if (userID != User.Id)
  197. {
  198. SendInstantiateRequest(userID);
  199. }
  200. }
  201. public bool Update()
  202. {
  203. if (SmartFox != null)
  204. {
  205. SmartFox.ProcessEvents();
  206. }
  207. return Behaviour();
  208. }
  209. private bool Activated;
  210. private void Activate(BaseEvent evt)
  211. {
  212. //Debug.LogWarning("Robot Activate");
  213. Activated = true;
  214. MoveTime = Random.Range(MinMoveTime, MaxMoveTime);
  215. LifetimeTime = Random.Range(MinLifetime, MaxLifetime);
  216. CreateChestTime = Random.Range(0, LifetimeTime);
  217. JoinedTime = DateUtil.GetTimeFromSeconds(((ISFSObject) evt.Params[SFSLabel.DefaultParams]).GetLong(SFSLabel.DateTime).ToString());
  218. //Debug.Log(JoinedTime);
  219. SendInstantiateRequest(-1);
  220. }
  221. private bool Behaviour()
  222. {
  223. if (!Activated)
  224. {
  225. return false;
  226. }
  227. if (!SFSManager.GardenSmartFox.PlazaRoomController.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.PlazaRoomController.CurrentRoomData;
  316. int round = Random.Range(1, roomData.MaxPlayer + 1);
  317. int value = Random.Range(MinChestValue, MaxChestValue);
  318. Vector3 playerPos = SFSManager.GardenSmartFox.PlazaRoomController.UserInstanceDictionary[User.Id].Player.transform.position;
  319. Vector3 chestPos = ChestManager.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 < ChestManager.PlazaRoomChests.Count; i++)
  347. {
  348. if (Mathf.Abs(ChestManager.PlazaRoomChests[i].transform.position.x - Position.x) <= MaxChestDistance)
  349. {
  350. if (OperatedChestIDs.Contains(ChestManager.PlazaRoomChests[i].ChestData.ID))
  351. {
  352. //Debug.LogWarning("this chest has been operated");
  353. }
  354. else
  355. {
  356. chests.Add(ChestManager.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. }