Container.ts 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. export class Container {
  2. protected _itemList: Array<{ type: number, count: number }> = null;
  3. constructor() {
  4. this._itemList = new Array<{ type: number, count: number }>();
  5. }
  6. public addCount(type: number, count: number): { type: number, count: number } {
  7. return this.addItem({ type: type, count: count });
  8. }
  9. public useCount(type: number, count: number): { type: number, count: number } {
  10. for (let i = 0; i < this._itemList.length; i++) {
  11. if (this._itemList[i].type == type) {
  12. if (this._itemList[i].count >= count) {
  13. this._itemList[i].count -= count;
  14. return this._itemList[i];
  15. }
  16. }
  17. }
  18. return null;
  19. }
  20. /**
  21. * 添加物品
  22. * @param item
  23. * @returns
  24. */
  25. public addItem(item: { type: number, count: number }): { type: number, count: number } {
  26. for (let i = 0; i < this._itemList.length; i++) {
  27. if (this._itemList[i].type == item.type) {
  28. this._itemList[i].count += item.count;
  29. return this._itemList[i];
  30. }
  31. }
  32. this._itemList.push(item);
  33. return item;
  34. }
  35. public getCount(type: number): number {
  36. for (let i = 0; i < this._itemList.length; i++) {
  37. if (this._itemList[i].type == type) {
  38. return this._itemList[i].count;
  39. }
  40. }
  41. return 0;
  42. }
  43. get itemList(): Array<{ type: number, count: number }> {
  44. return this._itemList;
  45. }
  46. set itemList(arr: Array<{ type: number, count: number }>) {
  47. this._itemList = arr;
  48. }
  49. /**
  50. * 序列化(数据库存储)
  51. */
  52. public serialize(): any {
  53. let list = [];
  54. for (let i: number = 0; i < this._itemList.length; i++) {
  55. let item = this._itemList[i];
  56. list.push({ type: item.type, count: item.count });
  57. }
  58. let data = {
  59. "list": list
  60. };
  61. return data;
  62. }
  63. /**
  64. * 反序列化(数据库读取)
  65. * @param data
  66. */
  67. public unserialize(data: any): void {
  68. if (!data) return;
  69. let list = data.list;
  70. this._itemList = [];
  71. for (let i: number = 0; i < list.length; i++) {
  72. this._itemList.push({ type: list[i].type, count: list[i].count });
  73. }
  74. }
  75. }