gGameMode=1;
gHeartsInHeart = 10;  -- сколько частей в одном большом сердце

--для создания ворон
TomatoChilds = { crow1 = { {0, params=CustomCrow} },tomatos = { {0, params=""} } };
--создание corn
CornChilds = { corns = { {0, params=""} } };
--создание corn
PumpkinChilds = { pumpkin = { {0, params=""} } };

-- получить параметры
function GetParams()
    aObj = GameObject:Get();   
    return aObj.Params;
end
-- взять статистику 
function GetStatics()
    aObj = GameObject:Get();   
    return aObj.Statics;
end

-- инициализация
function OnInit()
    obj = GameObject:Get();
    -- каждое сердечко состоит из gHeartsInHeart частей, отсюда коэф. gHeartsInHeart
    obj.Params.LifeHearts = CPP_GameMessage(12,"get_life_hearts_count",-1) * gHeartsInHeart;
    obj.Params.MaxLifeHearts = obj.Params.LifeHearts;
    obj.Params.deltaDay = obj.Params.levelTime / 26;
    CPP_GameMessage(111,"day",-1);
    obj.cur_number_cycle = 0;

    bonuses.Goal=0;
    bonuses.Car=0;
    bonuses.Telephon=0;
    
    
    if (EndlessUpgrades[1] ~= nil) then
        obj.Params.MaxScoreLimit = EndlessUpgrades[1].score;
    end
    obj.Params.ExpertScoresLimit = obj.Params.MaxScoreLimit;
    obj.Params.WinScoresLimit = obj.Params.MaxScoreLimit;
    --ScriptDump("1");
    if(aObj.NeedProducts)then
        ProductsCount =0;
--[[        
        table.foreach( aObj.NeedProducts, CheckProductsCount );
        --ScriptDump("deflevel.lua:OnInit():ProductsCount:"..ProductsCount);
        if( ProductsCount>0)then
            CPP_GameMessage(6,"",ProductsCount);
            table.foreach( aObj.NeedProducts, CreateNeedProductsList );
        end          
--]]        
    end 
end

--checks the level time
function TimeTrigger()
    aObj = GameObject:Get();
    if (aObj.cur_time == nil) then
        aObj.cur_time = 0;
    end
--[[ --отключим запуск временных апгрейдов    
    if (aObj.cur_time >= aObj.Params.deltaTime) then
        aObj.cur_time = 0;
        if (aObj.cur_number_cycle == nil) then
            aObj.cur_number_cycle = 1;
        else
            aObj.cur_number_cycle = aObj.cur_number_cycle + 1;
        end
        OnElapsedTimeCycle(aObj.cur_number_cycle);
    end
--]]    
    if (aObj.Params.gameEnd == 1) then 
        if( aObj.Params.iDayIsEnd == nil)then
            --CPP_GameMessage(5,"EndDay",0);      
            aObj.Params.iDayIsEnd = true;
        end
        CPP_GameMessage(0,"quit",0);
        return 1;
    end
--[[    
    if (aObj.Params.levelTime <= 0) then 
        aObj.Params.gameEnd = 1;
        CPP_GameMessage(111,"day",2);
    end
--]]
    if (aObj.Params.LifeHearts == 0) then 
        aObj.Params.gameEnd = 1;
        CPP_GameMessage(111,"day",2);
    end
    aObj.Params.levelTime = aObj.Params.levelTime - 1;
    aObj.Params.curDeltaDay = aObj.Params.curDeltaDay + 1;
    if (aObj.Params.curDeltaDay >= aObj.Params.deltaDay) then
        CPP_GameMessage(111,"day",1);
        aObj.Params.curDeltaDay = 0;
    end
    aObj.cur_time = aObj.cur_time + 1;
    return 1;
end

-- для временных апгрейдов
function OnElapsedTimeCycle(aCur_number_cycle)
    --найдем upgrade
    local aUpgradeName = "endless_time_def";
    if (EndlessUpgrades["endless_time_"..aCur_number_cycle] ~= nil) then
        aUpgradeName = "endless_time_"..aCur_number_cycle;
    else
        if (EndlessUpgrades[aUpgradeName] == nil) then return; end
    end
    --ScriptDump("OnElapsedTimeCycle");
    CPP_RecursiveRun(aUpgradeName,1);
end

