Ejemplo n.º 1
0
function sn_ube_simulator_fill_side(&$combat_data, $side_info, $attacker, $player_id = -1)
{
    global $ube_convert_techs;
    $player_id = $player_id == -1 ? count($combat_data[UBE_PLAYERS]) : $player_id;
    foreach ($side_info as $fleet_data) {
        $combat_data[UBE_PLAYERS][$player_id][UBE_NAME] = $attacker ? 'Attacker' : 'Defender';
        $combat_data[UBE_PLAYERS][$player_id][UBE_ATTACKER] = $attacker;
        $combat_data[UBE_FLEETS][$player_id][UBE_OWNER] = $player_id;
        foreach ($fleet_data as $unit_id => $unit_count) {
            if (!$unit_count) {
                continue;
            }
            $unit_type = get_unit_param($unit_id, P_UNIT_TYPE);
            if ($unit_type == UNIT_SHIPS || $unit_type == UNIT_DEFENCE) {
                $combat_data[UBE_FLEETS][$player_id][UBE_COUNT][$unit_id] = $unit_count;
            } elseif ($unit_type == UNIT_RESOURCES) {
                $combat_data[UBE_FLEETS][$player_id][UBE_RESOURCES][$unit_id] = $unit_count;
            } elseif ($unit_type == UNIT_TECHNOLOGIES) {
                $combat_data[UBE_PLAYERS][$player_id][UBE_BONUSES][$ube_convert_techs[$unit_id]] += $unit_count * get_unit_param($unit_id, P_BONUS_VALUE) / 100;
            } elseif ($unit_type == UNIT_GOVERNORS) {
                if ($unit_id == MRC_FORTIFIER) {
                    foreach ($ube_convert_techs as $ube_id) {
                        $combat_data[UBE_FLEETS][$player_id][UBE_BONUSES][$ube_id] += $unit_count * get_unit_param($unit_id, P_BONUS_VALUE) / 100;
                    }
                }
            } elseif ($unit_type == UNIT_MERCENARIES) {
                if ($unit_id == MRC_ADMIRAL) {
                    foreach ($ube_convert_techs as $ube_id) {
                        $combat_data[UBE_PLAYERS][$player_id][UBE_BONUSES][$ube_id] += $unit_count * get_unit_param($unit_id, P_BONUS_VALUE) / 100;
                    }
                }
            }
        }
    }
}
Ejemplo n.º 2
0
function sn_admin_planet_edit_query_string($unit_id, $unit_amount, $mode)
{
    if ($unit_amount && in_array($unit_id, sn_get_groups($mode))) {
        $unit_amount = round($unit_amount);
        $unit_name = get_unit_param($unit_id, P_NAME);
        $result = "{$unit_name} = GREATEST(0, {$unit_name} + ({$unit_amount}))";
    } else {
        $result = '';
    }
    return $result;
}
Ejemplo n.º 3
0
function sn_techtree_view($template = null)
{
    global $lang, $user, $planetrow;
    $tech_tree = array();
    foreach (get_unit_param('techtree') as $unit_group_id => $unit_list) {
        $tech_tree[] = array('NAME' => $lang['tech'][$unit_group_id]);
        foreach ($unit_list as $unit_id) {
            $sn_data_unit = get_unit_param($unit_id);
            $level_basic = $sn_data_unit[P_STACKABLE] ? 0 : mrc_get_level($user, $planetrow, $unit_id, false, true);
            $unit_level = $sn_data_unit[P_STACKABLE] ? 0 : mrc_get_level($user, $planetrow, $unit_id);
            $rendered_info = array('ID' => $unit_id, 'NAME' => $lang['tech'][$unit_id], 'LEVEL' => $unit_level, 'LEVEL_BASIC' => $level_basic, 'LEVEL_BONUS' => max(0, $unit_level - $level_basic), 'LEVEL_MAX' => $sn_data_unit['max']);
            $rendered_info['.']['require'] = unit_requirements_render($user, $planetrow, $unit_id);
            $tech_tree[] = $rendered_info;
        }
    }
    $template = gettemplate('techtree', $template);
    $template_result['.']['techtree'] = $tech_tree;
    $template->assign_recursive($template_result);
    return $template;
}
Ejemplo n.º 4
0
function sn_techtree_view($template = null)
{
    global $lang, $user, $planetrow;
    $tech_tree = array();
    foreach (get_unit_param('techtree') as $unit_group_id => $unit_list) {
        $tech_tree[] = array('NAME' => $lang['tech'][$unit_group_id], 'GROUP_ID' => $unit_group_id);
        foreach ($unit_list as $unit_id) {
            $sn_data_unit = get_unit_param($unit_id);
            $level_basic = $sn_data_unit[P_STACKABLE] ? 0 : mrc_get_level($user, $planetrow, $unit_id, false, true);
            $unit_level = $sn_data_unit[P_STACKABLE] ? 0 : mrc_get_level($user, $planetrow, $unit_id);
            $rendered_info = array('ID' => $unit_id, 'NAME' => $lang['tech'][$unit_id], 'LEVEL' => $unit_level, 'LEVEL_BASIC' => $level_basic, 'LEVEL_BONUS' => max(0, $unit_level - $level_basic), 'LEVEL_MAX' => $sn_data_unit['max']);
            $rendered_info['.']['require'] = unit_requirements_render($user, $planetrow, $unit_id);
            $rendered_info['.']['grants'] = unit_requirements_render($user, $planetrow, $unit_id, P_UNIT_GRANTS);
            $tech_tree[] = $rendered_info;
        }
    }
    $template = gettemplate('techtree', $template);
    $template_result['.']['techtree'] = $tech_tree;
    $template->assign_recursive($template_result);
    $template->assign_vars(array('PAGE_HEADER' => $lang['tech'][UNIT_TECHNOLOGIES], 'PLAYER_OPTION_TECH_TREE_TABLE' => classSupernova::$user_options[PLAYER_OPTION_TECH_TREE_TABLE]));
    return $template;
}
Ejemplo n.º 5
0
function tpl_planet_density_info(&$template, &$density_price_chart, $user_dark_matter)
{
    global $lang;
    $density_base_cost = get_unit_param(UNIT_PLANET_DENSITY, P_COST);
    $density_base_cost = $density_base_cost[RES_DARK_MATTER];
    foreach ($density_price_chart as $density_price_index => &$density_price_data) {
        $density_number_style = pretty_number($density_cost = $density_base_cost * $density_price_data, true, $user_dark_matter, false, false);
        $density_price_data = array('COST' => $density_cost, 'COST_TEXT' => $density_number_style['text'], 'COST_TEXT_CLASS' => $density_number_style['class'], 'REST' => $user_dark_matter - ceil($density_base_cost * $density_price_data), 'ID' => $density_price_index, 'TEXT' => $lang['uni_planet_density_types'][$density_price_index]);
        $template->assign_block_vars('densities', $density_price_data);
    }
}
Ejemplo n.º 6
0
    }
    //  $SubQry = substr($SubQry, 0, -1);
    //  if($SubQry) {
    //    db_planet_set_by_id($planetrow['id'], $SubQry);
    //  }
    !empty($SubQry) ? db_planet_set_by_id($planetrow['id'], implode(',', $SubQry)) : false;
}
// -------------------------------------------------------------------------------------------------------
// $BuildTemp                   = $planetrow[ 'temp_max' ];
// $BuildEnergyTech             = $user['energy_tech'];
for ($Option = 10; $Option >= 0; $Option--) {
    $template->assign_block_vars('option', array('VALUE' => $Option * 10));
}
$caps_real = eco_get_planet_caps($user, $planetrow, 3600);
$template->assign_block_vars('production', array('TYPE' => $lang['res_basic_income'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][0], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][0], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][0], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][0], true, true)));
foreach ($sn_group_factories as $unit_id) {
    if (mrc_get_level($user, $planetrow, $unit_id) > 0 && get_unit_param($unit_id)) {
        $level_plain = mrc_get_level($user, $planetrow, $unit_id, false, true);
        $template->assign_block_vars('production', array('ID' => $unit_id, 'PERCENT' => $planetrow[pname_factory_production_field_name($unit_id)] * 10, 'TYPE' => $lang['tech'][$unit_id], 'LEVEL' => $level_plain, 'LEVEL_BONUS' => mrc_get_level($user, $planetrow, $unit_id) - $level_plain, 'LEVEL_TYPE' => $unit_id > 200 ? $lang['quantity'] : $lang['level'], 'METAL_TYPE' => pretty_number($caps_real['production'][RES_METAL][$unit_id], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['production'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['production'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['production'][RES_ENERGY][$unit_id], true, true), 'METAL_FULL' => pretty_number($caps_real['production_full'][RES_METAL][$unit_id], true, true), 'CRYSTAL_FULL' => pretty_number($caps_real['production_full'][RES_CRYSTAL][$unit_id], true, true), 'DEUTERIUM_FULL' => pretty_number($caps_real['production_full'][RES_DEUTERIUM][$unit_id], true, true), 'ENERGY_FULL' => pretty_number($caps_real['production_full'][RES_ENERGY][$unit_id], true, true), 'SELECT' => $row_select, 'P_MINING_IS_MANAGED' => get_unit_param($unit_id, P_MINING_IS_MANAGED)));
    }
}
$user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
$planet_density_index = $planetrow['density_index'];
$density_price_chart = planet_density_price_chart($planetrow);
tpl_planet_density_info($template, $density_price_chart, $user_dark_matter);
$template->assign_block_vars('production', array('TYPE' => $lang['res_total'], 'METAL_TYPE' => pretty_number($caps_real['total'][RES_METAL], true, true), 'CRYSTAL_TYPE' => pretty_number($caps_real['total'][RES_CRYSTAL], true, true), 'DEUTERIUM_TYPE' => pretty_number($caps_real['total'][RES_DEUTERIUM], true, true), 'ENERGY_TYPE' => pretty_number($caps_real['total'][RES_ENERGY], true, true), 'METAL_FULL' => pretty_number($caps_real['total_production_full'][RES_METAL], true, true), 'CRYSTAL_FULL' => pretty_number($caps_real['total_production_full'][RES_CRYSTAL], true, true), 'DEUTERIUM_FULL' => pretty_number($caps_real['total_production_full'][RES_DEUTERIUM], true, true), 'ENERGY_FULL' => pretty_number($caps_real['total_production_full'][RES_ENERGY], true, true)));
int_calc_storage_bar(RES_METAL);
int_calc_storage_bar(RES_CRYSTAL);
int_calc_storage_bar(RES_DEUTERIUM);
$template->assign_vars(array('PLANET_NAME' => $planetrow['name'], 'PLANET_TYPE' => $planetrow['planet_type'], 'PLANET_DENSITY_INDEX' => $planet_density_index, 'PLANET_CORE_TEXT' => $lang['uni_planet_density_types'][$planet_density_index], 'PRODUCTION_LEVEL' => floor($caps_real['efficiency'] * 100), 'PAGE_HINT' => $lang['res_hint']));
display($template, $lang['res_planet_production']);
Ejemplo n.º 7
0
            sn_db_transaction_rollback();
            break;
        case ACTION_USE:
            art_use($user, $planetrow, $unit_id);
            header("Location: artifacts.php#{$unit_id}");
            ob_end_flush();
            die;
            break;
    }
    message($Message, $lang['tech'][UNIT_ARTIFACTS], 'artifacts.' . PHP_EX, 5);
}
$template = gettemplate('artifacts', true);
foreach ($sn_group_artifacts as $artifact_id) {
    $artifact_level = mrc_get_level($user, array(), $artifact_id, true);
    $build_data = eco_get_build_data($user, $planetrow, $artifact_id, $artifact_level);
    $artifact_data = get_unit_param($artifact_id);
    $artifact_data_bonus = $artifact_data['bonus'];
    $artifact_data_bonus = $artifact_data_bonus >= 0 ? "+{$artifact_data_bonus}" : "{$artifact_data_bonus}";
    switch ($artifact_data['bonus_type']) {
        case BONUS_PERCENT:
            $artifact_data_bonus = "{$artifact_data_bonus}% ";
            break;
        case BONUS_ADD:
            break;
        case BONUS_ABILITY:
            $artifact_data_bonus = '';
            break;
        default:
            break;
    }
    $template->assign_block_vars('artifact', array('ID' => $artifact_id, 'NAME' => $lang['tech'][$artifact_id], 'DESCRIPTION' => $lang['info'][$artifact_id]['description'], 'EFFECT' => $lang['info'][$artifact_id]['effect'], 'COST' => $build_data[BUILD_CREATE][RES_DARK_MATTER], 'COST_TEXT' => pretty_number($build_data[BUILD_CREATE][RES_DARK_MATTER]), 'LEVEL' => intval($artifact_level), 'LEVEL_MAX' => intval($artifact_data['max']), 'BONUS' => $artifact_data_bonus, 'BONUS_TYPE' => $artifact_data['bonus_type'], 'CAN_BUY' => $build_data['CAN'][BUILD_CREATE]));
Ejemplo n.º 8
0
function killer_add_planet($planet)
{
    global $final_cost;
    $final_cost = array();
    $sn_group_resources_loot = sn_get_groups('resources_loot');
    /*
    foreach($sn_group_resources_loot as &$value)
    {
      $value = get_unit_param($value, P_NAME);
    }
    */
    foreach (sn_get_groups('structures') as $unit_id) {
        $build_level = mrc_get_level($user, $planet, $unit_id, true, true);
        if ($build_level > 0) {
            $unit_cost = get_unit_param($unit_id, 'cost');
            $build_factor = $unit_cost['factor'] != 1 ? (1 - pow($unit_cost['factor'], $build_level)) / (1 - $unit_cost['factor']) : $unit_cost['factor'];
            foreach ($sn_group_resources_loot as $resource_id) {
                $final_cost[$resource_id] += isset($unit_cost[$resource_id]) && $unit_cost[$resource_id] > 0 ? floor($unit_cost[$resource_id] * $build_factor) : 0;
            }
        }
    }
    foreach (sn_get_groups(array('defense', 'fleet')) as $unit_id) {
        $unit_count = mrc_get_level($user, $planet, $unit_id, true, true);
        if ($unit_count > 0) {
            $unit_cost = get_unit_param($unit_id, 'cost');
            foreach ($sn_group_resources_loot as $resource_id) {
                $final_cost[$resource_id] += isset($unit_cost[$resource_id]) && $unit_cost[$resource_id] > 0 ? floor($unit_cost[$resource_id] * $unit_count) : 0;
            }
        }
    }
    foreach ($sn_group_resources_loot as $resource_id) {
        $final_cost[$resource_id] += floor(mrc_get_level($user, $planet, $resource_id, true, true));
    }
}
Ejemplo n.º 9
0
function sn_eco_build($que_type, &$auser, &$planet)
{
    global $lang, $config;
    if ($ally_id = sys_get_param_id('ally_id')) {
        define('SN_IN_ALLY', true);
        $ranks = ally_get_ranks($auser['ally']);
        if ($ranks[$auser['ally_rank_id']]['admin'] || $auser['ally']['ally_owner'] == $auser['id']) {
            $user =& $auser['ally']['player'];
            $planet = array('metal' => $user['metal'], 'crystal' => $user['crystal'], 'deuterium' => $user['deuterium']);
        }
    }
    if (!$user) {
        $user =& $auser;
    }
    switch ($action = sys_get_param_escaped('action')) {
        case 'create':
            // Add unit to que for build
        // Add unit to que for build
        case 'destroy':
            // Add unit to que for remove
            $operation_result = que_build($user, $planet, $action == 'destroy' ? BUILD_DESTROY : BUILD_CREATE);
            break;
        case 'trim':
            que_delete($que_type, $user, $planet, false);
            break;
        case 'clear':
            que_delete($que_type, $user, $planet, true);
            break;
    }
    $group_missile = sn_get_groups('missile');
    $silo_capacity_free = 0;
    if ($que_type == QUE_STRUCTURES) {
        $build_unit_list = sn_get_groups('build_allow');
        $build_unit_list = $build_unit_list[$planet['planet_type']];
        $artifact_id = ART_NANO_BUILDER;
        $page_header = $lang['tech'][UNIT_STRUCTURES];
    } elseif ($que_type == QUE_RESEARCH) {
        if (!mrc_get_level($user, $planet, STRUC_LABORATORY)) {
            message($lang['no_laboratory'], $lang['tech'][UNIT_TECHNOLOGIES]);
        }
        if (eco_unit_busy($user, $planet, UNIT_TECHNOLOGIES)) {
            message($lang['eco_bld_msg_err_laboratory_upgrading'], $lang['tech'][UNIT_TECHNOLOGIES]);
        }
        $build_unit_list = sn_get_groups('tech');
        $artifact_id = ART_HEURISTIC_CHIP;
        $page_header = $lang['tech'][UNIT_TECHNOLOGIES] . ($user['user_as_ally'] ? " {$lang['sys_of_ally']} {$user['username']}" : '');
    } elseif ($que_type == QUE_MERCENARY) {
        //    if(!mrc_get_level($user, $planet, STRUC_LABORATORY)) {
        //      message($lang['no_laboratory'], $lang['tech'][UNIT_TECHNOLOGIES]);
        //    }
        //    if(eco_unit_busy($user, $planet, UNIT_TECHNOLOGIES)) {
        //      message($lang['eco_bld_msg_err_laboratory_upgrading'], $lang['tech'][UNIT_TECHNOLOGIES]);
        //    }
        $build_unit_list = sn_get_groups('mercenaries');
        $artifact_id = 0;
        $page_header = $lang['tech'][UNIT_MERCENARIES] . ($user['user_as_ally'] ? " {$lang['sys_of_ally']} {$user['username']}" : '');
    } else {
        if (mrc_get_level($user, $planet, STRUC_FACTORY_HANGAR) == 0) {
            message($lang['need_hangar'], $lang['tech'][STRUC_FACTORY_HANGAR]);
        }
        $build_unit_list = sn_get_groups($page_mode = $que_type == SUBQUE_FLEET ? 'fleet' : 'defense');
        $page_header = $lang[$page_mode];
        $artifact_id = 0;
        $silo_capacity_free = mrc_get_level($user, $planet, STRUC_SILO) * get_unit_param(STRUC_SILO, P_CAPACITY);
        foreach ($group_missile as $unit_id) {
            $silo_capacity_free -= (mrc_get_level($user, $planet, $unit_id, false, true) + (isset($in_que[$unit_id]) && $in_que[$unit_id] ? $in_que[$unit_id] : 0)) * get_unit_param($unit_id, P_UNIT_SIZE);
        }
        $silo_capacity_free = max(0, $silo_capacity_free);
    }
    // Caching values that used more then one time into local variables
    //  $config_resource_multiplier = $config->resource_multiplier;
    $config_resource_multiplier = game_resource_multiplier();
    /*
    // Code for fully working new que system
    $hangar_busy = count($que['que'][QUE_HANGAR]);
    $lab_busy    = count($que['que'][QUE_RESEARCH]) && !$config->BuildLabWhileRun;
    */
    $template = gettemplate('buildings_builds', true);
    if (!empty($operation_result)) {
        $template->assign_block_vars('result', $operation_result);
    }
    $planet_id = $que_type == QUE_RESEARCH || $que_type == QUE_MERCENARY ? 0 : $planet['id'];
    $ques = que_get($user['id'], $planet_id, $que_type);
    $in_que =& $ques['in_que'][$que_type][$user['id']][$planet_id];
    $que =& $ques['ques'][$que_type][$user['id']][$planet_id];
    que_tpl_parse($template, $que_type, $user, $planet, $que);
    $que_length = count($que);
    $can_que_element = $que_length < que_get_max_que_length($user, $planet, $que_type);
    $fleet_list = flt_get_fleets_to_planet($planet);
    $planet_fields_max = eco_planet_fields_max($planet);
    $planet_fields_current = $planet['field_current'];
    $planet_fields_que = is_array($in_que) ? -array_sum($in_que) : 0;
    $planet_fields_free = max(0, $planet_fields_max - $planet_fields_current + $planet_fields_que);
    $planet_fields_queable = $que_type != QUE_STRUCTURES || $planet_fields_free > 0;
    //$planet_temp_max       = $planet['temp_max'];
    $sn_modifiers_resource = sn_get_groups('modifiers');
    $sn_modifiers_resource = $sn_modifiers_resource[MODIFIER_RESOURCE_PRODUCTION];
    $sn_groups_density = sn_get_groups('planet_density');
    $density_info = $sn_groups_density[$planet['density_index']][UNIT_RESOURCES];
    $user_dark_matter = mrc_get_level($user, null, RES_DARK_MATTER);
    foreach ($build_unit_list as $unit_id) {
        $level_base = mrc_get_level($user, $planet, $unit_id, false, true);
        $level_effective = mrc_get_level($user, $planet, $unit_id);
        $level_in_que = $in_que[$unit_id];
        $level_bonus = max(0, $level_effective - $level_base);
        $level_base_and_que = $level_base + $level_in_que;
        $unit_info = get_unit_param($unit_id);
        // pdump($unit_info, '$unit_info');
        $unit_stackable = isset($unit_info[P_STACKABLE]) && $unit_info[P_STACKABLE];
        $build_data = eco_get_build_data($user, $planet, $unit_id, $level_base_and_que);
        // pdump($build_data, '$build_data');
        $temp[RES_METAL] = floor($planet['metal'] + $fleet_list['own']['total'][RES_METAL] - $build_data[BUILD_CREATE][RES_METAL]);
        $temp[RES_CRYSTAL] = floor($planet['crystal'] + $fleet_list['own']['total'][RES_CRYSTAL] - $build_data[BUILD_CREATE][RES_CRYSTAL]);
        $temp[RES_DEUTERIUM] = floor($planet['deuterium'] + $fleet_list['own']['total'][RES_DEUTERIUM] - $build_data[BUILD_CREATE][RES_DEUTERIUM]);
        $temp[RES_DARK_MATTER] = floor($user_dark_matter - $build_data[BUILD_CREATE][RES_DARK_MATTER]);
        $build_data['RESULT'][BUILD_CREATE] = $build_data['RESULT'][BUILD_CREATE] == BUILD_ALLOWED && !$can_que_element ? BUILD_QUE_FULL : $build_data['RESULT'][BUILD_CREATE];
        // Restricting $can_build by resources on planet and (where applicable) with max count per unit
        $can_build = $unit_info[P_MAX_STACK] ? max(0, $unit_info[P_MAX_STACK] - $level_in_que - $level_effective) : $build_data['CAN'][BUILD_CREATE];
        // Restricting $can_build by free silo capacity
        $can_build = ($unit_is_missile = in_array($unit_id, $group_missile)) ? min($can_build, floor($silo_capacity_free / $unit_info[P_UNIT_SIZE])) : $can_build;
        if (!$can_build) {
            if (!$build_data['CAN'][BUILD_CREATE]) {
                $build_data['RESULT'][BUILD_CREATE] = BUILD_NO_RESOURCES;
            } elseif ($unit_is_missile && $silo_capacity_free < $unit_info[P_UNIT_SIZE]) {
                $build_data['RESULT'][BUILD_CREATE] = BUILD_SILO_FULL;
            } elseif ($unit_info[P_MAX_STACK]) {
                $build_data['RESULT'][BUILD_CREATE] = BUILD_MAX_REACHED;
            }
        }
        $build_result_text = $lang['sys_build_result'][$build_data['RESULT'][BUILD_CREATE]];
        $build_result_text = !is_array($build_result_text) ? $build_result_text : (isset($build_result_text[$unit_id]) ? $build_result_text[$unit_id] : $build_result_text[0]);
        $template->assign_block_vars('production', array('ID' => $unit_id, 'NAME' => $lang['tech'][$unit_id], 'DESCRIPTION' => $lang['info'][$unit_id]['description_short'], 'LEVEL_OLD' => $level_base, 'LEVEL_BONUS' => $level_bonus, 'LEVEL_NEXT' => $level_base + $level_in_que + 1, 'LEVEL_QUED' => $level_in_que, 'LEVEL' => $level_base_and_que, 'CAN_BUILD' => $can_build, 'BUILD_CAN' => $build_data['CAN'][BUILD_CREATE], 'TIME' => pretty_time($build_data[RES_TIME][BUILD_CREATE]), 'TIME_SECONDS' => $build_data[RES_TIME][BUILD_CREATE], 'METAL' => $build_data[BUILD_CREATE][RES_METAL], 'METAL_TEXT' => pretty_number($build_data[BUILD_CREATE][RES_METAL], true, $planet['metal']), 'CRYSTAL' => $build_data[BUILD_CREATE][RES_CRYSTAL], 'CRYSTAL_TEXT' => pretty_number($build_data[BUILD_CREATE][RES_CRYSTAL], true, $planet['crystal']), 'DEUTERIUM' => $build_data[BUILD_CREATE][RES_DEUTERIUM], 'DEUTERIUM_TEXT' => pretty_number($build_data[BUILD_CREATE][RES_DEUTERIUM], true, $planet['deuterium']), 'ENERGY' => $build_data[BUILD_CREATE][RES_ENERGY], 'DARK_MATTER' => $build_data[BUILD_CREATE][RES_DARK_MATTER], 'DARK_MATTER_ONLY' => $build_data[P_OPTIONS][P_ONLY_DARK_MATTER], 'BUILD_RESULT' => $build_data['RESULT'][BUILD_CREATE], 'BUILD_RESULT_TEXT' => $build_result_text, 'DESTROY_RESULT' => $build_data['RESULT'][BUILD_DESTROY], 'DESTROY_CAN' => $build_data['CAN'][BUILD_DESTROY], 'DESTROY_TIME' => pretty_time($build_data[RES_TIME][BUILD_DESTROY]), 'DESTROY_METAL' => $build_data[BUILD_DESTROY][RES_METAL], 'DESTROY_CRYSTAL' => $build_data[BUILD_DESTROY][RES_CRYSTAL], 'DESTROY_DEUTERIUM' => $build_data[BUILD_DESTROY][RES_DEUTERIUM], 'METAL_REST' => pretty_number($temp[RES_METAL], true, true), 'CRYSTAL_REST' => pretty_number($temp[RES_CRYSTAL], true, true), 'DEUTERIUM_REST' => pretty_number($temp[RES_DEUTERIUM], true, true), 'DARK_MATTER_REST' => pretty_number($temp[RES_DARK_MATTER], true, true), 'METAL_REST_NUM' => $temp[RES_METAL], 'CRYSTAL_REST_NUM' => $temp[RES_CRYSTAL], 'DEUTERIUM_REST_NUM' => $temp[RES_DEUTERIUM], 'DARK_MATTER_REST_NUM' => $temp[RES_DARK_MATTER], 'UNIT_BUSY' => eco_unit_busy($user, $planet, $que, $unit_id), 'MAP_IS_RESOURCE' => !empty($unit_info['production'])));
        if ($unit_stackable) {
            $level_production_base = array('ACTUAL_SHIELD' => pretty_number(mrc_modify_value($user, false, array(MRC_ADMIRAL, TECH_SHIELD), $unit_info['shield'])), 'ACTUAL_ARMOR' => pretty_number(mrc_modify_value($user, false, array(MRC_ADMIRAL, TECH_ARMOR), $unit_info['armor'])), 'ACTUAL_WEAPON' => pretty_number(mrc_modify_value($user, false, array(MRC_ADMIRAL, TECH_WEAPON), $unit_info['attack'])));
            if ($unit_info[P_UNIT_TYPE] == UNIT_SHIPS) {
                $ship_data = get_ship_data($unit_id, $user);
                $level_production_base += array('ACTUAL_SPEED' => pretty_number($ship_data['speed']), 'ACTUAL_CONSUMPTION' => pretty_number($ship_data['consumption']), 'ACTUAL_CAPACITY' => pretty_number($ship_data['capacity']));
            }
            if ($unit_info['production']) {
                foreach ($unit_info['production'] as $resource_id => $resource_calc) {
                    if ($resource_income = floor(mrc_modify_value($user, $planet, $sn_modifiers_resource, $resource_calc(1, 10, $user, $planet) * $config_resource_multiplier * (isset($density_info[$resource_id]) ? $density_info[$resource_id] : 1)))) {
                        $level_production_base['R' . $resource_id] = $resource_income;
                    }
                }
            }
            $template->assign_block_vars('production.resource', $level_production_base);
        } elseif ($unit_info['production']) {
            $level_production_base = array();
            $element_level_start = $level_effective + $in_que[$unit_id];
            foreach ($unit_info['production'] as $resource_id => $resource_calc) {
                if ($resource_income = floor(mrc_modify_value($user, $planet, $sn_modifiers_resource, $resource_calc($element_level_start, 10, $user, $planet) * $config_resource_multiplier * (isset($density_info[$resource_id]) ? $density_info[$resource_id] : 1)))) {
                    $level_production_base[$resource_id] = $resource_income;
                }
            }
            $level_start = $level_base_and_que > 1 ? $level_effective + $level_in_que - 1 : 1;
            for ($i = 0; $i < 6; $i++) {
                $level_production = array('LEVEL' => $level_start + $i);
                foreach ($unit_info['production'] as $resource_id => $resource_calc) {
                    if ($resource_income = floor(mrc_modify_value($user, $planet, $sn_modifiers_resource, $resource_calc($level_start + $i, 10, $user, $planet) * $config_resource_multiplier * (isset($density_info[$resource_id]) ? $density_info[$resource_id] : 1)))) {
                        $level_production['R' . $resource_id] = $resource_income;
                        $level_production['D' . $resource_id] = $resource_income - $level_production_base[$resource_id];
                    }
                }
                $template->assign_block_vars('production.resource', $level_production);
            }
        } elseif ($unit_id == TECH_ASTROTECH) {
            $element_level_start = $level_effective + $in_que[$unit_id];
            /*
            foreach($unit_info['production'] as $resource_id => $resource_calc) {
              if($resource_income = floor(mrc_modify_value($user, $planet, $sn_modifiers_resource, $resource_calc($element_level_start, 10, $user, $planet) * $config_resource_multiplier * (isset($density_info[$resource_id]) ? $density_info[$resource_id] : 1)))) {
                $level_production_base[$resource_id] = $resource_income;
              }
            }
            */
            $level_production_base = array(UNIT_PLAYER_EXPEDITIONS_MAX => get_player_max_expeditons($user, $element_level_start), UNIT_PLAYER_COLONIES_MAX => get_player_max_colonies($user, $element_level_start));
            $level_start = $level_base_and_que > 1 ? $level_effective + $level_in_que - 1 : 1;
            for ($i = 0; $i < 6; $i++) {
                $level_production = array('LEVEL' => $level_start + $i);
                $level_production['R' . UNIT_PLAYER_EXPEDITIONS_MAX] = get_player_max_expeditons($user, $level_start + $i);
                $level_production['D' . UNIT_PLAYER_EXPEDITIONS_MAX] = $level_production['R' . UNIT_PLAYER_EXPEDITIONS_MAX] - $level_production_base[UNIT_PLAYER_EXPEDITIONS_MAX];
                $level_production['R' . UNIT_PLAYER_COLONIES_MAX] = get_player_max_colonies($user, $level_start + $i);
                $level_production['D' . UNIT_PLAYER_COLONIES_MAX] = $level_production['R' . UNIT_PLAYER_COLONIES_MAX] - $level_production_base[UNIT_PLAYER_COLONIES_MAX];
                /*
                        foreach($unit_info['production'] as $resource_id => $resource_calc) {
                          if($resource_income = floor(mrc_modify_value($user, $planet, $sn_modifiers_resource, $resource_calc($level_start + $i, 10, $user, $planet) * $config_resource_multiplier * (isset($density_info[$resource_id]) ? $density_info[$resource_id] : 1)))) {
                            $level_production['R'.$resource_id] = $resource_income;
                            $level_production['D'.$resource_id] = $resource_income - $level_production_base[$resource_id];
                          }
                        }
                        $template->assign_block_vars('production.resource', $level_production);
                */
                $template->assign_block_vars('production.resource', $level_production);
                $level_production_base = array(UNIT_PLAYER_EXPEDITIONS_MAX => $level_production['R' . UNIT_PLAYER_EXPEDITIONS_MAX], UNIT_PLAYER_COLONIES_MAX => $level_production['R' . UNIT_PLAYER_COLONIES_MAX]);
            }
        }
        //pdump(unit_requirements_render($user, $planet, $unit_id));
        foreach (unit_requirements_render($user, $planet, $unit_id) as $requirement) {
            $template->assign_block_vars('production.require', $requirement);
        }
    }
    $sector_cost = eco_get_build_data($user, $planet, UNIT_SECTOR, mrc_get_level($user, $planet, UNIT_SECTOR), true);
    $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
    $template->assign_vars(array('ALLY_ID' => $user['user_as_ally'], 'QUE_ID' => $que_type, 'SHOW_SECTORS' => $que_type == QUE_STRUCTURES, 'FLEET_OWN_COUNT' => $fleet_list['own']['count'], 'ARTIFACT_ID' => $artifact_id, 'ARTIFACT_LEVEL' => mrc_get_level($user, array(), $artifact_id), 'ARTIFACT_NAME' => $lang['tech'][$artifact_id], 'REQUEST_URI' => urlencode($_SERVER['REQUEST_URI']), 'PAGE_HEADER' => $page_header, 'TIME_NOW' => SN_TIME_NOW, 'PLN_ID' => $planet['id'], 'METAL' => $planet['metal'], 'CRYSTAL' => $planet['crystal'], 'DEUTERIUM' => $planet['deuterium'], 'DARK_MATTER' => $user_dark_matter, 'METAL_INCOMING' => $fleet_list['own']['total'][RES_METAL], 'CRYSTAL_INCOMING' => $fleet_list['own']['total'][RES_CRYSTAL], 'DEUTERIUM_INCOMING' => $fleet_list['own']['total'][RES_DEUTERIUM], 'FIELDS_CURRENT' => $planet_fields_current, 'FIELDS_MAX' => $planet_fields_max, 'FIELDS_FREE' => $planet_fields_free, 'FIELDS_QUE' => $planet_fields_que == 0 ? '' : $planet_fields_que > 0 ? "+{$planet_fields_que}" : $planet_fields_que, 'QUE_HAS_PLACE' => $can_que_element, 'QUE_HAS_FIELDS' => $planet_fields_queable, 'PAGE_HINT' => $lang['eco_bld_page_hint'], 'PLANET_TYPE' => $planet['planet_type'], 'SECTOR_CAN_BUY' => $sector_cost <= mrc_get_level($user, null, RES_DARK_MATTER), 'SECTOR_COST' => $sector_cost, 'SECTOR_COST_TEXT' => pretty_number($sector_cost), 'STACKABLE' => $unit_stackable, 'TEMPORARY' => intval($config->empire_mercenary_temporary && $que_type == QUE_MERCENARY), 'STRING_CREATE' => $que_type == QUE_MERCENARY ? $lang['bld_hire'] : ($que_type == QUE_RESEARCH ? $lang['bld_research'] : $lang['bld_create']), 'STRING_BUILD_TIME' => $que_type == QUE_RESEARCH ? $lang['ResearchTime'] : $lang['ConstructionTime'], 'U_opt_int_struc_vertical' => $user['option_list'][OPT_INTERFACE]['opt_int_struc_vertical']));
    display(parsetemplate($template));
    // , $lang['Builds']
}
Ejemplo n.º 10
0
function tpl_parse_planet($planet)
{
    global $lang;
    $fleet_list = flt_get_fleets_to_planet($planet);
    $que = que_get($planet['id_owner'], $planet['id'], false);
    $structure_que = tpl_parse_planet_que($que, $planet, QUE_STRUCTURES);
    // TODO Заменить на que_tpl_parse_element($que_element);
    $structure_que_first = is_array($structure_que['que']) ? reset($structure_que['que']) : array();
    $hangar_que = tpl_parse_planet_que($que, $planet, SUBQUE_FLEET);
    // TODO Заменить на que_tpl_parse_element($que_element);
    $hangar_que_first = is_array($hangar_que['que']) ? reset($hangar_que['que']) : array();
    $defense_que = tpl_parse_planet_que($que, $planet, SUBQUE_DEFENSE);
    // TODO Заменить на que_tpl_parse_element($que_element);
    $defense_que_first = is_array($defense_que['que']) ? reset($defense_que['que']) : array();
    $result = array('ID' => $planet['id'], 'NAME' => $planet['name'], 'IMAGE' => $planet['image'], 'GALAXY' => $planet['galaxy'], 'SYSTEM' => $planet['system'], 'PLANET' => $planet['planet'], 'TYPE' => $planet['planet_type'], 'COORDINATES' => uni_render_coordinates($planet), 'METAL_PERCENT' => $planet['metal_mine_porcent'] * 10, 'CRYSTAL_PERCENT' => $planet['crystal_mine_porcent'] * 10, 'DEUTERIUM_PERCENT' => $planet['deuterium_sintetizer_porcent'] * 10, 'STRUCTURE' => isset($structure_que_first['id']) ? $lang['tech'][$structure_que_first['id']] : '', 'HANGAR' => isset($hangar_que_first['id']) ? $lang['tech'][$hangar_que_first['id']] : '', 'hangar_que' => $hangar_que, 'DEFENSE' => isset($defense_que_first['id']) ? $lang['tech'][$defense_que_first['id']] : '', 'defense_que' => $defense_que, 'FIELDS_CUR' => $planet['field_current'], 'FIELDS_MAX' => eco_planet_fields_max($planet), 'FILL' => min(100, floor($planet['field_current'] / eco_planet_fields_max($planet) * 100)), 'FLEET_OWN' => $fleet_list['own']['count'], 'FLEET_ENEMY' => $fleet_list['enemy']['count'], 'FLEET_NEUTRAL' => $fleet_list['neutral']['count'], 'fleet_list' => $fleet_list, 'PLANET_GOVERNOR_ID' => $planet['PLANET_GOVERNOR_ID'], 'PLANET_GOVERNOR_NAME' => $lang['tech'][$planet['PLANET_GOVERNOR_ID']], 'PLANET_GOVERNOR_LEVEL' => $planet['PLANET_GOVERNOR_LEVEL'], 'PLANET_GOVERNOR_LEVEL_MAX' => get_unit_param($planet['PLANET_GOVERNOR_ID'], P_MAX_STACK));
    if (!empty($que['ques'][QUE_STRUCTURES][$planet['id_owner']][$planet['id']])) {
        $result['building_que'] = array();
        $building_que =& $que['ques'][QUE_STRUCTURES][$planet['id_owner']][$planet['id']];
        foreach ($building_que as $que_element) {
            $result['building_que'][] = que_tpl_parse_element($que_element);
        }
    }
    return $result;
}
Ejemplo n.º 11
0
function sn_eco_can_build_unit($user, $planet, $unit_id, &$result)
{
    global $config;
    $result = isset($result) ? $result : BUILD_ALLOWED;
    $result = $result == BUILD_ALLOWED && eco_unit_busy($user, $planet, $unit_id) ? BUILD_UNIT_BUSY : $result;
    $unit_param = get_unit_param($unit_id);
    if ($unit_param[P_UNIT_TYPE] != UNIT_MERCENARIES || !$config->empire_mercenary_temporary) {
        $requirement =& $unit_param[P_REQUIRE];
        if ($result == BUILD_ALLOWED && $requirement) {
            foreach ($requirement as $require_id => $require_level) {
                if (mrc_get_level($user, $planet, $require_id) < $require_level) {
                    $result = BUILD_REQUIRE_NOT_MEET;
                    break;
                }
            }
        }
    }
    return $result;
}
Ejemplo n.º 12
0
function sn_ube_combat_prepare_first_round(&$combat_data)
{
    global $ube_combat_bonus_list, $ube_convert_to_techs;
    // Готовим информацию для первого раунда - проводим все нужные вычисления из исходных данных
    $first_round_data = array();
    foreach ($combat_data[UBE_FLEETS] as $fleet_id => &$fleet_info) {
        $fleet_info[UBE_COUNT] = is_array($fleet_info[UBE_COUNT]) ? $fleet_info[UBE_COUNT] : array();
        $player_data =& $combat_data[UBE_PLAYERS][$fleet_info[UBE_OWNER]];
        $fleet_info[UBE_FLEET_TYPE] = $player_data[UBE_ATTACKER] ? UBE_ATTACKERS : UBE_DEFENDERS;
        foreach ($ube_combat_bonus_list as $bonus_id => $bonus_value) {
            // Вычисляем бонус игрока
            $bonus_value = isset($player_data[UBE_BONUSES][$bonus_id]) ? $player_data[UBE_BONUSES][$bonus_id] : 0;
            // Добавляем к бонусам флота бонусы игрока
            $fleet_info[UBE_BONUSES][$bonus_id] += $bonus_value;
        }
        $first_round_data[$fleet_id][UBE_COUNT] = $fleet_info[UBE_PRICE] = array();
        foreach ($fleet_info[UBE_COUNT] as $unit_id => $unit_count) {
            if ($unit_count <= 0) {
                continue;
            }
            $unit_info = get_unit_param($unit_id);
            // Заполняем информацию о кораблях в информации флота
            foreach ($ube_combat_bonus_list as $bonus_id => $bonus_value) {
                $fleet_info[$bonus_id][$unit_id] = floor($unit_info[$ube_convert_to_techs[$bonus_id]] * (1 + $fleet_info[UBE_BONUSES][$bonus_id]));
            }
            $fleet_info[UBE_AMPLIFY][$unit_id] = $unit_info[P_AMPLIFY];
            // TODO: Переделать через get_ship_data()
            $fleet_info[UBE_CAPACITY][$unit_id] = $unit_info[P_CAPACITY];
            $fleet_info[UBE_TYPE][$unit_id] = $unit_info[P_UNIT_TYPE];
            // TODO: Переделать через список ресурсов
            $fleet_info[UBE_PRICE][RES_METAL][$unit_id] = $unit_info[P_COST][RES_METAL];
            $fleet_info[UBE_PRICE][RES_CRYSTAL][$unit_id] = $unit_info[P_COST][RES_CRYSTAL];
            $fleet_info[UBE_PRICE][RES_DEUTERIUM][$unit_id] = $unit_info[P_COST][RES_DEUTERIUM];
            $fleet_info[UBE_PRICE][RES_DARK_MATTER][$unit_id] = $unit_info[P_COST][RES_DARK_MATTER];
            // Копируем её в информацию о первом раунде
            $first_round_data[$fleet_id][UBE_ARMOR][$unit_id] = $fleet_info[UBE_ARMOR][$unit_id] * $unit_count;
            $first_round_data[$fleet_id][UBE_COUNT][$unit_id] = $unit_count;
            $first_round_data[$fleet_id][UBE_ARMOR_REST][$unit_id] = $fleet_info[UBE_ARMOR][$unit_id];
            $first_round_data[$fleet_id][UBE_SHIELD_REST][$unit_id] = $fleet_info[UBE_SHIELD][$unit_id];
        }
    }
    $combat_data[UBE_ROUNDS][0][UBE_FLEETS] = $first_round_data;
    $combat_data[UBE_ROUNDS][1][UBE_FLEETS] = $first_round_data;
    sn_ube_combat_round_prepare($combat_data, 0);
}
Ejemplo n.º 13
0
/**
 * MissionCaseRecycling.php
 *
 * @version 1.0
 * @copyright 2008 By Chlorel for XNova
 */
function flt_mission_recycle(&$mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $destination_planet =& $mission_data['dst_planet'];
    if (!$fleet_row) {
        return CACHE_NOTHING;
    }
    if (!isset($destination_planet['id'])) {
        // doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        flt_send_back($mission_data['fleet']);
        return CACHE_FLEET;
    }
    global $lang;
    $RecyclerCapacity = 0;
    $OtherFleetCapacity = 0;
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    foreach ($fleet_array as $unit_id => $unit_count) {
        if (in_array($unit_id, sn_get_groups('fleet'))) {
            $capacity = get_unit_param($unit_id, P_CAPACITY) * $unit_count;
            if (in_array($unit_id, sn_get_groups('flt_recyclers'))) {
                $RecyclerCapacity += $capacity;
            } else {
                $OtherFleetCapacity += $capacity;
            }
        }
    }
    $IncomingFleetGoods = $fleet_row["fleet_resource_metal"] + $fleet_row["fleet_resource_crystal"] + $fleet_row["fleet_resource_deuterium"];
    if ($IncomingFleetGoods > $OtherFleetCapacity) {
        $RecyclerCapacity -= $IncomingFleetGoods - $OtherFleetCapacity;
    }
    if ($destination_planet["debris_metal"] + $destination_planet["debris_crystal"] <= $RecyclerCapacity) {
        $RecycledGoods["metal"] = $destination_planet["debris_metal"];
        $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
    } else {
        if ($destination_planet["debris_metal"] > $RecyclerCapacity / 2 and $destination_planet["debris_crystal"] > $RecyclerCapacity / 2) {
            $RecycledGoods["metal"] = $RecyclerCapacity / 2;
            $RecycledGoods["crystal"] = $RecyclerCapacity / 2;
        } else {
            if ($destination_planet["debris_metal"] > $destination_planet["debris_crystal"]) {
                $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                if ($destination_planet["debris_metal"] > $RecyclerCapacity - $RecycledGoods["crystal"]) {
                    $RecycledGoods["metal"] = $RecyclerCapacity - $RecycledGoods["crystal"];
                } else {
                    $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                }
            } else {
                $RecycledGoods["metal"] = $destination_planet["debris_metal"];
                if ($destination_planet["debris_crystal"] > $RecyclerCapacity - $RecycledGoods["metal"]) {
                    $RecycledGoods["crystal"] = $RecyclerCapacity - $RecycledGoods["metal"];
                } else {
                    $RecycledGoods["crystal"] = $destination_planet["debris_crystal"];
                }
            }
        }
    }
    $NewCargo['Metal'] = $fleet_row["fleet_resource_metal"] + $RecycledGoods["metal"];
    $NewCargo['Crystal'] = $fleet_row["fleet_resource_crystal"] + $RecycledGoods["crystal"];
    $NewCargo['Deuterium'] = $fleet_row["fleet_resource_deuterium"];
    db_planet_set_by_gspt($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], PT_PLANET, "`debris_metal` = `debris_metal` - '{$RecycledGoods['metal']}', `debris_crystal` = `debris_crystal` - '{$RecycledGoods['crystal']}'");
    $Message = sprintf($lang['sys_recy_gotten'], pretty_number($RecycledGoods["metal"]), $lang['Metal'], pretty_number($RecycledGoods["crystal"]), $lang['Crystal']);
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_RECYCLE, $lang['sys_mess_spy_control'], $lang['sys_recy_report'], $Message);
    $QryUpdateFleet = "UPDATE {{fleets}} SET `fleet_mess` = 1,`fleet_resource_metal` = '{$NewCargo['Metal']}',`fleet_resource_crystal` = '{$NewCargo['Crystal']}',`fleet_resource_deuterium` = '{$NewCargo['Deuterium']}' ";
    $QryUpdateFleet .= "WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;";
    doquery($QryUpdateFleet);
    return CACHE_FLEET | CACHE_PLANET_DST;
}
Ejemplo n.º 14
0
     while ($user_row = db_fetch($user_query)) {
         foreach ($sn_group_tech as $tech_id) {
             if ($tech_level = intval($user_row[get_unit_param($tech_id, P_NAME)])) {
                 $que_lines[] = "({$user_row['id']}," . LOC_USER . ",{$user_row['id']}," . UNIT_TECHNOLOGIES . ",{$tech_id},{$tech_level})";
             }
         }
     }
     if (!empty($que_lines)) {
         upd_do_query("INSERT INTO {{unit}} (unit_player_id, unit_location_type, unit_location_id, unit_type, unit_snid, unit_level) VALUES " . implode(',', $que_lines));
     }
     upd_alter_table('users', array("DROP COLUMN `graviton_tech`"), $update_tables['users']['graviton_tech']);
 }
 if (!$update_indexes['unit']['I_unit_record_search']) {
     upd_alter_table('unit', array("ADD KEY `I_unit_record_search` (`unit_snid`,`unit_player_id`,`unit_level` DESC,`unit_id`)"), !$update_indexes['unit']['I_unit_record_search']);
     foreach (sn_get_groups(array('structures', 'fleet', 'defense')) as $unit_id) {
         $planet_units[get_unit_param($unit_id, P_NAME)] = 1;
     }
     $drop_index = array();
     $create_index =& $drop_index;
     // array();
     foreach ($planet_units as $unit_name => $unit_create) {
         if ($update_indexes['planets']['I_' . $unit_name]) {
             $drop_index[] = "DROP KEY I_{$unit_name}";
         }
         if ($update_indexes['planets']['i_' . $unit_name]) {
             $drop_index[] = "DROP KEY i_{$unit_name}";
         }
         if ($unit_create) {
             $create_index[] = "ADD KEY `I_{$unit_name}` (`id_owner`, {$unit_name} DESC)";
         }
     }
Ejemplo n.º 15
0
function sn_sn_powerup_get_price_matrix($powerup_id, $powerup_unit = false, $level_max = null, $plain = false, &$result)
{
    global $sn_powerup_buy_discounts;
    $result = array();
    $powerup_data = get_unit_param($powerup_id);
    //pdump($powerup_data, '$powerup_data');
    $is_upgrade = !empty($powerup_unit) && $powerup_unit;
    // pdump($powerup_unit, '$powerup_unit');
    $level_current = $term_original = $time_left = 0;
    if ($is_upgrade) {
        $time_finish = strtotime($powerup_unit['unit_time_finish']);
        $time_left = max(0, $time_finish - SN_TIME_NOW);
        if ($time_left > 0) {
            $term_original = $time_finish - strtotime($powerup_unit['unit_time_start']);
            $level_current = $powerup_unit['unit_level'];
        }
    }
    $level_max = $level_max > $powerup_data[P_MAX_STACK] ? $level_max : $powerup_data[P_MAX_STACK];
    $original_cost = 0;
    for ($i = 1; $i <= $level_max; $i++) {
        $base_cost = eco_get_total_cost($powerup_id, $i);
        $base_cost = $base_cost[BUILD_CREATE][RES_DARK_MATTER];
        foreach ($sn_powerup_buy_discounts as $period => $discount) {
            $upgrade_price = floor($base_cost * $discount * $period / PERIOD_MONTH);
            $result[$i][$period] = $upgrade_price;
            $original_cost = $is_upgrade && $i == $level_current && $period <= $term_original ? $upgrade_price : $original_cost;
        }
    }
    if ($is_upgrade && $time_left) {
        $term_original = round($term_original / PERIOD_DAY);
        $time_left = min(floor($time_left / PERIOD_DAY), $term_original);
        $cost_left = $term_original > 0 ? ceil($time_left / $term_original * $original_cost) : 0;
        array_walk_recursive($result, function (&$value) use($cost_left) {
            $value -= $cost_left;
        });
    }
    return $result;
}
Ejemplo n.º 16
0
function mrc_mercenary_render($user)
{
    global $config, $lang, $sn_powerup_buy_discounts;
    $mode = sys_get_param_int('mode', UNIT_MERCENARIES);
    $mode = in_array($mode, array(UNIT_MERCENARIES, UNIT_PLANS)) ? $mode : UNIT_MERCENARIES;
    $is_permanent = $mode == UNIT_PLANS || !$config->empire_mercenary_temporary;
    if ($mercenary_id = sys_get_param_int('mercenary_id')) {
        $operation_result = mrc_mercenary_hire($mode, $user, $mercenary_id);
    }
    lng_include('infos');
    $template = gettemplate('mrc_mercenary_hire', true);
    if (!empty($operation_result)) {
        $template->assign_block_vars('result', $operation_result);
    }
    foreach ($sn_powerup_buy_discounts as $hire_period => $hire_discount) {
        $template->assign_block_vars('period', array('LENGTH' => $hire_period, 'TEXT' => $lang['mrc_period_list'][$hire_period], 'DISCOUNT' => $hire_period / $config->empire_mercenary_base_period * $hire_discount, 'SELECTED' => $hire_period == $config->empire_mercenary_base_period));
    }
    $user_dark_matter = mrc_get_level($user, '', RES_DARK_MATTER);
    $cost_alliance_multiplyer = SN_IN_ALLY === true && $mode == UNIT_PLANS ? $config->ali_bonus_members : 1;
    $cost_alliance_multiplyer = $cost_alliance_multiplyer >= 1 ? $cost_alliance_multiplyer : 1;
    foreach (sn_get_groups($mode == UNIT_PLANS ? 'plans' : 'mercenaries') as $mercenary_id) {
        $mercenary = get_unit_param($mercenary_id);
        $mercenary_bonus = $mercenary['bonus'];
        $mercenary_bonus = $mercenary_bonus >= 0 ? "+{$mercenary_bonus}" : "{$mercenary_bonus}";
        switch ($mercenary['bonus_type']) {
            case BONUS_PERCENT:
                $mercenary_bonus = "{$mercenary_bonus}% ";
                break;
            case BONUS_ABILITY:
                $mercenary_bonus = '';
                break;
            case BONUS_ADD:
            default:
                break;
        }
        $mercenary_level = mrc_get_level($user, null, $mercenary_id, false, true);
        $mercenary_level_bonus = max(0, mrc_get_level($user, null, $mercenary_id) - $mercenary_level);
        $total_cost_old = 0;
        if ($is_permanent) {
            $total_cost_old = eco_get_total_cost($mercenary_id, $mercenary_level);
            $total_cost_old = $total_cost_old[BUILD_CREATE][RES_DARK_MATTER] * $cost_alliance_multiplyer;
        }
        $total_cost = eco_get_total_cost($mercenary_id, $mercenary_level + 1);
        $total_cost[BUILD_CREATE][RES_DARK_MATTER] *= $cost_alliance_multiplyer;
        $mercenary_unit = classSupernova::db_get_unit_by_location($user['id'], LOC_USER, $user['id'], $mercenary_id);
        $mercenary_time_finish = strtotime($mercenary_unit['unit_time_finish']);
        $template->assign_block_vars('officer', array('ID' => $mercenary_id, 'NAME' => $lang['tech'][$mercenary_id], 'DESCRIPTION' => $lang['info'][$mercenary_id]['description'], 'EFFECT' => $lang['info'][$mercenary_id]['effect'], 'COST' => $total_cost[BUILD_CREATE][RES_DARK_MATTER] - $total_cost_old, 'COST_TEXT' => pretty_number($total_cost[BUILD_CREATE][RES_DARK_MATTER] - $total_cost_old, 0, $user_dark_matter), 'LEVEL' => $mercenary_level, 'LEVEL_BONUS' => $mercenary_level_bonus, 'LEVEL_MAX' => $mercenary['max'], 'BONUS' => $mercenary_bonus, 'BONUS_TYPE' => $mercenary['bonus_type'], 'HIRE_END' => $mercenary_time_finish && $mercenary_time_finish >= SN_TIME_NOW ? date(FMT_DATE_TIME, $mercenary_time_finish) : '', 'CAN_BUY' => mrc_officer_accessible($user, $mercenary_id)));
        $upgrade_cost = 1;
        for ($i = $config->empire_mercenary_temporary ? 1 : $mercenary_level + 1; $mercenary['max'] ? $i <= $mercenary['max'] : $upgrade_cost <= $user_dark_matter; $i++) {
            $total_cost = eco_get_total_cost($mercenary_id, $i);
            $total_cost[BUILD_CREATE][RES_DARK_MATTER] *= $cost_alliance_multiplyer;
            $upgrade_cost = $total_cost[BUILD_CREATE][RES_DARK_MATTER] - $total_cost_old;
            $template->assign_block_vars('officer.level', array('VALUE' => $i, 'PRICE' => $upgrade_cost));
        }
    }
    $template->assign_vars(array('PAGE_HEADER' => $lang['tech'][$mode], 'MODE' => $mode, 'IS_PERMANENT' => intval($is_permanent), 'EMPIRE_MERCENARY_TEMPORARY' => $config->empire_mercenary_temporary, 'DARK_MATTER' => $user_dark_matter));
    display(parsetemplate($template), $lang['tech'][$mode]);
}
Ejemplo n.º 17
0
 * 1.4st - Security checks & tests by Gorlum for http://supernova.ws
 * @version 1.4
 * @copyright 2008 by Chlorel for XNova
 */
include 'common.' . substr(strrchr(__FILE__, '.'), 1);
if (HIDE_BUILDING_RECORDS) {
    return;
}
$template = gettemplate('records', true);
$user_skip_list_data = sys_stat_get_user_skip_list();
$user_skip_list = empty($user_skip_list_data) ? '' : ' AND p.id_owner NOT IN (' . implode(',', $user_skip_list_data) . ')';
$user_skip_list_un = empty($user_skip_list_data) ? '' : ' AND un.unit_player_id NOT IN (' . implode(',', $user_skip_list_data) . ')';
$user_skip_list_unit = empty($user_skip_list_data) ? '' : ' AND unit_player_id NOT IN (' . implode(',', $user_skip_list_data) . ')';
$show_groups = array(UNIT_TECHNOLOGIES => 'tech', UNIT_STRUCTURES => 'structures', UNIT_STRUCTURES_SPECIAL => 'structures', UNIT_SHIPS => 'fleet', UNIT_DEFENCE => 'defense');
$user_name_cache = array();
foreach ($show_groups as $unit_group_id => $mode) {
    $template->assign_block_vars('records', array('UNIT' => $lang['tech'][$unit_group_id], 'COUNT' => in_array($unit_group_id, array(UNIT_STRUCTURES, UNIT_STRUCTURES_SPECIAL, UNIT_TECHNOLOGIES)) ? $lang['sys_level_max'] : $lang['sys_quantity_total'], 'HEADER' => true));
    $unit_group = get_unit_param('techtree', $unit_group_id);
    // TODO - REWRITE!!!!
    foreach ($unit_group as $unit_id) {
        $unit_name =& $lang['tech'][$unit_id];
        if ($unit_name) {
            // TODO - ISUNITSTACKABLE!
            $data_row = $unit_group_id == UNIT_SHIPS || $unit_group_id == UNIT_DEFENCE ? db_unit_records_sum($unit_id, $user_skip_list_unit) : db_unit_records_plain($unit_id, $user_skip_list_unit);
            if ($data_row) {
                $template->assign_block_vars('records', array('UNIT' => $unit_name, 'USER' => $data_row['username'] ? js_safe_string($data_row['username']) : $lang['rec_rien'], 'COUNT' => $data_row['unit_level'] ? pretty_number($data_row['unit_level']) : $lang['rec_rien']));
            }
        }
    }
}
display($template, $lang['rec_title']);
Ejemplo n.º 18
0
function sn_flt_can_attack($planet_src, $planet_dst, $fleet = array(), $mission, $options = false, &$result)
{
    //TODO: try..catch
    global $config, $user;
    if ($user['vacation']) {
        return $result = ATTACK_OWN_VACATION;
    }
    if (empty($fleet) || !is_array($fleet)) {
        return $result = ATTACK_NO_FLEET;
    }
    $sn_groups_mission = sn_get_groups('missions');
    if (!isset($sn_groups_mission[$mission])) {
        return $result = ATTACK_MISSION_ABSENT;
    }
    $sn_data_mission = $sn_groups_mission[$mission];
    //TODO: Проверка на отстуствие ресурсов в нетранспортных миссиях (Транспорт, Передислокация, Колонизация)
    //TODO: Проверка на наличие ресурсов при Транспорте
    // TODO: Проверка на отрицательные ресурсы при транспорте
    // TODO: Проверка на перегрузку при транспорте
    // TODO: В ракетных миссиях могут лететь только ракеты
    // TODO: В неракетных миссиях ракеты должны отсутствовать
    $ships = 0;
    $recyclers = 0;
    $spies = 0;
    $resources = 0;
    $ship_ids = sn_get_groups('fleet');
    $resource_ids = sn_get_groups('resources_loot');
    foreach ($fleet as $ship_id => $ship_count) {
        $is_ship = in_array($ship_id, $ship_ids);
        $is_resource = in_array($ship_id, $resource_ids);
        if (!$is_ship && !$is_resource) {
            // TODO Спецобработчик для Капитана и модулей
            //      return ATTACK_WRONG_UNIT;
        }
        if ($ship_count < 0) {
            return $result = $is_ship ? ATTACK_SHIP_COUNT_WRONG : ATTACK_RESOURCE_COUNT_WRONG;
        }
        if ($ship_count > mrc_get_level($user, $planet_src, $ship_id)) {
            // TODO ATTACK_NO_MISSILE
            return $result = $is_ship ? ATTACK_NO_SHIPS : ATTACK_NO_RESOURCES;
        }
        if ($is_ship) {
            $single_ship_data = get_ship_data($ship_id, $user);
            if ($single_ship_data[P_SPEED] <= 0) {
                return $result = ATTACK_ZERO_SPEED;
            }
            $ships += $ship_count;
            $recyclers += in_array($ship_id, sn_get_groups('flt_recyclers')) ? $ship_count : 0;
            $spies += $ship_id == SHIP_SPY ? $ship_count : 0;
        } elseif ($is_resource) {
            $resources += $ship_count;
        }
    }
    /*
      if($ships <= 0)
      {
        return ATTACK_NO_FLEET;
      }
    */
    if (isset($options['resources']) && $options['resources'] > 0 && !(isset($sn_data_mission['transport']) && $sn_data_mission['transport'])) {
        return $result = ATTACK_RESOURCE_FORBIDDEN;
    }
    /*
      elseif($mission == MT_TRANSPORT)
      {
        return ATTACK_TRANSPORT_EMPTY;
      }
    */
    $speed = $options['fleet_speed_percent'];
    if ($speed && ($speed != intval($speed) || $speed < 1 || $speed > 10)) {
        return $result = ATTACK_WRONG_SPEED;
    }
    $travel_data = flt_travel_data($user, $planet_src, $planet_dst, $fleet, $options['fleet_speed_percent']);
    if (mrc_get_level($user, $planet_src, RES_DEUTERIUM) < $fleet[RES_DEUTERIUM] + $travel_data['consumption']) {
        return $result = ATTACK_NO_FUEL;
    }
    if ($travel_data['consumption'] > $travel_data['capacity']) {
        return $result = ATTACK_TOO_FAR;
    }
    if ($travel_data['hold'] < $resources) {
        return $result = ATTACK_OVERLOADED;
    }
    $fleet_start_time = SN_TIME_NOW + $travel_data['duration'];
    $fleet_group = $options['fleet_group'];
    if ($fleet_group) {
        if ($mission != MT_AKS) {
            return $result = ATTACK_WRONG_MISSION;
        }
        $acs = doquery("SELECT * FROM {{aks}} WHERE id = '{$fleet_group}' LIMIT 1;", '', true);
        if (!$acs['id']) {
            return $result = ATTACK_NO_ACS;
        }
        if ($planet_dst['galaxy'] != $acs['galaxy'] || $planet_dst['system'] != $acs['system'] || $planet_dst['planet'] != $acs['planet'] || $planet_dst['planet_type'] != $acs['planet_type']) {
            return $result = ATTACK_ACS_WRONG_TARGET;
        }
        if ($fleet_start_time > $acs['ankunft']) {
            return $result = ATTACK_ACS_TOO_LATE;
        }
    }
    $flying_fleets = $options['flying_fleets'];
    if (!$flying_fleets) {
        $flying_fleets = doquery("SELECT COUNT(fleet_id) AS `flying_fleets` FROM {{fleets}} WHERE `fleet_owner` = '{$user['id']}';", '', true);
        $flying_fleets = $flying_fleets['flying_fleets'];
    }
    if (GetMaxFleets($user) <= $flying_fleets && $mission != MT_MISSILE) {
        return $result = ATTACK_NO_SLOTS;
    }
    // В одиночку шпионские зонды могут летать только в миссии Шпионаж, Передислокация и Транспорт
    if ($ships && $spies && $spies == $ships && !($mission == MT_SPY || $mission == MT_RELOCATE || $mission == MT_TRANSPORT)) {
        return $result = ATTACK_SPIES_LONLY;
    }
    // Checking for no planet
    if (!$planet_dst['id_owner']) {
        if ($mission == MT_COLONIZE && !$fleet[SHIP_COLONIZER]) {
            return $result = ATTACK_NO_COLONIZER;
        }
        if ($mission == MT_EXPLORE || $mission == MT_COLONIZE) {
            return $result = ATTACK_ALLOWED;
        }
        return $result = ATTACK_NO_TARGET;
    }
    if ($mission == MT_RECYCLE) {
        if ($planet_dst['debris_metal'] + $planet_dst['debris_crystal'] <= 0) {
            return $result = ATTACK_NO_DEBRIS;
        }
        if ($recyclers <= 0) {
            return $result = ATTACK_NO_RECYCLERS;
        }
        return $result = ATTACK_ALLOWED;
    }
    // Got planet. Checking if it is ours
    if ($planet_dst['id_owner'] == $user['id']) {
        if ($mission == MT_TRANSPORT || $mission == MT_RELOCATE) {
            return $result = ATTACK_ALLOWED;
        }
        return $planet_src['id'] == $planet_dst['id'] ? ATTACK_SAME : ATTACK_OWN;
    }
    // No, planet not ours. Cutting mission that can't be send to not-ours planet
    if ($mission == MT_RELOCATE || $mission == MT_COLONIZE || $mission == MT_EXPLORE) {
        return $result = ATTACK_WRONG_MISSION;
    }
    $enemy = db_user_by_id($planet_dst['id_owner']);
    // We cannot attack or send resource to users in VACATION mode
    if ($enemy['vacation'] && $mission != MT_RECYCLE) {
        return $result = ATTACK_VACATION;
    }
    // Multi IP protection
    // TODO: Here we need a procedure to check proxies
    if (sys_is_multiaccount($user, $enemy)) {
        return $result = ATTACK_SAME_IP;
    }
    $user_points = $user['total_points'];
    $enemy_points = $enemy['total_points'];
    // Is it transport? If yes - checking for buffing to prevent mega-alliance destroyer
    if ($mission == MT_TRANSPORT) {
        if ($user_points >= $enemy_points || $config->allow_buffing) {
            return $result = ATTACK_ALLOWED;
        } else {
            return $result = ATTACK_BUFFING;
        }
    }
    // Only aggresive missions passed to this point. HOLD counts as passive but aggresive
    // Is it admin with planet protection?
    if ($planet_dst['id_level'] > $user['authlevel']) {
        return $result = ATTACK_ADMIN;
    }
    // Okay. Now skipping protection checks for inactive longer then 1 week
    if (!$enemy['onlinetime'] || $enemy['onlinetime'] >= SN_TIME_NOW - 60 * 60 * 24 * 7) {
        if ($enemy_points <= $config->game_noob_points && $user_points > $config->game_noob_points || $config->game_noob_factor && $user_points > $enemy_points * $config->game_noob_factor) {
            if ($mission != MT_HOLD) {
                return $result = ATTACK_NOOB;
            }
            if ($mission == MT_HOLD && !($user['ally_id'] && $user['ally_id'] == $enemy['ally_id'] && $config->ally_help_weak)) {
                return $result = ATTACK_NOOB;
            }
        }
    }
    // Is it HOLD mission? If yes - there should be ally deposit
    if ($mission == MT_HOLD) {
        if (mrc_get_level($user, $planet_dst, STRUC_ALLY_DEPOSIT)) {
            return $result = ATTACK_ALLOWED;
        }
        return $result = ATTACK_NO_ALLY_DEPOSIT;
    }
    if ($mission == MT_SPY) {
        return $result = $spies >= 1 ? ATTACK_ALLOWED : ATTACK_NO_SPIES;
    }
    // Is it MISSILE mission?
    if ($mission == MT_MISSILE) {
        $sn_data_mip = get_unit_param(UNIT_DEF_MISSILE_INTERPLANET);
        if (mrc_get_level($user, $planet_src, STRUC_SILO) < $sn_data_mip[P_REQUIRE][STRUC_SILO]) {
            return $result = ATTACK_NO_SILO;
        }
        if (!$fleet[UNIT_DEF_MISSILE_INTERPLANET]) {
            return $result = ATTACK_NO_MISSILE;
        }
        $distance = abs($planet_dst['system'] - $planet_src['system']);
        $mip_range = flt_get_missile_range($user);
        if ($distance > $mip_range || $planet_dst['galaxy'] != $planet_src['galaxy']) {
            return $result = ATTACK_MISSILE_TOO_FAR;
        }
        if (isset($options['target_structure']) && $options['target_structure'] && !in_array($options['target_structure'], sn_get_groups('defense_active'))) {
            return $result = ATTACK_WRONG_STRUCTURE;
        }
    }
    if ($mission == MT_DESTROY && $planet_dst['planet_type'] != PT_MOON) {
        return $result = ATTACK_WRONG_MISSION;
    }
    if ($mission == MT_ATTACK || $mission == MT_AKS || $mission == MT_DESTROY) {
        return $result = flt_bashing_check($user, $enemy, $planet_dst, $mission, $travel_data['duration'], $fleet_group);
    }
    return $result = ATTACK_ALLOWED;
}
Ejemplo n.º 19
0
function eco_get_planet_caps(&$user, &$planet_row, $production_time = 0)
{
    // TODO Считать $production_time для термоядерной электростанции
    global $config;
    static $sn_group_modifiers, $config_resource_multiplier, $config_eco_scale_storage;
    if (!$sn_group_modifiers) {
        $sn_group_modifiers = sn_get_groups('modifiers');
        // $config_resource_multiplier = $config->resource_multiplier;
        $config_resource_multiplier = game_resource_multiplier();
        $config_eco_scale_storage = $config->eco_scale_storage ? $config_resource_multiplier : 1;
    }
    $caps = array();
    foreach (sn_get_groups('storages') as $unit_id) {
        foreach (get_unit_param($unit_id, P_STORAGE) as $resource_id => $function) {
            $caps['storage'][$resource_id][$unit_id] = floor($config_eco_scale_storage * mrc_modify_value($user, $planet_row, $sn_group_modifiers[MODIFIER_RESOURCE_CAPACITY], $function(mrc_get_level($user, $planet_row, $unit_id))));
        }
    }
    if ($planet_row['planet_type'] == PT_MOON) {
        return $caps;
    }
    $sn_group_planet_density = sn_get_groups('planet_density');
    $planet_density = $sn_group_planet_density[$planet_row['density_index']][UNIT_RESOURCES];
    $caps['production_full'][RES_METAL][0] = floor($config->metal_basic_income * $config_resource_multiplier * (isset($planet_density[RES_METAL]) ? $planet_density[RES_METAL] : 1));
    $caps['production_full'][RES_CRYSTAL][0] = floor($config->crystal_basic_income * $config_resource_multiplier * (isset($planet_density[RES_CRYSTAL]) ? $planet_density[RES_CRYSTAL] : 1));
    $caps['production_full'][RES_DEUTERIUM][0] = floor($config->deuterium_basic_income * $config_resource_multiplier * (isset($planet_density[RES_DEUTERIUM]) ? $planet_density[RES_DEUTERIUM] : 1));
    $caps['production_full'][RES_ENERGY][0] = floor($config->energy_basic_income * $config_resource_multiplier * (isset($planet_density[RES_ENERGY]) ? $planet_density[RES_ENERGY] : 1));
    foreach (sn_get_groups('factories') as $unit_id) {
        $unit_data = get_unit_param($unit_id);
        $unit_level = mrc_get_level($user, $planet_row, $unit_id);
        $unit_load = $planet_row[pname_factory_production_field_name($unit_id)];
        foreach ($unit_data['production'] as $resource_id => $function) {
            $caps['production_full'][$resource_id][$unit_id] = $function($unit_level, $unit_load, $user, $planet_row) * $config_resource_multiplier * (isset($planet_density[$resource_id]) ? $planet_density[$resource_id] : 1);
        }
    }
    array_walk_recursive($caps['production_full'], 'eco_get_planet_caps_modify_production', array('user' => $user, 'planet' => $planet_row));
    foreach ($caps['production_full'] as $resource_id => $resource_data) {
        $caps['total_production_full'][$resource_id] = array_sum($resource_data);
    }
    $caps['production'] = $caps['production_full'];
    if ($caps['production'][RES_ENERGY][STRUC_MINE_FUSION]) {
        $deuterium_balance = array_sum($caps['production'][RES_DEUTERIUM]);
        $energy_balance = array_sum($caps['production'][RES_ENERGY]);
        if ($deuterium_balance < 0 || $energy_balance < 0) {
            $caps['production'][RES_DEUTERIUM][STRUC_MINE_FUSION] = $caps['production'][RES_ENERGY][STRUC_MINE_FUSION] = 0;
        }
    }
    foreach ($caps['production'][RES_ENERGY] as $energy) {
        $caps[RES_ENERGY][$energy >= 0 ? BUILD_CREATE : BUILD_DESTROY] += $energy;
    }
    $caps[RES_ENERGY][BUILD_DESTROY] = -$caps[RES_ENERGY][BUILD_DESTROY];
    $caps['efficiency'] = $caps[RES_ENERGY][BUILD_DESTROY] > $caps[RES_ENERGY][BUILD_CREATE] ? $caps[RES_ENERGY][BUILD_CREATE] / $caps[RES_ENERGY][BUILD_DESTROY] : 1;
    foreach ($caps['production'] as $resource_id => &$resource_data) {
        if ($caps['efficiency'] != 1) {
            foreach ($resource_data as $unit_id => &$resource_production) {
                if (!($unit_id == STRUC_MINE_FUSION && $resource_id == RES_DEUTERIUM) && $unit_id != 0 && !($resource_id == RES_ENERGY && $resource_production >= 0)) {
                    $resource_production = $resource_production * $caps['efficiency'];
                }
            }
        }
        $caps['total'][$resource_id] = array_sum($resource_data);
        $caps['total'][$resource_id] = $caps['total'][$resource_id] >= 0 ? floor($caps['total'][$resource_id]) : ceil($caps['total'][$resource_id]);
    }
    foreach ($caps['storage'] as $resource_id => &$resource_data) {
        $caps['total_storage'][$resource_id] = array_sum($resource_data);
    }
    $planet_row['caps'] = $caps;
    $planet_row['metal_max'] = $caps['total_storage'][RES_METAL];
    $planet_row['crystal_max'] = $caps['total_storage'][RES_CRYSTAL];
    $planet_row['deuterium_max'] = $caps['total_storage'][RES_DEUTERIUM];
    $planet_row['energy_max'] = $caps[RES_ENERGY][BUILD_CREATE];
    $planet_row['energy_used'] = $caps[RES_ENERGY][BUILD_DESTROY];
    return $caps;
}
Ejemplo n.º 20
0
function sn_imperium_view($template = null)
{
    global $user, $lang;
    $planets = array();
    $ques = array();
    $sn_group_factories = sn_get_groups('factories');
    $planet_density = sn_get_groups('planet_density');
    if (sys_get_param('save_production')) {
        $production = sys_get_param('percent');
        if (is_array($production) && !empty($production)) {
            // sn_db_transaction_start();
            $query = array();
            $planet_row_list = db_planet_list_sorted($user, false, '*');
            // while($planet = db_fetch($planet_row_list))
            foreach ($planet_row_list as $planet) {
                foreach ($sn_group_factories as $factory_unit_id) {
                    $unit_db_name_porcent = pname_factory_production_field_name($factory_unit_id);
                    if (get_unit_param($factory_unit_id, P_MINING_IS_MANAGED) && isset($production[$factory_unit_id][$planet['id']]) && ($actual_porcent = intval($production[$factory_unit_id][$planet['id']] / 10)) >= 0 && $actual_porcent <= 10 && $actual_porcent != $planet[$unit_db_name_porcent]) {
                        $query[$planet['id']][] = "{$unit_db_name_porcent} = {$actual_porcent}";
                    }
                }
            }
            foreach ($query as $planet_id => $query_data) {
                db_planet_set_by_id($planet_id, implode(',', $query_data));
            }
            // sn_db_transaction_commit();
        }
    }
    $planet_row_list = db_planet_list_sorted($user);
    // while ($planet = db_fetch($planet_row_list))
    foreach ($planet_row_list as $planet) {
        sn_db_transaction_start();
        $global_data = sys_o_get_updated($user, $planet['id'], SN_TIME_NOW, false, true);
        $planets[$planet['id']] = $global_data['planet'];
        // $ques[$planet['id']] = que_get($user['id'], $planet['id'], false);
        $ques[$planet['id']] = $global_data['que'];
        sn_db_transaction_commit();
    }
    $template = gettemplate('imperium', $template);
    $template->assign_var('amount', count($planets) + 2);
    for ($i = 100; $i >= 0; $i -= 10) {
        $template->assign_block_vars('percent', array('PERCENT' => $i));
    }
    $fleet_id = 1;
    $fleets = array();
    $total['temp_min'] = 1000;
    $total['temp_max'] = -999;
    foreach ($planets as $planet_index => &$planet) {
        $list_planet_que = $ques[$planet_index];
        $planet_template = tpl_parse_planet($planet);
        $planet_fleet_id = 0;
        $fleet_list = $planet_template['fleet_list'];
        //flt_get_fleets_to_planet($planet);
        if ($fleet_list['own']['count']) {
            $planet_fleet_id = "p{$fleet_id}";
            $fleets[] = tpl_parse_fleet_sn($fleet_list['own']['total'], $planet_fleet_id);
            $fleet_id++;
        }
        $template->assign_block_vars('planet', array_merge($planet_template, array('PLANET_FLEET_ID' => $planet_fleet_id, 'METAL_CUR' => pretty_number($planet['metal'], true, $planet['caps']['total_storage'][RES_METAL]), 'METAL_PROD' => pretty_number($planet['caps']['total'][RES_METAL]), 'CRYSTAL_CUR' => pretty_number($planet['crystal'], true, $planet['caps']['total_storage'][RES_CRYSTAL]), 'CRYSTAL_PROD' => pretty_number($planet['caps']['total'][RES_CRYSTAL]), 'DEUTERIUM_CUR' => pretty_number($planet['deuterium'], true, $planet['caps']['total_storage'][RES_DEUTERIUM]), 'DEUTERIUM_PROD' => pretty_number($planet['caps']['total'][RES_DEUTERIUM]), 'ENERGY_CUR' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE] - $planet['caps'][RES_ENERGY][BUILD_DESTROY], true, true), 'ENERGY_MAX' => pretty_number($planet['caps'][RES_ENERGY][BUILD_CREATE]), 'TEMP_MIN' => $planet['temp_min'], 'TEMP_MAX' => $planet['temp_max'], 'DENSITY_CLASS' => $planet['density_index'], 'DENSITY_RICHNESS' => $planet_density[$planet['density_index']][UNIT_PLANET_DENSITY_RICHNESS], 'DENSITY_CLASS_TEXT' => $lang['uni_planet_density_types'][$planet['density_index']])));
        $planet['fleet_list'] = $planet_template['fleet_list'];
        $planet['BUILDING_ID'] = $planet_template['BUILDING_ID'];
        $planet['hangar_que'] = $planet_template['hangar_que'];
        $planet['full_que'] = $list_planet_que;
        $total['fields'] += $planet['field_current'];
        $total['metal'] += $planet['metal'];
        $total['crystal'] += $planet['crystal'];
        $total['deuterium'] += $planet['deuterium'];
        $total['energy'] += $planet['energy_max'] - $planet['energy_used'];
        $total['fields_max'] += eco_planet_fields_max($planet);
        $total['metal_perhour'] += $planet['caps']['total'][RES_METAL];
        $total['crystal_perhour'] += $planet['caps']['total'][RES_CRYSTAL];
        $total['deuterium_perhour'] += $planet['caps']['total'][RES_DEUTERIUM];
        $total['energy_max'] += $planet['caps'][RES_ENERGY][BUILD_CREATE];
        $total['temp_min'] = min($planet['temp_min'], $total['temp_min']);
        $total['temp_max'] = max($planet['temp_max'], $total['temp_max']);
    }
    tpl_assign_fleet($template, $fleets);
    unset($planet);
    $show_groups = array(UNIT_STRUCTURES => 'structures', UNIT_STRUCTURES_SPECIAL => 'structures', UNIT_SHIPS => 'fleet', UNIT_DEFENCE => 'defense');
    foreach ($show_groups as $unit_group_id => $mode) {
        $template->assign_block_vars('prods', array('NAME' => $lang['tech'][$unit_group_id]));
        $unit_group = get_unit_param('techtree', $unit_group_id);
        foreach ($unit_group as $unit_id) {
            $unit_count = $unit_count_abs = 0;
            $block_vars = array();
            $unit_is_factory = in_array($unit_id, $sn_group_factories) && get_unit_param($unit_id, P_MINING_IS_MANAGED);
            // $unit_db_name = pname_resource_name($unit_id);
            foreach ($planets as $planet) {
                $unit_level_plain = mrc_get_level($user, $planet, $unit_id, false, true);
                $level_plus['FACTORY'] = $unit_is_factory;
                $level_plus['LEVEL_PLUS_YELLOW'] = 0;
                $level_plus['LEVEL_PLUS_GREEN'] = 0;
                $level_plus['PERCENT'] = $unit_is_factory ? $unit_level_plain ? $planet[pname_factory_production_field_name($unit_id)] * 10 : -1 : -1;
                switch ($mode) {
                    /*
                    case 'structures':
                      $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
                      if($level_plus_build)
                      {
                        $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
                        $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
                      }
                    break;
                    */
                    /** @noinspection PhpMissingBreakStatementInspection */
                    case 'fleet':
                        $level_plus['LEVEL_PLUS_YELLOW'] = $planet['fleet_list']['own']['total'][$unit_id] <= 0 ? $planet['fleet_list']['own']['total'][$unit_id] : "+{$planet['fleet_list']['own']['total'][$unit_id]}";
                        $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'] += $level_plus['LEVEL_PLUS_YELLOW'];
                    case 'structures':
                    case 'defense':
                        $level_plus_build = $ques[$planet['id']]['in_que'][que_get_unit_que($unit_id)][$user['id']][$planet['id']][$unit_id];
                        if ($level_plus_build) {
                            $level_plus['LEVEL_PLUS_GREEN'] = $level_plus_build < 0 ? $level_plus_build : "+{$level_plus_build}";
                            // $level_plus['LEVEL_PLUS_GREEN'] = "+{$level_plus_build}";
                            $total['units'][$unit_id]['LEVEL_PLUS_GREEN'] += $level_plus['LEVEL_PLUS_GREEN'];
                        }
                        break;
                    default:
                        break;
                }
                $block_vars[] = array_merge($level_plus, array('ID' => $planet['id'], 'TYPE' => $planet['planet_type'], 'LEVEL' => $unit_level_plain == 0 && !$level_plus['LEVEL_PLUS_YELLOW'] && !$level_plus['LEVEL_PLUS_GREEN'] ? '-' : $unit_level_plain));
                $unit_count += $unit_level_plain;
                $unit_count_abs += $unit_level_plain + abs($level_plus['LEVEL_PLUS_YELLOW']) + abs($level_plus['LEVEL_PLUS_GREEN']);
            }
            if ($unit_count_abs) {
                $template->assign_block_vars('prods', array('ID' => $unit_id, 'FIELD' => 'unit_' . $unit_id, 'NAME' => $lang['tech'][$unit_id], 'MODE' => $mode));
                foreach ($block_vars as $block_var) {
                    $template->assign_block_vars('prods.planet', $block_var);
                }
                $unit_green = $total['units'][$unit_id]['LEVEL_PLUS_GREEN'];
                $unit_yellow = $total['units'][$unit_id]['LEVEL_PLUS_YELLOW'];
                $template->assign_block_vars('prods.planet', array('ID' => 0, 'LEVEL' => $unit_count, 'LEVEL_PLUS_GREEN' => $unit_green == 0 ? '' : ($unit_green > 0 ? "+{$unit_green}" : $unit_green), 'LEVEL_PLUS_YELLOW' => $unit_yellow == 0 ? '' : ($unit_yellow > 0 ? "+{$unit_yellow}" : $unit_yellow), 'PERCENT' => $unit_is_factory ? '' : -1, 'FACTORY' => $unit_is_factory));
            }
        }
    }
    $template->assign_block_vars('planet', array_merge(array('ID' => 0, 'NAME' => $lang['sys_total'], 'FIELDS_CUR' => $total['fields'], 'FIELDS_MAX' => $total['fields_max'], 'METAL_CUR' => pretty_number($total['metal']), 'METAL_PROD' => pretty_number($total['metal_perhour']), 'CRYSTAL_CUR' => pretty_number($total['crystal']), 'CRYSTAL_PROD' => pretty_number($total['crystal_perhour']), 'DEUTERIUM_CUR' => pretty_number($total['deuterium']), 'DEUTERIUM_PROD' => pretty_number($total['deuterium_perhour']), 'ENERGY_CUR' => pretty_number($total['energy']), 'ENERGY_MAX' => pretty_number($total['energy_max']), 'TEMP_MIN' => $total['temp_min'], 'TEMP_MAX' => $total['temp_max'])));
    $template->assign_vars(array('COLONIES_CURRENT' => get_player_current_colonies($user), 'COLONIES_MAX' => get_player_max_colonies($user), 'EXPEDITIONS_CURRENT' => get_player_current_expeditions($user), 'EXPEDITIONS_MAX' => get_player_max_expeditons($user), 'PLANET_DENSITY_RICHNESS_NORMAL' => PLANET_DENSITY_RICHNESS_NORMAL, 'PLANET_DENSITY_RICHNESS_AVERAGE' => PLANET_DENSITY_RICHNESS_AVERAGE, 'PLANET_DENSITY_RICHNESS_GOOD' => PLANET_DENSITY_RICHNESS_GOOD, 'PLANET_DENSITY_RICHNESS_PERFECT' => PLANET_DENSITY_RICHNESS_PERFECT));
    //$template->assign_recursive($template_result);
    return $template;
}
Ejemplo n.º 21
0
function int_planet_pretemplate($planetrow, &$template)
{
    global $lang;
    $governor_id = $planetrow['PLANET_GOVERNOR_ID'];
    $template->assign_vars(array('PLANET_ID' => $planetrow['id'], 'PLANET_NAME' => htmlentities($planetrow['name'], ENT_QUOTES, 'UTF-8'), 'PLANET_NAME_JS' => htmlentities(js_safe_string($planetrow['name']), ENT_QUOTES, 'UTF-8'), 'PLANET_GALAXY' => $planetrow['galaxy'], 'PLANET_SYSTEM' => $planetrow['system'], 'PLANET_PLANET' => $planetrow['planet'], 'PLANET_TYPE' => $planetrow['planet_type'], 'PLANET_TYPE_TEXT' => $lang['sys_planet_type'][$planetrow['planet_type']], 'PLANET_DEBRIS' => $planetrow['debris_metal'] + $planetrow['debris_crystal'], 'PLANET_GOVERNOR_ID' => $governor_id, 'PLANET_GOVERNOR_NAME' => $lang['tech'][$governor_id], 'PLANET_GOVERNOR_LEVEL' => $planetrow['PLANET_GOVERNOR_LEVEL'], 'PLANET_GOVERNOR_LEVEL_MAX' => get_unit_param($governor_id, P_MAX_STACK)));
}
Ejemplo n.º 22
0
             //  => 'Игрок купил Губернатора %1$s ID %2$d уровня %3$d на планету %4$s',
             // die();
         }
         sn_db_transaction_commit();
         sys_redirect('overview.php?mode=manage');
         die;
     }
     lng_include('mrc_mercenary');
     int_planet_pretemplate($planetrow, $template);
     foreach (sn_get_groups('governors') as $governor_id) {
         if ($planetrow['planet_type'] == PT_MOON && $governor_id == MRC_TECHNOLOGIST) {
             continue;
         }
         $governor_level = $planetrow['PLANET_GOVERNOR_ID'] == $governor_id ? $planetrow['PLANET_GOVERNOR_LEVEL'] : 0;
         $build_data = eco_get_build_data($user, $planetrow, $governor_id, $governor_level);
         $template->assign_block_vars('governors', array('ID' => $governor_id, 'NAME' => $lang['tech'][$governor_id], 'COST' => $build_data[BUILD_CREATE][RES_DARK_MATTER], 'MAX' => get_unit_param($governor_id, P_MAX_STACK), 'LEVEL' => $governor_level));
     }
     $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
     $planet_density_index = $planetrow['density_index'];
     $density_price_chart = planet_density_price_chart($planet_density_index);
     tpl_planet_density_info($template, $density_price_chart, $user_dark_matter);
     $sector_cost = eco_get_build_data($user, $planetrow, UNIT_SECTOR, mrc_get_level($user, $planetrow, UNIT_SECTOR), true);
     $sector_cost = $sector_cost[BUILD_CREATE][RES_DARK_MATTER];
     $planet_fill = floor($planetrow['field_current'] / eco_planet_fields_max($planetrow) * 100);
     $planet_fill = $planet_fill > 100 ? 100 : $planet_fill;
     $can_teleport = uni_planet_teleport_check($user, $planetrow);
     $template->assign_vars(array('DARK_MATTER' => $user['dark_matter'], 'PLANET_FILL' => floor($planetrow['field_current'] / eco_planet_fields_max($planetrow) * 100), 'PLANET_FILL_BAR' => $planet_fill, 'SECTOR_CAN_BUY' => $sector_cost <= $user_dark_matter, 'SECTOR_COST' => $sector_cost, 'SECTOR_COST_TEXT' => pretty_number($sector_cost), 'planet_field_current' => $planetrow['field_current'], 'planet_field_max' => eco_planet_fields_max($planetrow), 'CAN_TELEPORT' => $can_teleport['result'] == ERR_NONE, 'CAN_NOT_TELEPORT_MSG' => $can_teleport['message'], 'TELEPORT_COST_TEXT' => pretty_number($config->planet_teleport_cost, true, $user['dark_matter']), 'CAN_CAPITAL' => $user['dark_matter'] >= $config->planet_capital_cost, 'CAPITAL_COST_TEXT' => pretty_number($config->planet_capital_cost, true, $user['dark_matter']), 'PLANET_DENSITY_INDEX' => $planet_density_index, 'PLANET_CORE_TEXT' => $lang['uni_planet_density_types'][$planet_density_index], 'IS_CAPITAL' => $planetrow['id'] == $user['id_planet'], 'PAGE_HINT' => $lang['ov_manage_page_hint']));
     $template->assign_block_vars('result', $result);
     display($template, $lang['rename_and_abandon_planet']);
     break;
 default:
