CocosCreator中,按权重取值

    // 根据权重获取值
    // key:可选值;值:权重
    private static getValueByWeight(weightMap: Map): T {
        let targetValue: T = weightMap.keys()[0];
        const curRandomValue: number = randomRange(0, 1);
        let totalWeight = 0;
        for (const v of weightMap.values()) {
            totalWeight += v;
        }

        let curProb = 0;
        for (const k of weightMap.keys()) {
            curProb += weightMap.get(k) / totalWeight;
            if (curProb >= curRandomValue) {
                targetValue = k;
                break;
            }
        }

        return targetValue;
    }

你可能感兴趣的:(CocosCreator中,按权重取值)