BagMgr.js 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. /**
  2. * 背包数据管理
  3. */
  4. let BagMgr = {
  5. // # 物品背包属性
  6. // .DataItemBag {
  7. // id 0: integer # 物品ID
  8. // count 1: integer # 物品数量
  9. // endTime 2: integer # 到期时间戳
  10. // }
  11. _items: [], // 背包基础信息
  12. init() {
  13. if (CC_EDITOR) {
  14. return;
  15. }
  16. this._items = [];
  17. this._initEventListener();
  18. this._initPublishListener();
  19. },
  20. _initEventListener() {
  21. // 通用消息
  22. G.PublicMgr.on(JMC.PUBLIC_MSG.SWITCH_ACCOUNT, JMC.PUBLIC_MSG_ORDER.BAG, this.handleDidSwitchAccount, this);
  23. G.PublicMgr.on(JMC.PUBLIC_MSG.LOGIN_SUCCESS, JMC.PUBLIC_MSG_ORDER.BAG, this.handleDidLoginSuccess, this);
  24. G.PublicMgr.on(JMC.PUBLIC_MSG.DISCONNECTED, JMC.PUBLIC_MSG_ORDER.BAG, this.handleDidDisconnected, this);
  25. },
  26. _initPublishListener() {
  27. cc.game.on('on_user_items', this.handleUpdateItems, this);
  28. },
  29. handleDidLoginSuccess() {
  30. this.requestInfo();
  31. },
  32. handleDidDisconnected() {
  33. },
  34. handleDidSwitchAccount() {
  35. this._items = [];
  36. },
  37. _addItemData(data) {
  38. let isUpdate = false;
  39. for (let [idx, itemData] of Object.entries(this._items)) {
  40. if (itemData.id == data.id) {
  41. isUpdate = true;
  42. if (data.count <= 0) {
  43. // 删除操作
  44. this._items.splice(idx, 1);
  45. } else {
  46. // 更新操作
  47. this._items[idx] = data;
  48. }
  49. break;
  50. }
  51. }
  52. if (!isUpdate && data.count > 0) {
  53. // new操作
  54. this._items.push(data);
  55. }
  56. },
  57. //* ************* 用户信息获取 ************* *//
  58. getItemDataById(itemid) {
  59. for (const data of this._items) {
  60. if (data.id == itemid) {
  61. return data;
  62. }
  63. }
  64. return undefined;
  65. },
  66. getItemNumById(itemid) {
  67. for (const data of this._items) {
  68. if (data.id == itemid) {
  69. return data.count;
  70. }
  71. }
  72. return 0;
  73. },
  74. //* ************* 客户端请求/响应 ************* *//
  75. requestInfo() {
  76. G.NetworkMgr.sendSocketRequest('bag_get_info', {}, this._responseBagGetInfo.bind(this));
  77. },
  78. _responseBagGetInfo(data) {
  79. let responseInfo = data.responseInfo;
  80. if (responseInfo.code === 200) {
  81. // 玩家基础信息
  82. this._items = responseInfo.items;
  83. G.PublicMgr.emit(JMC.PUBLIC_MSG.BAG_INFO);
  84. } else {
  85. // 断开网络并且弹出重连窗口
  86. G.NetworkMgr.closeSocket();
  87. G.AppUtils.getSceneCtrl().showOfflineAlert();
  88. }
  89. },
  90. _onUserItems(data) {
  91. if (!data || !data.items || data.items.length == 0) return;
  92. for (const item of data.items) {
  93. this._addItemData(item);
  94. }
  95. }
  96. }
  97. module.exports = BagMgr;