Ejemplo n.º 23
0
 upd_check_key('avatar_max_width', 128, !isset($config->avatar_max_width));
 upd_check_key('avatar_max_height', 128, !isset($config->avatar_max_height));
 upd_alter_table('users', array("MODIFY COLUMN `avatar` tinyint(1) unsigned NOT NULL DEFAULT '0'"), strtoupper($update_tables['users']['avatar']['Type']) != 'TINYINT(1) UNSIGNED');
 upd_alter_table('alliance', array("MODIFY COLUMN `ally_image` tinyint(1) unsigned NOT NULL DEFAULT '0'"), strtoupper($update_tables['alliance']['ally_image']['Type']) != 'TINYINT(1) UNSIGNED');
 upd_alter_table('users', array("DROP COLUMN `settings_allylogo`"), isset($update_tables['users']['settings_allylogo']));
 if (!isset($update_tables['powerup'])) {
     upd_do_query("DROP TABLE IF EXISTS {$config->db_prefix}mercenaries;");
     upd_create_table('powerup', "(\n          `powerup_id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,\n          `powerup_user_id` bigint(20) UNSIGNED NULL DEFAULT NULL,\n          `powerup_planet_id` bigint(20) UNSIGNED NULL DEFAULT NULL,\n          `powerup_category` SMALLINT NOT NULL DEFAULT 0,\n          `powerup_unit_id` MEDIUMINT UNSIGNED NOT NULL DEFAULT '0',\n          `powerup_unit_level` SMALLINT UNSIGNED NOT NULL DEFAULT '0',\n          `powerup_time_start` int(11) NOT NULL DEFAULT '0',\n          `powerup_time_finish` int(11) NOT NULL DEFAULT '0',\n\n          PRIMARY KEY (`powerup_id`),\n          KEY `I_powerup_user_id` (`powerup_user_id`),\n          KEY `I_powerup_planet_id` (`powerup_planet_id`),\n          KEY `I_user_powerup_time` (`powerup_user_id`, `powerup_unit_id`, `powerup_time_start`, `powerup_time_finish`),\n          KEY `I_planet_powerup_time` (`powerup_planet_id`, `powerup_unit_id`, `powerup_time_start`, `powerup_time_finish`),\n\n          CONSTRAINT `FK_powerup_user_id` FOREIGN KEY (`powerup_user_id`) REFERENCES `{$config->db_prefix}users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,\n          CONSTRAINT `FK_powerup_planet_id` FOREIGN KEY (`powerup_planet_id`) REFERENCES `{$config->db_prefix}planets` (`id`) ON DELETE CASCADE ON UPDATE CASCADE\n        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
     upd_check_key('empire_mercenary_temporary', 0, !isset($config->empire_mercenary_temporary));
     upd_check_key('empire_mercenary_base_period', PERIOD_MONTH, !isset($config->empire_mercenary_base_period));
     $update_query_template = "UPDATE {{users}} SET id = id %s WHERE id = %d LIMIT 1;";
     $user_list = upd_do_query("SELECT * FROM {{users}};");
     while ($user_row = db_fetch($user_list)) {
         $update_query_str = '';
         foreach (sn_get_groups('mercenaries') as $mercenary_id) {
             $mercenary_data_name = get_unit_param($mercenary_id, P_NAME);
             if ($mercenary_level = $user_row[$mercenary_data_name]) {
                 $update_query_str = ", `{$mercenary_data_name}` = 0";
                 upd_do_query("DELETE FROM {{powerup}} WHERE powerup_user_id = {$user_row['id']} AND powerup_unit_id = {$mercenary_id} LIMIT 1;");
                 upd_do_query("INSERT {{powerup}} SET powerup_user_id = {$user_row['id']}, powerup_unit_id = {$mercenary_id}, powerup_unit_level = {$mercenary_level};");
             }
         }
         if ($update_query_str) {
             upd_do_query(sprintf($update_query_template, $update_query_str, $user_row['id']));
         }
     }
 }
 if (!isset($update_tables['universe'])) {
     upd_create_table('universe', "(\n          `universe_galaxy` SMALLINT UNSIGNED NOT NULL DEFAULT '0',\n          `universe_system` SMALLINT UNSIGNED NOT NULL DEFAULT '0',\n          `universe_name` varchar(32) NOT NULL DEFAULT '',\n          `universe_price` bigint(20) NOT NULL DEFAULT 0,\n\n          PRIMARY KEY (`universe_galaxy`, `universe_system`)\n        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
     upd_check_key('uni_price_galaxy', 10000, !isset($config->uni_price_galaxy));
     upd_check_key('uni_price_system', 1000, !isset($config->uni_price_system));
Ejemplo n.º 24
0
function pname_resource_name($resource_id)
{
    return get_unit_param($resource_id, P_NAME);
}
Ejemplo n.º 25
0
function sys_stat_calculate()
{
    global $config, $sta_update_step;
    ini_set('memory_limit', $config->stats_php_memory ? $config->stats_php_memory : '1024M');
    $user_skip_list = sys_stat_get_user_skip_list();
    // $sn_groups_resources_loot = sn_get_groups('resources_loot');
    $rate[RES_METAL] = $config->rpg_exchange_metal;
    $rate[RES_CRYSTAL] = $config->rpg_exchange_crystal / $config->rpg_exchange_metal;
    $rate[RES_DEUTERIUM] = $config->rpg_exchange_deuterium / $config->rpg_exchange_metal;
    $rate[RES_DARK_MATTER] = $config->rpg_exchange_darkMatter / $config->rpg_exchange_metal;
    $sta_update_step = -1;
    sta_set_time_limit('starting update');
    $counts = $points = $unit_cost_cache = $user_allies = array();
    sn_db_transaction_start();
    sta_set_time_limit('calculating players stats');
    $i = 0;
    // Блокируем всех пользователей
    classSupernova::db_lock_tables('users');
    $user_list = db_user_list('', true, 'id, dark_matter, metal, crystal, deuterium, user_as_ally, ally_id');
    $row_num = count($user_list);
    // while($player = db_fetch($query))
    foreach ($user_list as $player) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating players stats (player {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $player['id'], $user_skip_list)) {
            continue;
        }
        $resources = $player['metal'] * $rate[RES_METAL] + $player['crystal'] * $rate[RES_CRYSTAL] + $player['deuterium'] * $rate[RES_DEUTERIUM] + $player['dark_matter'] * $rate[RES_DARK_MATTER];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
        // А здесь мы фильтруем пользователей по $user_skip_list - далее не нужно этого делать, потому что
        if (!isset($user_skip_list[$user_id])) {
            $user_allies[$user_id] = $player['ally_id'];
        }
    }
    unset($user_list);
    classSupernova::cache_clear(LOC_USER, true);
    //pdump(classSupernova::$data[LOC_USER]);
    //pdump(classSupernova::$locks[LOC_USER]);
    sta_set_time_limit('calculating planets stats');
    $i = 0;
    $query = db_planet_list_resources_by_owner();
    $row_num = db_num_rows($query);
    while ($planet = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating planets stats (planet {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $planet['id_owner'], $user_skip_list)) {
            continue;
        }
        $resources = $planet['metal'] * $rate[RES_METAL] + $planet['crystal'] * $rate[RES_CRYSTAL] + $planet['deuterium'] * $rate[RES_DEUTERIUM];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    // Calculation of Fleet-In-Flight
    sta_set_time_limit('calculating flying fleets stats');
    $i = 0;
    $query = doquery("SELECT fleet_owner, fleet_array, fleet_resource_metal, fleet_resource_crystal, fleet_resource_deuterium FROM {{fleets}};");
    $row_num = db_num_rows($query);
    while ($fleet_row = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating flying fleets stats (fleet {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $fleet_row['fleet_owner'], $user_skip_list)) {
            continue;
        }
        $fleet = sys_unit_str2arr($fleet_row['fleet_array']);
        foreach ($fleet as $unit_id => $unit_amount) {
            $counts[$user_id][UNIT_SHIPS] += $unit_amount;
            if (!isset($unit_cost_cache[$unit_id][0])) {
                $unit_cost_cache[$unit_id][0] = get_unit_param($unit_id, P_COST);
            }
            $unit_cost_data =& $unit_cost_cache[$unit_id][0];
            $points[$user_id][UNIT_SHIPS] += ($unit_cost_data[RES_METAL] * $rate[RES_METAL] + $unit_cost_data[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $unit_cost_data[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $unit_amount;
        }
        $resources = $fleet_row['fleet_resource_metal'] * $rate[RES_METAL] + $fleet_row['fleet_resource_crystal'] * $rate[RES_CRYSTAL] + $fleet_row['fleet_resource_deuterium'] * $rate[RES_DEUTERIUM];
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    sta_set_time_limit('calculating unit stats');
    $i = 0;
    $query = db_unit_list_stat_calculate();
    $row_num = db_num_rows($query);
    while ($unit = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating unit stats (unit {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $unit['unit_player_id'], $user_skip_list)) {
            continue;
        }
        $counts[$user_id][$unit['unit_type']] += $unit['unit_level'] * $unit['unit_amount'];
        $total_cost = eco_get_total_cost($unit['unit_snid'], $unit['unit_level']);
        $points[$user_id][$unit['unit_type']] += (isset($total_cost['total']) ? $total_cost['total'] : 0) * $unit['unit_amount'];
    }
    sta_set_time_limit('calculating ques stats');
    $i = 0;
    $query = db_que_list_stat();
    $row_num = db_num_rows($query);
    while ($que_item = db_fetch($query)) {
        if ($i++ % 100 == 0) {
            sta_set_time_limit("calculating ques stats (que item {$i}/{$row_num})", false);
        }
        if (array_key_exists($user_id = $que_item['que_player_id'], $user_skip_list)) {
            continue;
        }
        $que_unit_amount = $que_item['que_unit_amount'];
        $que_item = sys_unit_str2arr($que_item['que_unit_price']);
        $resources = ($que_item[RES_METAL] * $rate[RES_METAL] + $que_item[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $que_item[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $que_unit_amount;
        $counts[$user_id][UNIT_RESOURCES] += $resources;
        // $points[$user_id][UNIT_RESOURCES] += $resources;
    }
    sta_set_time_limit('archiving old statistic');
    // Statistic rotation
    // doquery("DELETE FROM {{statpoints}} WHERE `stat_code` >= 14;");
    doquery("DELETE FROM {{statpoints}} WHERE `stat_date` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL {$config->stats_history_days} DAY));");
    doquery("UPDATE {{statpoints}} SET `stat_code` = `stat_code` + 1;");
    sta_set_time_limit('posting new user stats to DB');
    $data = array();
    foreach ($user_allies as $user_id => $ally_id) {
        // $counts[UNIT_RESOURCES] дублирует $points[UNIT_RESOURCES], поэтому $points не заполняем, а берем $counts и делим на 1000
        $points[$user_id][UNIT_RESOURCES] = $counts[$user_id][UNIT_RESOURCES] / 1000;
        $points[$user_id] = array_map('floor', $points[$user_id]);
        $counts[$user_id] = array_map('floor', $counts[$user_id]);
        $ally_id = $ally_id ? $ally_id : 'NULL';
        $user_defence_points = $points[$user_id][UNIT_DEFENCE] + $points[$user_id][UNIT_DEF_MISSILES];
        $user_defence_counts = $counts[$user_id][UNIT_DEFENCE] + $counts[$user_id][UNIT_DEF_MISSILES];
        $user_points = array_sum($points[$user_id]);
        $user_counts = array_sum($counts[$user_id]);
        $data[] = $q = "({$user_id},{$ally_id},1,1,'{$points[$user_id][UNIT_TECHNOLOGIES]}','{$counts[$user_id][UNIT_TECHNOLOGIES]}'," . "'{$points[$user_id][UNIT_STRUCTURES]}','{$counts[$user_id][UNIT_STRUCTURES]}','{$user_defence_points}','{$user_defence_counts}'," . "'{$points[$user_id][UNIT_SHIPS]}','{$counts[$user_id][UNIT_SHIPS]}','{$points[$user_id][UNIT_RESOURCES]}','{$counts[$user_id][UNIT_RESOURCES]}'," . "{$user_points},{$user_counts}," . SN_TIME_NOW . ")";
        sys_stat_calculate_flush($data);
    }
    sys_stat_calculate_flush($data, true);
    // Updating Allie's stats
    sta_set_time_limit('posting new Alliance stats to DB');
    doquery("INSERT INTO {{statpoints}}\n      (`tech_points`, `tech_count`, `build_points`, `build_count`, `defs_points`, `defs_count`,\n        `fleet_points`, `fleet_count`, `res_points`, `res_count`, `total_points`, `total_count`,\n        `stat_date`, `id_owner`, `id_ally`, `stat_type`, `stat_code`,\n        `tech_old_rank`, `build_old_rank`, `defs_old_rank`, `fleet_old_rank`, `res_old_rank`, `total_old_rank`\n      )\n      SELECT\n        SUM(u.`tech_points`)+aus.`tech_points`, SUM(u.`tech_count`)+aus.`tech_count`, SUM(u.`build_points`)+aus.`build_points`, SUM(u.`build_count`)+aus.`build_count`,\n        SUM(u.`defs_points`)+aus.`defs_points`, SUM(u.`defs_count`)+aus.`defs_count`, SUM(u.`fleet_points`)+aus.`fleet_points`, SUM(u.`fleet_count`)+aus.`fleet_count`,\n        SUM(u.`res_points`)+aus.`res_points`, SUM(u.`res_count`)+aus.`res_count`, SUM(u.`total_points`)+aus.`total_points`, SUM(u.`total_count`)+aus.`total_count`,\n        " . SN_TIME_NOW . ", NULL, u.`id_ally`, 2, 1,\n        a.tech_rank, a.build_rank, a.defs_rank, a.fleet_rank, a.res_rank, a.total_rank\n      FROM {{statpoints}} as u\n        join {{alliance}} as al on al.id = u.id_ally\n        left join {{statpoints}} as aus on aus.id_owner = al.ally_user_id and aus.stat_type = 1 AND aus.stat_code = 1\n        LEFT JOIN {{statpoints}} as a ON a.id_ally = u.id_ally AND a.stat_code = 2 AND a.stat_type = 2\n      WHERE u.`stat_type` = 1 AND u.stat_code = 1 AND u.id_ally<>0\n      GROUP BY u.`id_ally`");
    // Удаляем больше не нужные записи о достижении игрока-альянса
    db_stat_list_delete_ally_player();
    // Some variables we need to update ranks
    $qryResetRowNum = 'SET @rownum=0;';
    $qryFormat = 'UPDATE {{statpoints}} SET `%1$s_rank` = (SELECT @rownum:=@rownum+1) WHERE `stat_type` = %2$d AND `stat_code` = 1 ORDER BY `%1$s_points` DESC, `id_owner` ASC, `id_ally` ASC;';
    $rankNames = array('tech', 'build', 'defs', 'fleet', 'res', 'total');
    // Updating player's ranks
    sta_set_time_limit("updating ranks for players");
    foreach ($rankNames as $rankName) {
        sta_set_time_limit("updating player rank '{$rankName}'", false);
        doquery($qryResetRowNum);
        doquery(sprintf($qryFormat, $rankName, 1));
    }
    sta_set_time_limit("updating ranks for Alliances");
    // --- Updating Allie's ranks
    foreach ($rankNames as $rankName) {
        sta_set_time_limit("updating Alliances rank '{$rankName}'", false);
        doquery($qryResetRowNum);
        doquery(sprintf($qryFormat, $rankName, 2));
    }
    sta_set_time_limit('setting previous user stats from archive');
    doquery("UPDATE {{statpoints}} as new\n      LEFT JOIN {{statpoints}} as old ON old.id_owner = new.id_owner AND old.stat_code = 2 AND old.stat_type = new.stat_type\n    SET\n      new.tech_old_rank = old.tech_rank,\n      new.build_old_rank = old.build_rank,\n      new.defs_old_rank  = old.defs_rank ,\n      new.fleet_old_rank = old.fleet_rank,\n      new.res_old_rank = old.res_rank,\n      new.total_old_rank = old.total_rank\n    WHERE\n      new.stat_type = 1 AND new.stat_code = 1;");
    sta_set_time_limit('setting previous allies stats from archive');
    doquery("UPDATE {{statpoints}} as new\n      LEFT JOIN {{statpoints}} as old ON old.id_ally = new.id_ally AND old.stat_code = 2 AND old.stat_type = new.stat_type\n    SET\n      new.tech_old_rank = old.tech_rank,\n      new.build_old_rank = old.build_rank,\n      new.defs_old_rank  = old.defs_rank ,\n      new.fleet_old_rank = old.fleet_rank,\n      new.res_old_rank = old.res_rank,\n      new.total_old_rank = old.total_rank\n    WHERE\n      new.stat_type = 2 AND new.stat_code = 1;");
    sta_set_time_limit('updating players current rank and points');
    db_stat_list_update_user_stats();
    sta_set_time_limit('updating Allys current rank and points');
    db_stat_list_update_ally_stats();
    // Counting real user count and updating values
    $config->db_saveItem('users_amount', db_user_count());
    sn_db_transaction_commit();
}
Ejemplo n.º 26
0
function eco_render_rapid_fire($unit_id)
{
    global $lang;
    $unit_data = get_unit_param($unit_id);
    $unit_durability = $unit_data['shield'] + $unit_data['armor'];
    $str_rapid_from = '';
    $str_rapid_to = '';
    foreach (sn_get_groups(array('fleet', 'defense_active')) as $enemy_id) {
        $enemy_data = get_unit_param($enemy_id);
        $enemy_durability = $enemy_data['shield'] + $enemy_data['armor'];
        $rapid = floor($unit_data['attack'] * (isset($unit_data['amplify'][$enemy_id]) ? $unit_data['amplify'][$enemy_id] : 1) / $enemy_durability);
        if ($rapid >= 1) {
            $str_rapid_to .= "{$lang['nfo_rf_again']} {$lang['tech'][$enemy_id]} <font color=\"#00ff00\">{$rapid}</font><br>";
        }
        $rapid = floor($enemy_data['attack'] * (isset($enemy_data['amplify'][$unit_id]) ? $enemy_data['amplify'][$unit_id] : 1) / $unit_durability);
        if ($rapid >= 1) {
            $str_rapid_from .= "{$lang['tech'][$enemy_id]} {$lang['nfo_rf_from']} <font color=\"#ff0000\">{$rapid}</font><br>";
        }
    }
    if ($str_rapid_to && $str_rapid_from) {
        $str_rapid_to .= '<hr>';
    }
    return array('to' => $str_rapid_to, 'from' => $str_rapid_from);
}
Ejemplo n.º 27
0
 $que_data_max = 0;
 $units_info = array();
 $que_data = array();
 $unit_data = array();
 $planets = array();
 foreach ($planet_unit_list as $unit_id) {
     if (!($unit_name = get_unit_param($unit_id, P_NAME))) {
         $unit_name = $sn_data_aux[$unit_id][P_NAME];
     }
     if (isset($update_tables['planets'][$unit_name])) {
         $drop[] = "DROP COLUMN `{$unit_name}`";
         if (isset($aux_group[$unit_id])) {
             $units_info[$unit_id] = $sn_data_aux[$unit_id];
             $units_info[$unit_id]['que'] = QUE_HANGAR;
         } else {
             $units_info[$unit_id] = get_unit_param($unit_id);
             foreach ($ques_info as $que_id => $que_data1) {
                 if (in_array($unit_id, $que_data1['unit_list'])) {
                     $units_info[$unit_id]['que'] = $que_id;
                     break;
                 }
             }
         }
     }
 }
 $query = upd_do_query("SELECT * FROM {{planets}} FOR UPDATE");
 while ($row = db_fetch($query)) {
     $user_id = $row['id_owner'];
     $planet_id = $row['id'];
     $planets[] = $planet_id;
     // Конвертируем юниты
Ejemplo n.º 28
0
function que_build($user, $planet, $build_mode = BUILD_CREATE, $redirect = true)
{
    global $lang;
    $unit_amount_qued = 0;
    try {
        if (!$user['id']) {
            throw new exception('{Нет идентификатора пользователя - сообщите Администрации}', ERR_ERROR);
            // TODO EXCEPTION
        }
        $unit_id = sys_get_param_int('unit_id');
        /*
        if(!$unit_id && is_array($unit_list = sys_get_param('fmenge')))
        {
          foreach($unit_list as $unit_id => $unit_amount) if($unit_amount) break;
        }
        */
        if (!$unit_id) {
            throw new exception('{Нет идентификатора юнита - сообщите Администрации}', ERR_ERROR);
            // TODO EXCEPTION
        }
        $que_id = que_get_unit_que($unit_id);
        if (!$que_id) {
            throw new exception('{Неправильный тип очереди - сообщите Администрации}', ERR_ERROR);
            // TODO EXCEPTION
        }
        if ($build_mode == BUILD_DESTROY && $que_id != QUE_STRUCTURES) {
            throw new exception('{Уничтожать можно только здания на планете}', ERR_ERROR);
            // TODO EXCEPTION
        }
        $que_data = sn_get_groups('ques');
        $que_data = $que_data[$que_id];
        //    die();
        // TODO Переделать под подочереди
        if ($que_id == QUE_STRUCTURES) {
            $sn_groups_build_allow = sn_get_groups('build_allow');
            $que_data['unit_list'] = $sn_groups_build_allow[$planet['planet_type']];
            if (!isset($que_data['unit_list'][$unit_id])) {
                throw new exception('{Это здание нельзя строить на ' . ($planet['planet_type'] == PT_PLANET ? 'планете' : 'луне'), ERR_ERROR);
                // TODO EXCEPTION
            }
        }
        /*
        // TODO Разделить очереди для Верфи и Обороны
        elseif($que_id == QUE_HANGAR)
        {
          $que_data['mercenary'] = in_array($unit_id, sn_get_groups('defense')) ? MRC_FORTIFIER : MRC_ENGINEER;
        }
        elseif($que_id == QUE_HANGAR)
        {
          $que_data['mercenary'] = in_array($unit_id, sn_get_groups('defense')) ? MRC_FORTIFIER : MRC_ENGINEER;
        }
        */
        sn_db_transaction_start();
        // Это нужно, что бы заблокировать пользователя и работу с очередями
        $user = db_user_by_id($user['id']);
        // Это нужно, что бы заблокировать планету от списания ресурсов
        if (isset($planet['id']) && $planet['id']) {
            $planet = db_planet_by_id($planet['id'], true);
        } else {
            $planet['id'] = 0;
        }
        $planet_id = $que_id == QUE_RESEARCH ? 0 : intval($planet['id']);
        $que = que_get($user['id'], $planet['id'], $que_id, true);
        $in_que =& $que['in_que'][$que_id][$user['id']][$planet_id];
        $que_max_length = que_get_max_que_length($user, $planet, $que_id, $que_data);
        // TODO Добавить вызовы функций проверок текущей и максимальной длин очередей
        if (count($in_que) >= $que_max_length) {
            throw new exception('{Все слоты очереди заняты}', ERR_ERROR);
            // TODO EXCEPTION
        }
        // TODO Отдельно посмотреть на уничтожение зданий - что бы можно было уничтожать их без планов
        switch (eco_can_build_unit($user, $planet, $unit_id)) {
            case BUILD_ALLOWED:
                break;
            case BUILD_UNIT_BUSY:
                throw new exception('{Строение занято}', ERR_ERROR);
                break;
                // TODO EXCEPTION eco_bld_msg_err_laboratory_upgrading
                // case BUILD_REQUIRE_NOT_MEET:
            // TODO EXCEPTION eco_bld_msg_err_laboratory_upgrading
            // case BUILD_REQUIRE_NOT_MEET:
            default:
                if ($build_mode == BUILD_CREATE) {
                    throw new exception('{Требования не удовлетворены}', ERR_ERROR);
                }
                break;
                // TODO EXCEPTION eco_bld_msg_err_requirements_not_meet
        }
        $unit_amount = floor(sys_get_param_float('unit_amount', 1));
        $unit_amount_qued = $unit_amount;
        $units_qued = isset($in_que[$unit_id]) ? $in_que[$unit_id] : 0;
        $unit_level = mrc_get_level($user, $planet, $unit_id, true, true) + $units_qued;
        if ($unit_max = get_unit_param($unit_id, P_MAX_STACK)) {
            if ($unit_level >= $unit_max) {
                throw new exception('{Максимальное количество юнитов данного типа уже достигнуто или будет достигнуто по окончанию очереди}', ERR_ERROR);
                // TODO EXCEPTION
            }
            $unit_amount = max(0, min($unit_amount, $unit_max - $unit_level));
        }
        if ($unit_amount < 1) {
            throw new exception('{Неправильное количество юнитов - сообщите Администрации}', ERR_ERROR);
            // TODO EXCEPTION
        }
        /*
        if($unit_max && $unit_level + $unit_amount > $unit_max)
        {
          throw new exception("Постройка {$unit_amount} {$lang['tech'][$unit_id]} приведет к привышению максимально возможного количества юнитов данного типа", ERR_ERROR); // TODO EXCEPTION
        }
        */
        // TODO Переделать eco_unit_busy для всех типов зданий
        //  if(eco_unit_busy($user, $planet, $que, $unit_id))
        //  {
        //    die('Unit busy'); // TODO EXCEPTION
        //  }
        if (get_unit_param($unit_id, P_STACKABLE)) {
            // TODO Поле 'max_Lot_size' для ограничения размера стэка в очереди - то ли в юниты, то ли в очередь
            if (in_array($unit_id, $group_missile = sn_get_groups('missile'))) {
                // TODO Поле 'container' - указывает на родительску структуру, в которой хранится данный юнит и по вместительности которой нужно применять размер юнита
                $used_silo = 0;
                foreach ($group_missile as $missile_id) {
                    $missile_qued = isset($in_que[$missile_id]) ? $in_que[$missile_id] : 0;
                    $used_silo += (mrc_get_level($user, $planet, $missile_id, true, true) + $missile_qued) * get_unit_param($missile_id, P_UNIT_SIZE);
                }
                $free_silo = mrc_get_level($user, $planet, STRUC_SILO) * get_unit_param(STRUC_SILO, P_CAPACITY) - $used_silo;
                if ($free_silo <= 0) {
                    throw new exception('{Ракетная шахта уже заполнена или будет заполнена по окончанию очереди}', ERR_ERROR);
                    // TODO EXCEPTION
                }
                $unit_size = get_unit_param($unit_id, P_UNIT_SIZE);
                if ($free_silo < $unit_size) {
                    throw new exception("{В ракетной шахте нет места для {$lang['tech'][$unit_id]}}", ERR_ERROR);
                    // TODO EXCEPTION
                }
                $unit_amount = max(0, min($unit_amount, floor($free_silo / $unit_size)));
            }
            $unit_level = $new_unit_level = 0;
        } else {
            $unit_amount = 1;
            if ($que_id == QUE_STRUCTURES) {
                // if($build_mode == BUILD_CREATE && eco_planet_fields_max($planet) - $planet['field_current'] - $que['sectors'][$planet['id']] <= 0)
                $sectors_qued = is_array($in_que) ? array_sum($in_que) : 0;
                if ($build_mode == BUILD_CREATE && eco_planet_fields_max($planet) - $planet['field_current'] - $sectors_qued <= 0) {
                    throw new exception('{Не хватает секторов на планете}', ERR_ERROR);
                    // TODO EXCEPTION
                }
                // И что это я такое написал? Зачем?
                //if($build_mode == BUILD_DESTROY && $planet['field_current'] <= $que['amounts'][$que_id])
                //{
                //  die('Too much buildings'); // TODO EXCEPTION
                //}
            }
            $build_multiplier = $build_mode == BUILD_CREATE ? 1 : -1;
            $new_unit_level = $unit_level + $unit_amount * $build_multiplier;
        }
        $build_data = eco_get_build_data($user, $planet, $unit_id, $unit_level);
        $unit_amount = min($build_data['CAN'][$build_mode], $unit_amount);
        if ($unit_amount < 0) {
            throw new exception('{Не хватает ресурсов}', ERR_ERROR);
            // TODO EXCEPTION
        }
        if ($new_unit_level < 0) {
            throw new exception('{Нельзя уничтожить больше юнитов, чем есть}', ERR_ERROR);
            // TODO EXCEPTION
        }
        if ($build_data['RESULT'][$build_mode] != BUILD_ALLOWED) {
            throw new exception('{Строительство блокировано}', ERR_ERROR);
            // TODO EXCEPTION
        }
        //    $unit_amount = min($unit_amount, MAX_FLEET_OR_DEFS_PER_ROW);
        $unit_amount_qued = 0;
        while ($unit_amount > 0 && count($que['ques'][$que_id][$user['id']][$planet_id]) < $que_max_length) {
            $place = min($unit_amount, MAX_FLEET_OR_DEFS_PER_ROW);
            que_add_unit($unit_id, $user, $planet, $build_data, $new_unit_level, $place, $build_mode);
            $unit_amount -= $place;
            $que = que_get($user['id'], $planet['id'], $que_id, true);
            $unit_amount_qued += $place;
        }
        //    pdump($que);
        /*
            pdump($que = que_get($user['id'], $planet['id'], $que_id, true));
        */
        // die();
        //    if(count($que['ques'][$que_id][$user['id']][$planet_id]) >= $que_max_length)
        sn_db_transaction_commit();
        if ($redirect) {
            sys_redirect("{$_SERVER['PHP_SELF']}?mode=" . sys_get_param_str('mode') . "&ally_id=" . sys_get_param_id('ally_id'));
            die;
        }
        $operation_result = array('STATUS' => ERR_NONE, 'MESSAGE' => '{Строительство начато}');
    } catch (exception $e) {
        sn_db_transaction_rollback();
        $operation_result = array('STATUS' => in_array($e->getCode(), array(ERR_NONE, ERR_WARNING, ERR_ERROR)) ? $e->getCode() : ERR_ERROR, 'MESSAGE' => $e->getMessage());
    }
    if (!empty($operation_result['MESSAGE'])) {
        $operation_result['MESSAGE'] .= ' ' . ($unit_amount_qued ? $unit_amount_qued : $unit_amount) . 'x[' . $lang['tech'][$unit_id] . ']' . (isset($planet['id']) ? ' на ' . $planet['name'] : '') . '}';
    }
    return $operation_result;
}
Ejemplo n.º 29
0
function upd_db_unit_changeset_prepare($unit_id, $unit_value, $user, $planet_id = null)
{
    if (!is_array($user)) {
        // TODO - remove later
        print '<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>';
        pdump(debug_backtrace());
        die('USER is not ARRAY');
    }
    if (!isset($user['id']) || !$user['id']) {
        // TODO - remove later
        print '<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>';
        pdump($user);
        pdump(debug_backtrace());
        die('USER[id] пустой');
    }
    $planet_id = is_array($planet_id) && isset($planet_id['id']) ? $planet_id['id'] : $planet_id;
    $unit_location = get_unit_param($unit_id, 'location');
    // sys_get_unit_location($user, array(), $unit_id);
    $location_id = $unit_location == LOC_USER ? $user['id'] : $planet_id;
    $location_id = $location_id ? $location_id : 'NULL';
    $db_changeset = array();
    $temp = upd_db_unit_by_location($user['id'], $unit_location, $location_id, $unit_id, true, 'unit_id');
    if ($temp['unit_id']) {
        // update
        $db_changeset = array('action' => SQL_OP_UPDATE, 'where' => array("`unit_id` = {$temp['unit_id']}"), 'fields' => array('unit_level' => array('delta' => $unit_value)));
    } else {
        // insert
        $db_changeset = array('action' => SQL_OP_INSERT, 'fields' => array('unit_player_id' => array('set' => $user['id']), 'unit_location_type' => array('set' => $unit_location), 'unit_location_id' => array('set' => $unit_location == LOC_USER ? $user['id'] : $planet_id), 'unit_type' => array('set' => get_unit_param($unit_id, P_UNIT_TYPE)), 'unit_snid' => array('set' => $unit_id), 'unit_level' => array('set' => $unit_value)));
    }
    return $db_changeset;
}
Ejemplo n.º 30
0
function COE_missileAttack($defenceTech, $attackerTech, $MIPs, $structures, $targetedStructure = '0')
{
    // Here we select which part of defense should take damage: structure or shield
    // $damageTo = P_SHIELD;
    // $damageTo = P_STRUCTURE;
    $damageTo = P_DEFENSE;
    $mip_data = get_unit_param(UNIT_DEF_MISSILE_INTERPLANET);
    $MIPDamage = floor(mrc_modify_value($attackerTech, false, TECH_WEAPON, $MIPs * $mip_data[P_ATTACK] * mt_rand(80, 120) / 100));
    foreach ($structures as $key => $structure) {
        $unit_info = get_unit_param($key);
        $amplify = isset($mip_data[P_AMPLIFY][$key]) ? $mip_data[P_AMPLIFY][$key] : 1;
        $structures[$key][P_SHIELD] = floor(mrc_modify_value($defenceTech, false, TECH_SHIELD, $unit_info[P_SHIELD]) / $amplify);
        $structures[$key][P_STRUCTURE] = floor(mrc_modify_value($defenceTech, false, TECH_ARMOR, $unit_info[P_ARMOR]) / $amplify);
        $structures[$key][P_DEFENSE] = floor((mrc_modify_value($defenceTech, false, TECH_ARMOR, $unit_info[P_ARMOR]) + mrc_modify_value($defenceTech, false, TECH_SHIELD, $unit_info[P_SHIELD])) / $amplify * mt_rand(80, 120) / 100);
    }
    $startStructs = $structures;
    if ($targetedStructure) {
        //attacking only selected structure
        $damageDone = $structures[$targetedStructure][$damageTo];
        $structsDestroyed = min(floor($MIPDamage / $damageDone), $structures[$targetedStructure][0]);
        $structures[$targetedStructure][0] -= $structsDestroyed;
        $MIPDamage -= $structsDestroyed * $damageDone;
    } else {
        // REALLY random attack
        $can_be_damaged = sn_get_groups('defense_active');
        //debug($structures);
        //debug($can_be_damaged);
        do {
            // finding is there any structure that can be damaged with leftovers of $MIPDamage
            foreach ($can_be_damaged as $key => $unit_id) {
                //debug($structures[$unit_id][0]);
                //debug($structures[$unit_id][$damageTo], $MIPDamage);
                if ($structures[$unit_id][0] <= 0 || $structures[$unit_id][$damageTo] > $MIPDamage) {
                    unset($can_be_damaged[$key]);
                }
            }
            if (empty($can_be_damaged)) {
                break;
            }
            sort($can_be_damaged);
            //debug($can_be_damaged, 'can be damaged');
            $random_defense = mt_rand(0, count($can_be_damaged) - 1);
            //debug($can_be_damaged[$random_defense], 'Target');
            $current_target =& $structures[$can_be_damaged[$random_defense]];
            //debug($current_target[0], 'Amount was');
            $can_be_destroyed = min($current_target[0], floor($MIPDamage / $current_target[$damageTo]));
            //debug($MIPDamage, 'MIPDamage');
            //debug($can_be_destroyed, 'Can be destroyed');
            $destroyed = mt_rand(1, $can_be_destroyed);
            $MIPDamage -= $current_target[$damageTo] * $destroyed;
            $current_target[0] -= $destroyed;
            //debug($destroyed, 'Actually destroyed');
            //print('<hr>');
        } while ($MIPDamage > 0 && !empty($can_be_damaged));
        //debug($MIPDamage, 'MIPDamage left');
    }
    //debug($structures);//die();
    // 1/2 of metal and 1/4 of crystal of destroyed structures returns to planet
    $metal = 0;
    $crystal = 0;
    foreach ($structures as $key => $structure) {
        $unit_info = get_unit_param($key);
        $destroyed = $startStructs[$key][0] - $structure[0];
        $metal += $destroyed * $unit_info[P_COST][RES_METAL] / 2;
        $crystal += $destroyed * $unit_info[P_COST][RES_CRYSTAL] / 4;
    }
    $return['structures'] = $structures;
    // Structures left after attack
    $return['metal'] = floor($metal);
    // Metal scraps
    $return['crystal'] = floor($crystal);
    // Crystal scraps
    return $return;
}