--для бесконечного уровня
function OnScoreChanged(aScore)
    aObj = GameObject:Get();
    if (aObj.upgrade_score_index == nil) then
        aObj.upgrade_score_index = 1;
        aObj.upgrade_score = 0;
        --local aUpgradeName = "endless_score_"..aObj.upgrade_score_index;
        local aUpgradeName = aObj.upgrade_score_index;
        if (EndlessUpgrades[aUpgradeName] == nil) then
            aObj.upgrade_score = -1;
        else
            aObj.upgrade_score = EndlessUpgrades[aUpgradeName].score;
        end
    end
    if (aObj.upgrade_score < 0) then
        --все использовали
        return;
    end
    if (aScore >= aObj.upgrade_score) then
        OnAppleScoreUpgrade();
    end
end 

function OnAppleScoreUpgrade()
    aObj = GameObject:Get();
    --CPP_RecursiveRun("endless_score_"..aObj.upgrade_score_index,1);
    CPP_RecursiveRun(""..aObj.upgrade_score_index,1);
    
    --ищем следующий
    aObj.upgrade_score_index = aObj.upgrade_score_index + 1;
    --local aUpgradeName = "endless_score_"..aObj.upgrade_score_index;
    local aUpgradeName = aObj.upgrade_score_index;
    local sizeTable = table.getn(EndlessUpgrades);
    if (sizeTable < aUpgradeName or EndlessUpgrades[aUpgradeName] == nil) then
        aObj.upgrade_score = -1;
        SetMaxScoreLimit(999999);
    else
        aObj.upgrade_score = EndlessUpgrades[aUpgradeName].score;
        SetMaxScoreLimit(aObj.upgrade_score);
    end
end

function ChangeOnTomato(aSubID)
    CPP_ReplaceObject(aSubID,'tomato',CustomTomato,'TomatoChilds');
end
function ChangeOnCorn(aSubID)
    CPP_ReplaceObject(aSubID,'corn',CustomCorn,'CornChilds');
end
function ChangeOnPumpkin(aSubID)
    CPP_ReplaceObject(aSubID,'pumpkins',CustomPumpkin,'PumpkinChilds');
end

-- winning level conditions
function isLevelWin()
    return 1;    
end
-- реакция на потерю сердечек
function OnHeartLost(aDeltaHearts)
    aObj = GameObject:Get();
    if (aDeltaHearts < 0) then
        aObj.Params.LifeHearts = aObj.Params.LifeHearts + aDeltaHearts * aObj.Params.LifeHeartsMinus;
        if (aObj.Params.LifeHearts <= 0) then aObj.Params.LifeHearts = 0; end
        return aObj.Params.LifeHearts;
    end
    if (aDeltaHearts > 0) then
        aObj.Params.LifeHearts = aObj.Params.LifeHearts + aDeltaHearts * aObj.Params.LifeHeartsPlus;
        if (aObj.Params.LifeHearts > aObj.Params.MaxLifeHearts) then 
            aObj.Params.LifeHearts = aObj.Params.MaxLifeHearts;
        end
        return aObj.Params.LifeHearts;
    end
    return -1;
end
--поменялся индикатор
function SetMaxScoreLimit(aMax)
    aObj = GameObject:Get();
    aObj.Params.MaxScoreLimit = aMax;
    CPP_GameMessage(112,"MaxScoreLimit",aObj.Params.MaxScoreLimit);
    if (aObj.Statics.score > 0) then
        CPP_GameMessage(5,"WinGame",0);
        CPP_PlaySound("achieved_goal",0);
    end
end

--вызывается когда все продукты отнесены и игрок больше не управляет собыотиями на уровне
function OnFinishLevel()
--[[
    local musik="";
    if( isLevelWin() )then
        musik="win";
    else
        musik="lose";
    end
    CPP_GameMessage(30, musik, 0);   
--]]    
    --CPP_GameMessage(30, "win", 1);   
end

function SetDeltaInLifeCycle(aID,aTask,aDelta)
    if (life_cycle[aID] == nil) then return ""; end
    local objTables = life_cycle[aID];
    local sizeObjTables = table.getn(objTables);
    local objCycle;
    local stepCycle;
    local sizeObjCycle = 0;
    for isds=1,sizeObjTables,1 do
        objCycle = objTables[isds];
        sizeObjCycle = table.getn(objCycle);
        for icycle=1,sizeObjCycle,1 do
            stepCycle = objCycle[icycle];
            if (stepCycle[1] == aTask) then
                stepCycle[2] = stepCycle[2] + aDelta;
--ScriptDump("stepCycle[2]="..stepCycle[2]);
            end
        end
    end
end
