123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475 |
- export class Container {
- protected _itemList: Array<{ type: number, count: number }> = null;
- constructor() {
- this._itemList = new Array<{ type: number, count: number }>();
- }
- public addCount(type: number, count: number): { type: number, count: number } {
- return this.addItem({ type: type, count: count });
- }
- public useCount(type: number, count: number): { type: number, count: number } {
- for (let i = 0; i < this._itemList.length; i++) {
- if (this._itemList[i].type == type) {
- if (this._itemList[i].count >= count) {
- this._itemList[i].count -= count;
- return this._itemList[i];
- }
- }
- }
- return null;
- }
- /**
- * 添加物品
- * @param item
- * @returns
- */
- public addItem(item: { type: number, count: number }): { type: number, count: number } {
- for (let i = 0; i < this._itemList.length; i++) {
- if (this._itemList[i].type == item.type) {
- this._itemList[i].count += item.count;
- return this._itemList[i];
- }
- }
- this._itemList.push(item);
- return item;
- }
- public getCount(type: number): number {
- for (let i = 0; i < this._itemList.length; i++) {
- if (this._itemList[i].type == type) {
- return this._itemList[i].count;
- }
- }
- return 0;
- }
- get itemList(): Array<{ type: number, count: number }> {
- return this._itemList;
- }
- set itemList(arr: Array<{ type: number, count: number }>) {
- this._itemList = arr;
- }
- /**
- * 序列化(数据库存储)
- */
- public serialize(): any {
- let list = [];
- for (let i: number = 0; i < this._itemList.length; i++) {
- let item = this._itemList[i];
- list.push({ type: item.type, count: item.count });
- }
- let data = {
- "list": list
- };
- return data;
- }
- /**
- * 反序列化(数据库读取)
- * @param data
- */
- public unserialize(data: any): void {
- if (!data) return;
- let list = data.list;
- this._itemList = [];
- for (let i: number = 0; i < list.length; i++) {
- this._itemList.push({ type: list[i].type, count: list[i].count });
- }
- }
- }
|