ServerPython/ZoneServerGroup/map1_8G/MapServer/MapServerData/Script/FormulaControl.py
@@ -33,6 +33,10 @@
#===============================================================================
#---------------------------------------------------------------------
import traceback
import random
import math
#---------------------------------------------------------------------
#公式字典名注册
#注册公式字典名方式 'Facl_DistKey_ + KeyName' (前缀名用于区别策划配置txt公式Key)
@@ -74,3 +78,71 @@
    AllFormulaDist = {}
    #GameWorld.Log('ClearCompileFormulaDist Sucess AllFormulaDist = %s'%(AllFormulaDist))
    return
def Eval(formulaKey, formula, paramDict, toInt=True, ceil=False, playerID=0):
    """ 动态计算
    :param formulaKey: 公式编译缓存key
    :param formula: 公式字符串,如 "int(Atk*10 + MaxHP)"
    :param paramDict: 参数字典,如 {'Atk': 100, 'MaxHP': 5000}
    :param toInt: 是否转为整数
    :param ceil: 是否向上取整
    :return: 计算结果
    """
    compileFormula = GetCompileFormula(formulaKey, formula)
    safe_env = {
        '__builtins__': None,
        # 基础数学函数
        'abs': abs,
        'min': min,
        'max': max,
        'pow': pow,
        'round': round,
        # 类型转换
        'int': int,
        'float': float,
        'bool': bool,
        # 数学常数
        #'pi': math.pi,
        #'e': math.e
    }
    safe_env.update(paramDict)
    try:
        # 执行计算
        value = eval(compileFormula, safe_env)
        if ceil:
            value = math.ceil(value)
        if toInt:
            value = int(value)
        return value
    except:
        import GameWorld
        GameWorld.SendGameErrorEx("FormulaEvalError", "formulaKey:%s, %s, %s" % (formulaKey, paramDict, traceback.format_exc()), playerID)
        return 0
def test():
    attrParamDict={
    'lineupHaloPer': 0, 'awakeTalentPer': 0, 'breakLVPer': 0, 'breakLVValue': 0, 'bookValue': 0, 'lineupStarAddPer': 0, 'lvValue': 0,
    'heroSelfValue': 0, 'awakeTalentValue': 0, 'fetterPer': 0, 'lineupBreakLVAddPer': 0,
    'starTalentValue': 30, 'inheritPer': 1, 'equipValue': 269, 'fetterValue': 0, 'lineupLVAddPer': 0, 'heroSelfPer': 0,
    'bookPer': 0, 'starTalentPer': 0, 'lineupHaloValue': 0, 'lineupInitAddPer': 0
    }
    formula = "(lvValue+equipValue+bookValue)*inheritPer+(heroSelfValue+lineupHaloValue+starTalentValue+breakLVValue+awakeTalentValue)+fetterValue"
    formula = "(lvValue+equipValue+bookValue)*(1+lineupHaloPer+bookPer+lineupInitAddPer+lineupLVAddPer+lineupBreakLVAddPer+lineupStarAddPer)*(inheritPer+fetterPer+starTalentValue+breakLVValue+awakeTalentValue)+heroSelfValue"
    import time
    doCount = 1
    time1 = time.time()
    for _ in xrange(doCount):
        value = Eval("aaa", formula, attrParamDict)
        print  "公式 计算结果: ", value
    print "use time %s" % (time.time() - time1)
    return
## 使用示例
#if __name__ == "__main__":
#    test()