Files
Max-Cocos-Demo/assets/games/scripts/currency/CurrencyManager.ts
2025-10-28 21:55:41 +08:00

65 lines
2.2 KiB
TypeScript

import { _decorator } from "cc";
import { EventManager } from "@max-studio/core/event/EventManager";
import { Singleton } from "@max-studio/core/Singleton";
import LogUtils from "@max-studio/core/utils/LogUtils";
import { CurrencyEventMessage, CurrencyType } from "./Types";
const { ccclass, property } = _decorator;
@ccclass("CurrencyManager")
export class CurrencyManager extends Singleton {
private currencyValues: Record<CurrencyType, number> = {} as Record<CurrencyType, number>;
/** 获取货币值 */
public getCurrencyValue(type: CurrencyType): number {
return this.currencyValues[type] || 0;
}
/** 设置货币值 */
public setCurrencyValue(type: CurrencyType, value: number, isNotify: boolean = true) {
this.currencyValues[type] = value;
if (isNotify) {
EventManager.getInstance().emit(CurrencyEventMessage.CURRENCY_VALUE_CHANGED, type, value);
}
}
/** 格式化货币显示 */
public formatCurrencyDisplay(type: CurrencyType, value?: number): string {
const amount = value ?? this.getCurrencyValue(type);
// 根据货币类型返回不同的格式
if (amount >= 1000000) {
return `${(amount / 1000000).toFixed(1)}M`;
} else if (amount >= 1000) {
return `${(amount / 1000).toFixed(1)}K`;
}
return amount.toString();
}
/** 检查货币是否足够 */
public isCurrencyEnough(type: CurrencyType, amount: number): boolean {
return this.getCurrencyValue(type) >= amount;
}
/** 消耗货币 */
public consumeCurrency(type: CurrencyType, amount: number, isNotify: boolean = true): boolean {
if (amount <= 0) {
LogUtils.warn(`[CurrencyManager] 消耗货币数量必须大于0: ${amount}`);
return false;
}
if (!this.isCurrencyEnough(type, amount)) {
LogUtils.warn(`[CurrencyManager] 货币不足: ${type}, 需要: ${amount}, 当前: ${this.getCurrencyValue(type)}`);
return false;
}
const currentValue = this.getCurrencyValue(type);
const newValue = currentValue - amount;
this.setCurrencyValue(type, newValue, isNotify);
return true;
}
}