Пример #1
0
function flt_mission_colonize(&$mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $src_user_row =& $mission_data['src_user'];
    global $lang;
    $TargetAdress = sprintf($lang['sys_adress_planet'], $fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet']);
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    $TheMessage = $lang['sys_colo_no_colonizer'];
    if ($fleet_array[SHIP_COLONIZER] >= 1) {
        $TheMessage = $lang['sys_colo_notfree'];
        if (!$mission_data['dst_planet'] || empty($mission_data['dst_planet'])) {
            $iPlanetCount = get_player_current_colonies($src_user_row);
            // Can we colonize more planets?
            $TheMessage = $lang['sys_colo_maxcolo'];
            if ($iPlanetCount < get_player_max_colonies($src_user_row)) {
                // Yes, we can colonize
                $TheMessage = $lang['sys_colo_badpos'];
                $NewOwnerPlanet = uni_create_planet($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $fleet_row['fleet_owner'], "{$lang['sys_colo_defaultname']} {$iPlanetCount}", false, array('user_row' => $src_user_row));
                if ($NewOwnerPlanet) {
                    $TheMessage = $lang['sys_colo_arrival'] . $TargetAdress . $lang['sys_colo_allisok'];
                    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], $TheMessage);
                    $fleet_array[SHIP_COLONIZER]--;
                    $fleet_row['fleet_amount']--;
                    $fleet_row['fleet_array'] = sys_unit_arr2str($fleet_array);
                    return RestoreFleetToPlanet($fleet_row, false);
                }
            }
        }
    }
    doquery("UPDATE `{{fleets}}` SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], "{$lang['sys_colo_arrival']}{$TargetAdress}{$TheMessage}");
    return CACHE_FLEET;
}
function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, $safe_fleet = false, &$result)
{
    sn_db_transaction_check(true);
    $result = CACHE_NOTHING;
    if (!is_array($fleet_row)) {
        return $result;
    }
    $prefix = $start ? 'start' : 'end';
    // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!!
    // TODO Проеверить от многократного срабатывания !!!
    // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока
    //  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1", true);
    // Узнаем ИД владельца планеты - без блокировки
    // TODO поменять на владельца планеты - когда его будут возвращать всегда !!!
    $user_id = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", false, 'id_owner');
    $user_id = $user_id['id_owner'];
    // Блокируем пользователя
    $user = db_user_by_id($user_id, true);
    // Блокируем планету
    $planet_arrival = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", true);
    // Блокируем флот
    //  $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1 FOR UPDATE;", true);
    // Если флот уже обработан - не существует или возращается - тогда ничего не делаем
    if (!$fleet_row || !is_array($fleet_row) || $fleet_row['fleet_mess'] == 1 && $only_resources) {
        return $result;
    }
    // Флот, который возвращается на захваченную планету, пропадает
    if ($start && $fleet_row['fleet_mess'] == 1 && $planet_arrival['id_owner'] != $fleet_row['fleet_owner']) {
        doquery("DELETE FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;");
        return $result;
    }
    //pdump($planet_arrival);
    $db_changeset = array();
    if (!$only_resources) {
        flt_destroy($fleet_row);
        if ($fleet_row['fleet_owner'] == $planet_arrival['id_owner']) {
            $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
            foreach ($fleet_array as $ship_id => $ship_count) {
                if ($ship_count) {
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']);
                }
            }
        } else {
            return CACHE_NOTHING;
        }
    } else {
        // flt_send_back($fleet_row);
        doquery("UPDATE {{fleets}} SET fleet_resource_metal = 0, fleet_resource_crystal = 0, fleet_resource_deuterium = 0, fleet_mess = 1 WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    if (!empty($db_changeset)) {
        db_changeset_apply($db_changeset);
    }
    db_planet_set_by_id($planet_arrival['id'], "`metal` = `metal` + '{$fleet_row['fleet_resource_metal']}', `crystal` = `crystal` + '{$fleet_row['fleet_resource_crystal']}', `deuterium` = `deuterium` + '{$fleet_row['fleet_resource_deuterium']}'");
    $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST);
    return $result;
}
Пример #3
0
/**
 * MissionCaseStay.php
 *
 * version 2.0 returns results for new fleet handler
 * @version 1.1
 * @copyright 2008 by Chlorel for XNova
 */
function flt_mission_relocate($mission_data)
{
    $fleet_row =& $mission_data['fleet'];
    $destination_planet =& $mission_data['dst_planet'];
    if (!$destination_planet || !is_array($destination_planet)) {
        // 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;
    $Message = sprintf($lang['sys_tran_mess_user'], $mission_data['src_planet']['name'], uni_render_coordinates_href($fleet_row, 'fleet_start_', 3, ''), $destination_planet['name'], uni_render_coordinates_href($fleet_row, 'fleet_end_', 3, ''), $fleet_row['fleet_resource_metal'], $lang['Metal'], $fleet_row['fleet_resource_crystal'], $lang['Crystal'], $fleet_row['fleet_resource_deuterium'], $lang['Deuterium']) . '<br />' . $lang['sys_relocate_mess_user'];
    foreach (sys_unit_str2arr($fleet_row['fleet_array']) as $ship_id => $ship_count) {
        $Message .= $lang['tech'][$ship_id] . ' - ' . $ship_count . '<br />';
    }
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_TRANSPORT, $lang['sys_mess_qg'], $lang['sys_stay_mess_stay'], $Message);
    return RestoreFleetToPlanet($fleet_row, false);
}
Пример #4
0
function sn_ube_attack_prepare_fleet(&$combat_data, &$fleet, $is_attacker)
{
    $fleet_owner_id = $fleet['fleet_owner'];
    $fleet_id = $fleet['fleet_id'];
    ube_attack_prepare_player($combat_data, $fleet_owner_id, $is_attacker);
    $fleet_data = sys_unit_str2arr($fleet['fleet_array']);
    $combat_data[UBE_FLEETS][$fleet_id][UBE_OWNER] = $fleet_owner_id;
    $fleet_info =& $combat_data[UBE_FLEETS][$fleet_id];
    $fleet_info[UBE_FLEET_GROUP] = $fleet['fleet_group'];
    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) {
            $fleet_info[UBE_COUNT][$unit_id] = $unit_count;
        }
    }
    $fleet_info[UBE_RESOURCES] = array(RES_METAL => $fleet['fleet_resource_metal'], RES_CRYSTAL => $fleet['fleet_resource_crystal'], RES_DEUTERIUM => $fleet['fleet_resource_deuterium']);
    $fleet_info[UBE_PLANET] = array(PLANET_GALAXY => $fleet['fleet_start_galaxy'], PLANET_SYSTEM => $fleet['fleet_start_system'], PLANET_PLANET => $fleet['fleet_start_planet'], PLANET_TYPE => $fleet['fleet_start_type']);
}
Пример #5
0
function flt_mission_colonize($mission_data)
{
    $fleet_row = $mission_data['fleet'];
    $src_user_row = $mission_data['src_user'];
    $destination_planet = $mission_data['dst_planet'];
    global $lang;
    $TargetAdress = sprintf($lang['sys_adress_planet'], $fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet']);
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    $TheMessage = $lang['sys_colo_no_colonizer'];
    if ($fleet_array[SHIP_COLONIZER] >= 1) {
        $TheMessage = $lang['sys_colo_notfree'];
        if (!$destination_planet) {
            $iMaxColo = $src_user_row['colonisation_tech'] + 1;
            $iPlanetCount = doquery("SELECT count(*) as `planet_count` FROM `{{planets}}` WHERE `id_owner` = '{$fleet_row['fleet_owner']}' AND `planet_type` = '1';", '', true);
            $iPlanetCount = $iPlanetCount['planet_count'];
            // Can we colonize more planets?
            $TheMessage = $lang['sys_colo_maxcolo'];
            if ($iPlanetCount < $iMaxColo && $iPlanetCount < $GLOBALS['config']->player_max_colonies + 1) {
                // Yes, we can colonize
                $TheMessage = $lang['sys_colo_badpos'];
                $NewOwnerPlanet = uni_create_planet($fleet_row['fleet_end_galaxy'], $fleet_row['fleet_end_system'], $fleet_row['fleet_end_planet'], $fleet_row['fleet_owner'], "{$lang['sys_colo_defaultname']} ¹{$iPlanetCount}");
                if ($NewOwnerPlanet) {
                    $TheMessage = $lang['sys_colo_arrival'] . $TargetAdress . $lang['sys_colo_allisok'];
                    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], $TheMessage);
                    $fleet_array[SHIP_COLONIZER]--;
                    $fleet_row['fleet_amount']--;
                    $fleet_row['fleet_array'] = sys_unit_arr2str($fleet_array);
                    if ($fleet_row['fleet_array']) {
                        $GLOBALS['debug']->warning("Sending several type of ships with colonizer leads to resource duplication. Resource duplicate X time where X - number of ship type<br>Fleet: {$fleet_row['fleet_array']}", 'Colonization With Fleet', 304);
                    }
                    return RestoreFleetToPlanet($fleet_row, false);
                }
            }
        }
    }
    doquery("UPDATE `{{fleets}}` SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_colo_mess_from'], $lang['sys_colo_mess_report'], "{$lang['sys_colo_arrival']}{$TargetAdress}{$TheMessage}");
    return CACHE_FLEET;
}
Пример #6
0
         foreach ($unit_cost as $resource_id => &$resource_amount) {
             if (!in_array($resource_id, $group_resource_loot)) {
                 unset($unit_cost[$resource_id]);
                 continue;
             }
             $resource_amount = floor($resource_amount * $price_increase / $build_destroy_divisor);
         }
         $unit_cost = sys_unit_arr2str($unit_cost);
         $units_levels[$unit_id] += $que_item[3];
         $que_data[] = "({$user_id},{$planet_id},{$planet_id},1,{$que_item[2]},{$unit_id},1,{$que_item[3]},{$units_levels[$unit_id]},{$que_item[2]},'{$unit_cost}')";
     }
 }
 // Конвертируем очередь верфи
 if ($row['b_hangar_id']) {
     $return_resources = array(RES_METAL => 0, RES_CRYSTAL => 0, RES_DEUTERIUM => 0);
     $hangar_units = sys_unit_str2arr($row['b_hangar_id']);
     foreach ($hangar_units as $unit_id => $unit_count) {
         if ($unit_count <= 0) {
             continue;
         }
         foreach ($units_info[$unit_id][P_COST] as $resource_id => $resource_amount) {
             if (!in_array($resource_id, $group_resource_loot)) {
                 continue;
             }
             $return_resources[$resource_id] += $unit_count * $resource_amount;
         }
     }
     if (array_sum($return_resources) > 0) {
         upd_do_query("UPDATE {{planets}} SET `metal` = `metal` + {$return_resources[RES_METAL]}, `crystal` = `crystal` + {$return_resources[RES_CRYSTAL]}, `deuterium` = `deuterium` + {$return_resources[RES_DEUTERIUM]} WHERE `id` = {$planet_id} LIMIT 1");
     }
 }
Пример #7
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();
}
Пример #8
0
function que_delete($que_type, $user = array(), $planet = array(), $clear = false)
{
    $planets_locked = array();
    // TODO: Some checks
    sn_db_transaction_start();
    $user = db_user_by_id($user['id'], true);
    $planet['id'] = $planet['id'] && $que_type !== QUE_RESEARCH ? $planet['id'] : 0;
    $global_que = que_get($user['id'], $planet['id'], $que_type, true);
    //pdump($global_que);
    //pdump($planet['id']);
    //pdump($global_que[$que_type][$planet['id']]);
    if (!empty($global_que['ques'][$que_type][$user['id']][$planet['id']])) {
        $que = array_reverse($global_que['ques'][$que_type][$user['id']][$planet['id']]);
        foreach ($que as $que_item) {
            db_que_delete_by_id($que_item['que_id']);
            if ($que_item['que_planet_id_origin']) {
                $planet['id'] = $que_item['que_planet_id_origin'];
            }
            if (!isset($planets_locked[$planet['id']])) {
                $planets_locked[$planet['id']] = $planet['id'] ? db_planet_by_id($planet['id'], true) : $planet;
            }
            $build_data = sys_unit_str2arr($que_item['que_unit_price']);
            db_change_units($user, $planets_locked[$planet['id']], array(RES_METAL => $build_data[RES_METAL] * $que_item['que_unit_amount'], RES_CRYSTAL => $build_data[RES_CRYSTAL] * $que_item['que_unit_amount'], RES_DEUTERIUM => $build_data[RES_DEUTERIUM] * $que_item['que_unit_amount']));
            if (!$clear) {
                break;
            }
        }
        if (is_numeric($planet['id'])) {
            db_planet_set_by_id($planet['id'], "`que_processed` = UNIX_TIMESTAMP(NOW())");
        } elseif (is_numeric($user['id'])) {
            db_user_set_by_id($user['id'], '`que_processed` = UNIX_TIMESTAMP(NOW())');
        }
        sn_db_transaction_commit();
    } else {
        sn_db_transaction_rollback();
    }
    //die();
    header("Location: {$_SERVER['PHP_SELF']}?mode={$que_type}" . "&ally_id=" . sys_get_param_id('ally_id'));
}
Пример #9
0
function flt_get_fleets_to_planet($planet, $fleet_db_list = 0)
{
    if (!($planet && $planet['id']) && !$fleet_db_list) {
        return $planet;
    }
    global $user;
    if ($fleet_db_list === 0) {
        $fleet_db_list = flt_get_fleets($planet);
    }
    foreach ($fleet_db_list as $fleet) {
        if ($fleet['fleet_owner'] == $user['id']) {
            if ($fleet['fleet_mission'] == MT_MISSILE) {
                continue;
            }
            $fleet_ownage = 'own';
        } else {
            switch ($fleet['fleet_mission']) {
                case MT_ATTACK:
                case MT_AKS:
                case MT_DESTROY:
                case MT_MISSILE:
                    $fleet_ownage = 'enemy';
                    break;
                default:
                    $fleet_ownage = 'neutral';
                    break;
            }
        }
        $fleet_list[$fleet_ownage]['fleets'][$fleet['fleet_id']] = $fleet;
        if ($fleet['fleet_mess'] == 1 || $fleet['fleet_mess'] == 0 && $fleet['fleet_mission'] == MT_RELOCATE || $fleet['fleet_target_owner'] != $user['id']) {
            //      $fleet_sn = flt_expand($fleet);
            $fleet_sn = sys_unit_str2arr($fleet['fleet_array']);
            foreach ($fleet_sn as $ship_id => $ship_amount) {
                if (in_array($ship_id, sn_get_groups('fleet'))) {
                    $fleet_list[$fleet_ownage]['total'][$ship_id] += $ship_amount;
                }
            }
        }
        $fleet_list[$fleet_ownage]['count']++;
        $fleet_list[$fleet_ownage]['amount'] += $fleet['fleet_amount'];
        $fleet_list[$fleet_ownage]['total'][RES_METAL] += $fleet['fleet_resource_metal'];
        $fleet_list[$fleet_ownage]['total'][RES_CRYSTAL] += $fleet['fleet_resource_crystal'];
        $fleet_list[$fleet_ownage]['total'][RES_DEUTERIUM] += $fleet['fleet_resource_deuterium'];
    }
    return $fleet_list;
}
Пример #10
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;
}
Пример #11
0
 * market.php
 *
 * Black market
 *
 * 1.0 - copyright (c) 2010 by Gorlum for http://supernova.ws
 *
 */
include 'common.' . substr(strrchr(__FILE__, '.'), 1);
define('SN_IN_MARKET', true);
lng_include('market');
lng_include('fleet');
$mode = sys_get_param_int('mode');
$action = sys_get_param_int('action');
$shipList = $_POST['ships'];
$page_title = "{$lang['eco_mrk_title']}";
$stock = sys_unit_str2arr($config->eco_stockman_fleet);
$newstock = $stock;
$intError = MARKET_DEAL;
switch ($mode) {
    case MARKET_RESOURCES:
        // Resource trader
        require 'includes/market/market_trader.inc';
        break;
    case MARKET_SCRAPPER:
        // Fleet scraper
        $rpg_cost = $config->rpg_cost_scraper;
        $submode = 'scraper';
        $error_no_stock = MARKET_NO_SHIPS;
        $error_zero_res = MARKET_ZERO_RES;
        $config_rpg_scrape_metal = $config->rpg_scrape_metal;
        $config_rpg_scrape_crystal = $config->rpg_scrape_crystal;
Пример #12
0
function qst_quest_parse($quest)
{
    list($quest['quest_unit_id'], $quest['quest_unit_amount']) = explode(',', $quest['quest_conditions']);
    $quest['quest_rewards_list'] = sys_unit_str2arr($quest['quest_rewards']);
    return $quest;
}
Пример #13
0
             if ($fleets_to_planet['own']['count']) {
                 $moon_fleet_id = $fleet_id;
                 $fleets[] = tpl_parse_fleet_sn($fleets_to_planet['own']['total'], $fleet_id);
                 $fleet_id++;
             }
         }
     }
 }
 //  $recyclers_incoming = 0;
 $recyclers_incoming_capacity = 0;
 $uni_galaxyRowPlanet['debris'] = $uni_galaxyRowPlanet['debris_metal'] + $uni_galaxyRowPlanet['debris_crystal'];
 if ($uni_galaxyRowPlanet['debris']) {
     if ($fleet_list[$Planet][PT_DEBRIS]) {
         foreach ($fleet_list[$Planet][PT_DEBRIS] as $fleet_row) {
             if ($fleet_row['fleet_owner'] == $user['id']) {
                 $fleet_data = sys_unit_str2arr($fleet_row['fleet_array']);
                 foreach ($recycler_info as $recycler_id => $recycler_data) {
                     $recyclers_incoming_capacity += $fleet_data[$recycler_id] * $recycler_data['capacity'];
                 }
             }
         }
     }
     $uni_galaxyRowPlanet['debris_reserved'] = $recyclers_incoming_capacity;
     $uni_galaxyRowPlanet['debris_reserved_percent'] = min(100, floor($uni_galaxyRowPlanet['debris_reserved'] / $uni_galaxyRowPlanet['debris'] * 100));
     $uni_galaxyRowPlanet['debris_to_gather'] = max(0, $uni_galaxyRowPlanet['debris'] - $recyclers_incoming_capacity);
     $uni_galaxyRowPlanet['debris_to_gather_percent'] = 100 - $uni_galaxyRowPlanet['debris_reserved_percent'];
     $recyclers_fleet_data = flt_calculate_fleet_to_transport($recyclers_fleet, $uni_galaxyRowPlanet['debris_to_gather'], $planetrow, $uni_galaxyRowPlanet);
     $uni_galaxyRowPlanet['debris_will_gather'] = max(0, min($recyclers_fleet_data['capacity'], $uni_galaxyRowPlanet['debris_to_gather']));
     $uni_galaxyRowPlanet['debris_will_gather_percent'] = $uni_galaxyRowPlanet['debris_to_gather'] ? floor($uni_galaxyRowPlanet['debris_will_gather'] / $uni_galaxyRowPlanet['debris_to_gather'] * $uni_galaxyRowPlanet['debris_to_gather_percent']) : 0;
     $uni_galaxyRowPlanet['debris_gather_total'] = max(0, $uni_galaxyRowPlanet['debris_will_gather'] + $uni_galaxyRowPlanet['debris_reserved']);
     $uni_galaxyRowPlanet['debris_gather_total_percent'] = min(100, floor($uni_galaxyRowPlanet['debris_gather_total'] / $uni_galaxyRowPlanet['debris'] * 100));
Пример #14
0
function flt_mission_explore(&$mission_data)
{
    if (!isset($mission_data['fleet_event']) || $mission_data['fleet_event'] != EVENT_FLT_ACOMPLISH) {
        return CACHE_NONE;
    }
    global $lang, $config;
    static $ship_data, $rates;
    $result = array('$mission_data' => $mission_data, '$outcome_list' => array(), '$mission_outcome' => FLT_EXPEDITION_OUTCOME_NONE, '$outcome_value' => 0, '$outcome_percent' => 0, '$outcome_mission_sub' => -1, '$fleet' => array(), '$fleet_lost' => array(), '$found_dark_matter' => 0, '$fleet_metal_points' => 0);
    $fleet =& $result['$fleet'];
    //  $fleet_left = &$result['$fleet_left'];
    $fleet_lost =& $result['$fleet_lost'];
    $outcome_mission_sub =& $result['$outcome_mission_sub'];
    $outcome_percent =& $result['$outcome_percent'];
    $found_dark_matter =& $result['$found_dark_matter'];
    $mission_outcome =& $result['$mission_outcome'];
    $outcome_value =& $result['$outcome_value'];
    $outcome_list =& $result['$outcome_list'];
    $fleet_metal_points =& $result['$fleet_metal_points'];
    if (!$ship_data) {
        foreach (sn_get_groups('fleet') as $unit_id) {
            $unit_info = get_unit_param($unit_id);
            if ($unit_info[P_UNIT_TYPE] != UNIT_SHIPS || !isset($unit_info['engine'][0]['speed']) || !$unit_info['engine'][0]['speed']) {
                continue;
            }
            $ship_data[$unit_id][P_COST_METAL] = get_unit_cost_in($unit_info[P_COST]);
        }
        $rates = get_resource_exchange();
    }
    $fleet_row = $mission_data['fleet'];
    $fleet = sys_unit_str2arr($fleet_row['fleet_array']);
    $fleet_capacity = 0;
    $fleet_metal_points = 0;
    foreach ($fleet as $ship_id => $ship_amount) {
        $unit_info = get_unit_param($ship_id);
        $fleet_capacity += $ship_amount * $unit_info[P_CAPACITY];
        $fleet_metal_points += $ship_amount * $ship_data[$ship_id][P_COST_METAL];
    }
    $fleet_capacity = max(0, $fleet_capacity - $fleet_row['fleet_resource_metal'] + $fleet_row['fleet_resource_crystal'] + $fleet_row['fleet_resource_deuterium']);
    $flt_stay_hours = ($fleet_row['fleet_end_stay'] - $fleet_row['fleet_start_time']) / 3600 * ($config->game_speed_expedition ? $config->game_speed_expedition : 1);
    $outcome_list = sn_get_groups('mission_explore_outcome_list');
    $outcome_list[FLT_EXPEDITION_OUTCOME_NONE]['chance'] = ceil(200 / pow($flt_stay_hours, 1 / 1.7));
    $chance_max = 0;
    foreach ($outcome_list as $key => &$value) {
        if (!$value['chance']) {
            unset($outcome_list[$key]);
            continue;
        }
        $value['value'] = $chance_max = $value['chance'] + $chance_max;
    }
    $outcome_value = mt_rand(0, $chance_max);
    // $outcome_value = 409;
    $outcome_description =& $outcome_list[$mission_outcome = FLT_EXPEDITION_OUTCOME_NONE];
    foreach ($outcome_list as $key => &$value) {
        if (!$value['chance']) {
            continue;
        }
        $mission_outcome = $key;
        $outcome_description = $value;
        if ($outcome_value <= $outcome_description['value']) {
            break;
        }
    }
    // Вычисляем вероятность выпадения данного числа в общем пуле
    $msg_sender = $lang['flt_mission_expedition']['msg_sender'];
    $msg_title = $lang['flt_mission_expedition']['msg_title'];
    $outcome_percent = ($outcome_description['value'] - $outcome_value) / $outcome_description['chance'];
    $msg_text = '';
    $msg_text_addon = '';
    $found_dark_matter = 0;
    //  $outcome_mission_sub = -1;
    switch ($mission_outcome) {
        //  switch(FLT_EXPEDITION_OUTCOME_LOST_FLEET) { // TODO DEBUG!
        case FLT_EXPEDITION_OUTCOME_LOST_FLEET:
            flt_mission_explore_outcome_lost_fleet($result);
            //      // $fleet_left = 1 - mt_rand(1, 3) * 0.25;// * 0.25;
            //      $fleet_left = 1 - mt_rand(1, 3) * mt_rand(200000, 300000) / 1000000;
            //      $fleet_lost = array();
            //      foreach($fleet as $unit_id => &$unit_amount) {
            //        $ships_left = floor($unit_amount * $fleet_left);
            //        $fleet_lost[$unit_id] = $unit_amount - $ships_left;
            //        $unit_amount = $ships_left;
            //        if(!$unit_amount) {
            //          unset($fleet[$unit_id]);
            //        }
            //      }
            break;
        case FLT_EXPEDITION_OUTCOME_LOST_FLEET_ALL:
            flt_mission_explore_outcome_lost_fleet_all($result);
            //      $fleet_lost = $fleet;
            //      $fleet = array();
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_FLEET:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем эквивалент найденного флота в метале
            // $found_in_metal = min($outcome_percent * $fleet_metal_points, $config->resource_multiplier * 10000000); // game_speed
            $found_in_metal = min($outcome_percent * $fleet_metal_points, game_resource_multiplier(true) * 10000000);
            // game_speed
            //  13 243 754 000 g x1
            //  60 762 247 000 a x10
            // 308 389 499 488 000 b x500
            // Рассчитываем стоимость самого дорого корабля в металле
            $max_metal_cost = 0;
            foreach ($fleet as $ship_id => $ship_amount) {
                $max_metal_cost = max($max_metal_cost, $ship_data[$ship_id]['metal_cost']);
            }
            // Ограничиваем корабли только теми, чья стоимость в металле меньше или равно стоимости самого дорогого корабля
            $can_be_found = array();
            foreach ($ship_data as $ship_id => $ship_info) {
                if ($ship_info['metal_cost'] < $max_metal_cost) {
                    $can_be_found[$ship_id] = $ship_info['metal_cost'];
                }
            }
            // Убираем колонизаторы и шпионов - миллиарды шпионов и колонизаторов нам не нужны
            unset($can_be_found[SHIP_COLONIZER]);
            unset($can_be_found[SHIP_SPY]);
            $fleet_found = array();
            while (count($can_be_found) && $found_in_metal >= max($can_be_found)) {
                $found_index = mt_rand(1, count($can_be_found)) - 1;
                $found_ship = array_slice($can_be_found, $found_index, 1, true);
                $found_ship_cost = reset($found_ship);
                $found_ship_id = key($found_ship);
                if ($found_ship_cost > $found_in_metal) {
                    unset($can_be_found[$found_ship_id]);
                } else {
                    $found_ship_count = mt_rand(1, floor($found_in_metal / $found_ship_cost));
                    $fleet_found[$found_ship_id] += $found_ship_count;
                    $found_in_metal -= $found_ship_count * $found_ship_cost;
                }
            }
            if (empty($fleet_found)) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            } else {
                foreach ($fleet_found as $unit_id => $unit_amount) {
                    $fleet[$unit_id] += $unit_amount;
                }
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_RESOURCES:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем количество найденных ресурсов
            $found_in_metal = ceil(min($outcome_percent * $fleet_metal_points, game_resource_multiplier(true) * 10000000, $fleet_capacity) * mt_rand(950000, 1050000) / 1000000);
            // game_speed
            $resources_found[RES_METAL] = floor(mt_rand(300000, 700000) / 1000000 * $found_in_metal);
            $found_in_metal -= $resources_found[RES_METAL];
            $found_in_metal = floor($found_in_metal * $rates[RES_METAL] / $rates[RES_CRYSTAL]);
            $resources_found[RES_CRYSTAL] = floor(mt_rand(500000, 1000000) / 1000000 * $found_in_metal);
            $found_in_metal -= $resources_found[RES_CRYSTAL];
            $found_in_metal = floor($found_in_metal * $rates[RES_CRYSTAL] / $rates[RES_DEUTERIUM]);
            $resources_found[RES_DEUTERIUM] = $found_in_metal;
            $fleet_row['fleet_resource_metal'] += $resources_found[RES_METAL];
            $fleet_row['fleet_resource_crystal'] += $resources_found[RES_CRYSTAL];
            $fleet_row['fleet_resource_deuterium'] += $resources_found[RES_DEUTERIUM];
            if (array_sum($resources_found) == 0) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_DM:
            $outcome_mission_sub = $outcome_percent >= 0.99 ? 0 : ($outcome_percent >= 0.9 ? 1 : 2);
            $outcome_percent = $outcome_description['percent'][$outcome_mission_sub];
            // Рассчитываем количество найденной ТМ
            $found_dark_matter = floor(min($outcome_percent * $fleet_metal_points / $rates[RES_DARK_MATTER], 10000) * mt_rand(750000, 1000000) / 1000000);
            if (!$found_dark_matter) {
                $msg_text_addon = $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['no_result'];
            }
            break;
        case FLT_EXPEDITION_OUTCOME_FOUND_ARTIFACT:
            break;
        default:
            break;
    }
    flt_mission_explore_addon($result);
    $query_data = array();
    if ($found_dark_matter) {
        rpg_points_change($fleet_row['fleet_owner'], RPG_EXPEDITION, $found_dark_matter, 'Expedition Bonus');
        $msg_text_addon = sprintf($lang['flt_mission_expedition']['found_dark_matter'], $found_dark_matter);
    }
    if (!empty($fleet_lost)) {
        $msg_text_addon = $lang['flt_mission_expedition']['lost_fleet'];
        foreach ($fleet_lost as $ship_id => $ship_amount) {
            $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
        }
    }
    $fleet_row['fleet_amount'] = array_sum($fleet);
    if (!empty($fleet) && $fleet_row['fleet_amount']) {
        if (!empty($fleet_found)) {
            $msg_text_addon = $lang['flt_mission_expedition']['found_fleet'];
            foreach ($fleet_found as $ship_id => $ship_amount) {
                $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
            }
        }
        if (!empty($resources_found) && array_sum($resources_found) > 0) {
            $msg_text_addon = $lang['flt_mission_expedition']['found_resources'];
            foreach ($resources_found as $ship_id => $ship_amount) {
                $msg_text_addon .= $lang['tech'][$ship_id] . ' - ' . $ship_amount . "\r\n";
            }
            $query_data[] = "`fleet_resource_metal` = `fleet_resource_metal` + {$resources_found[RES_METAL]}";
            $query_data[] = "`fleet_resource_crystal` = `fleet_resource_crystal` + {$resources_found[RES_CRYSTAL]}";
            $query_data[] = "`fleet_resource_deuterium` = `fleet_resource_deuterium` + {$resources_found[RES_DEUTERIUM]}";
        }
        if (!empty($fleet_lost) || !empty($fleet_found)) {
            $fleet_row['fleet_array'] = sys_unit_arr2str($fleet);
            $query_data[] = "`fleet_amount` = {$fleet_row['fleet_amount']}";
            $query_data[] = "`fleet_array` = '{$fleet_row['fleet_array']}'";
        }
        $query_data[] = '`fleet_mess` = 1';
        $query_data = "UPDATE {{fleets}} SET " . implode(',', $query_data);
    } else {
        // Удалить флот
        $query_data = "DELETE FROM {{fleets}}";
    }
    $query_data .= " WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1";
    doquery($query_data);
    db_user_set_by_id($fleet_row['fleet_owner'], "`player_rpg_explore_xp` = `player_rpg_explore_xp` + 1");
    if (!$msg_text) {
        $messages =& $lang['flt_mission_expedition']['outcomes'][$mission_outcome]['messages'];
        if ($outcome_mission_sub >= 0 && is_array($messages)) {
            $messages =& $messages[$outcome_mission_sub];
        }
        $msg_text = is_string($messages) ? $messages : (is_array($messages) ? $messages[mt_rand(0, count($messages) - 1)] : '');
    }
    $msg_text = sprintf($msg_text, $fleet_row['fleet_id'], uni_render_coordinates($fleet_row, 'fleet_end_')) . ($msg_text_addon ? "\r\n" . $msg_text_addon : '');
    msg_send_simple_message($fleet_row['fleet_owner'], '', $fleet_row['fleet_end_stay'], MSG_TYPE_EXPLORE, $msg_sender, $msg_title, $msg_text);
    return CACHE_FLEET | CACHE_USER_SRC;
}
Пример #15
0
function flt_mission_spy($mission_data)
{
    global $time_now;
    $fleet_row = $mission_data['fleet'];
    $target_user_row = $mission_data['dst_user'];
    $target_planet_row = $mission_data['dst_planet'];
    $spying_user_row = $mission_data['src_user'];
    $spying_planet_row = $mission_data['src_planet'];
    if (!$target_user_row || !$target_planet_row || !is_array($target_user_row) || !is_array($target_planet_row)) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    if ($fleet_array[SHIP_SPY] > 0) {
        $TargetSpyLvl = GetSpyLevel($target_user_row);
        //mrc_modify_value($target_user_row, $target_planet_row, MRC_SPY, GetSpyLevel($target_user_row));
        $CurrentSpyLvl = GetSpyLevel($spying_user_row);
        //mrc_modify_value($spying_user_row, $spying_planet_row, MRC_SPY, GetSpyLevel($spying_user_row));
        $spy_probes = $fleet_array[SHIP_SPY];
        $spy_diff = $CurrentSpyLvl + sqrt($spy_probes) - 1 - $TargetSpyLvl;
        /*
            pdump($spy_probes, '$spy_probes');
            pdump($CurrentSpyLvl, '$CurrentSpyLvl');
            pdump($TargetSpyLvl, '$TargetSpyLvl');
            pdump(sqrt($spy_probes), 'sqrt($spy_probes)');
            pdump($spy_diff, '$spy_diff');
        */
        global $lang, $sn_data;
        $spy_resources = flt_spy_scan($target_planet_row, 0, $lang['sys_spy_maretials'], $target_user_row['username']);
        $spy_info = flt_spy_scan($target_planet_row, 1, $lang['sys_spy_fleet']);
        $spy_fleet = "<div class='spy_medium'>{$spy_info}</div>";
        $spy_info = flt_spy_scan($target_planet_row, 2, $lang['sys_spy_defenses']);
        $spy_defence = "<div class='spy_medium'>{$spy_info}</div>";
        $spy_info = flt_spy_scan($target_planet_row, 3, $lang['tech'][0]);
        $spy_buildings = "<div class='spy_long'>{$spy_info}</div>";
        $combat_pack[0] = array(RES_METAL => $target_planet_row['metal'], RES_CRYSTAL => $target_planet_row['crystal'], RES_DEUTERIUM => $target_planet_row['deuterium']);
        $spy_message = $spy_resources;
        if ($spy_diff >= 2) {
            $spy_message .= $spy_fleet;
            coe_compress_add_units($sn_data['groups']['fleet'], $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 3) {
            $spy_message .= $spy_defence;
            coe_compress_add_units($sn_data['groups']['defense_active'], $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 5) {
            $spy_message .= $spy_buildings;
        }
        if ($spy_diff >= 7) {
            $spy_info = flt_spy_scan($target_user_row, 4, $lang['tech'][TECH_TECHNOLOGY]);
            $spy_tech = "<div class='spy_long'>{$spy_info}</div>";
            $spy_message .= $spy_tech;
            coe_compress_add_units(array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR), $target_user_row, $combat_pack[0]);
        }
        $simulator_link = eco_sym_encode_replay($combat_pack, 'D');
        $target_unit_list = 0;
        foreach ($sn_data['groups']['fleet'] as $unit_id) {
            $target_unit_list += max(0, $target_planet_row[$sn_data[$unit_id]['name']]);
        }
        $spy_detected = $spy_probes * $target_unit_list / 4 * pow(2, $TargetSpyLvl - $CurrentSpyLvl);
        if (mt_rand(0, 99) > $spy_detected) {
            $DestProba = sprintf($lang['sys_mess_spy_detect_chance'], $spy_detected);
            $spy_detected = false;
        } else {
            $DestProba = $lang['sys_mess_spy_destroyed'];
            $spy_detected = true;
        }
        $spy_message .= "<br /><center><a href=\"fleet.php?target_mission=1&planet_type={$fleet_row['fleet_end_type']}&galaxy={$fleet_row['fleet_end_galaxy']}";
        $spy_message .= "&system={$fleet_row['fleet_end_system']}&planet={$fleet_row['fleet_end_planet']} \">{$lang['type_mission'][1]}</a></center>";
        $spy_message .= "<center><a href=\"simulator.php?replay={$simulator_link}\">{$lang['COE_combatSimulator']}</a></center><br />";
        $spy_message .= "<center>" . $DestProba . "</center>";
        // End of link generation
        msg_send_simple_message($spying_user_row['id'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_qg'], $lang['sys_mess_spy_report'], $spy_message);
        $TargetMessage = $lang['sys_mess_spy_ennemyfleet'] . " " . $spying_planet_row['name'];
        $TargetMessage .= "<a href=\"galaxy.php?mode=3&galaxy=" . $spying_planet_row["galaxy"] . "&system=" . $spying_planet_row["system"] . "\">";
        $TargetMessage .= "[" . $spying_planet_row["galaxy"] . ":" . $spying_planet_row["system"] . ":" . $spying_planet_row["planet"] . "]</a> ";
        $TargetMessage .= $lang['sys_mess_spy_seen_at'] . " " . $target_planet_row['name'];
        $TargetMessage .= " [" . $target_planet_row["galaxy"] . ":" . $target_planet_row["system"] . ":" . $target_planet_row["planet"] . "].";
        $target_user_id = $fleet_row['fleet_target_owner'];
        if ($spy_detected) {
            doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
            if ($target_planet_row['planet_type'] == PT_PLANET) {
                $debris_planet_id = $target_planet_row['id'];
            } else {
                $debris_planet_id = $target_planet_row['parent_planet'];
            }
            $QryUpdateGalaxy = "UPDATE {{planets}} SET ";
            $QryUpdateGalaxy .= "`debris_metal` = `debris_metal` + '" . floor($spy_probes * $sn_data[SHIP_SPY]['metal'] * 0.3) . "', ";
            $QryUpdateGalaxy .= "`debris_crystal` = `debris_crystal` + '" . floor($spy_probes * $sn_data[SHIP_SPY]['crystal'] * 0.3) . "' ";
            $QryUpdateGalaxy .= "WHERE `id` = '{$debris_planet_id}' LIMIT 1;";
            doquery($QryUpdateGalaxy);
            $TargetMessage .= "<br />{$lang['sys_mess_spy_destroyed_enemy']}";
            //      msg_send_simple_message ( $target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $TargetMessage . );
            $result = CACHE_FLEET | CACHE_PLANET_DST;
        } else {
            $result = CACHE_FLEET;
        }
        msg_send_simple_message($target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $TargetMessage);
    }
    if (!$spy_detected) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    return $result;
}
Пример #16
0
function flt_mission_spy(&$mission_data)
{
    global $lang;
    $fleet_row =& $mission_data['fleet'];
    $target_user_row =& $mission_data['dst_user'];
    $target_planet_row =& $mission_data['dst_planet'];
    $spying_user_row =& $mission_data['src_user'];
    $spying_planet_row =& $mission_data['src_planet'];
    if (!isset($target_user_row['id']) || !isset($target_planet_row['id']) || !isset($spying_user_row['id'])) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = 1 WHERE `fleet_id` = {$fleet_row['fleet_id']} LIMIT 1;");
        return;
    }
    $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']);
    if ($fleet_array[SHIP_SPY] > 0) {
        $TargetSpyLvl = GetSpyLevel($target_user_row);
        $CurrentSpyLvl = GetSpyLevel($spying_user_row);
        $spy_diff_empire = $CurrentSpyLvl - $TargetSpyLvl;
        $spy_probes = $fleet_array[SHIP_SPY];
        $spy_diff = $spy_diff_empire + sqrt($spy_probes) - 1;
        $combat_pack[0] = array(RES_METAL => $target_planet_row['metal'], RES_CRYSTAL => $target_planet_row['crystal'], RES_DEUTERIUM => $target_planet_row['deuterium']);
        $spy_message = "<table width=\"440\" cellspacing = \"1\"><tr><td class=\"c\" colspan=\"4\">{$lang['sys_spy_maretials']} {$target_planet_row['name']} ";
        $spy_message .= uni_render_coordinates_href($target_planet_row, '', 3);
        $spy_message .= " ({$lang['Player_']} '{$target_user_row['username']}') {$lang['On_']} ";
        $spy_message .= date(FMT_DATE_TIME, $fleet_row['fleet_end_time']);
        $spy_message .= "</td></tr><tr>";
        $spy_message .= "<td width=220>{$lang['sys_metal']}</td><td width=220 align=right>" . pretty_number($target_planet_row['metal']) . "</td>";
        $spy_message .= "<td width=220>{$lang['sys_crystal']}</td></td><td width=220 align=right>" . pretty_number($target_planet_row['crystal']) . "</td>";
        $spy_message .= "</tr><tr>";
        $spy_message .= "<td width=220>{$lang['sys_deuterium']}</td><td width=220 align=right>" . pretty_number($target_planet_row['deuterium']) . "</td>";
        $spy_message .= "<td width=220>{$lang['sys_energy']}</td><td width=220 align=right>" . pretty_number($target_planet_row['energy_max']) . "</td>";
        $spy_message .= "</tr>";
        if ($spy_diff >= 2) {
            $spy_message .= "<div class='spy_medium'>" . flt_spy_scan($target_planet_row, 'fleet', $lang['tech'][UNIT_SHIPS], $target_user_row) . "</div>";
            coe_compress_add_units(sn_get_groups('fleet'), $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 3) {
            $spy_message .= "<div class='spy_medium'>" . flt_spy_scan($target_planet_row, 'defense', $lang['tech'][UNIT_DEFENCE], $target_user_row) . "</div>";
            coe_compress_add_units(sn_get_groups('defense_active'), $target_planet_row, $combat_pack[0]);
        }
        if ($spy_diff >= 5) {
            $spy_message .= "<div class='spy_long'>" . flt_spy_scan($target_planet_row, 'structures', $lang['tech'][UNIT_STRUCTURES], $target_user_row) . "</div>";
        }
        if ($spy_diff_empire >= 0) {
            $spy_message .= "<div class='spy_long'>" . flt_spy_scan($target_planet_row, 'tech', $lang['tech'][UNIT_TECHNOLOGIES], $target_user_row) . "</div>";
            coe_compress_add_units(array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR), $target_planet_row, $combat_pack[0], $target_user_row);
        }
        // TODO: Наемники, губернаторы, артефакты и прочее имперское
        $simulator_link = sn_ube_simulator_encode_replay($combat_pack, 'D');
        $target_unit_list = 0;
        foreach (sn_get_groups('fleet') as $unit_id) {
            $target_unit_list += max(0, mrc_get_level($target_user_row, $target_planet_row, $unit_id, false, true));
        }
        $spy_detected = $spy_probes * $target_unit_list / 4 * pow(2, $TargetSpyLvl - $CurrentSpyLvl);
        if (mt_rand(0, 99) > $spy_detected) {
            $spy_outcome_str = sprintf($lang['sys_mess_spy_detect_chance'], $spy_detected);
            $spy_detected = false;
        } else {
            $spy_outcome_str = $lang['sys_mess_spy_destroyed'];
            $spy_detected = true;
        }
        $spy_message .= "<tr><th class=\"c_c\" colspan=4>";
        $spy_message .= "{$spy_outcome_str}<br />";
        $spy_message .= "<a href=\"fleet.php?target_mission=1&planet_type={$fleet_row['fleet_end_type']}&galaxy={$fleet_row['fleet_end_galaxy']}&system={$fleet_row['fleet_end_system']}&planet={$fleet_row['fleet_end_planet']} \">{$lang['type_mission'][1]}</a><br />";
        $spy_message .= "<a href=\"simulator.php?replay={$simulator_link}\">{$lang['COE_combatSimulator']}</a><br />";
        $spy_message .= "</th></tr></table>";
        // End of link generation
        msg_send_simple_message($spying_user_row['id'], '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_qg'], $lang['sys_mess_spy_report'], $spy_message);
        $target_message = "{$lang['sys_mess_spy_ennemyfleet']} {$spying_planet_row['name']} " . uni_render_coordinates_href($spying_planet_row, '', 3);
        $target_message .= " {$lang['sys_mess_spy_seen_at']} {$target_planet_row['name']} " . uni_render_coordinates($target_planet_row);
        $target_user_id = $fleet_row['fleet_target_owner'];
        if ($spy_detected) {
            doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
            $debris_planet_id = $target_planet_row['planet_type'] == PT_PLANET ? $target_planet_row['id'] : $target_planet_row['parent_planet'];
            $spy_cost = get_unit_param(SHIP_SPY, P_COST);
            db_planet_set_by_id($debris_planet_id, "`debris_metal` = `debris_metal` + " . floor($spy_probes * $spy_cost[RES_METAL] * 0.3) . ", `debris_crystal` = `debris_crystal` + " . floor($spy_probes * $spy_cost[RES_CRYSTAL] * 0.3));
            $target_message .= "<br />{$lang['sys_mess_spy_destroyed_enemy']}";
            $result = CACHE_FLEET | CACHE_PLANET_DST;
        } else {
            $result = CACHE_FLEET;
        }
        msg_send_simple_message($target_user_id, '', $fleet_row['fleet_start_time'], MSG_TYPE_SPY, $lang['sys_mess_spy_control'], $lang['sys_mess_spy_activity'], $target_message);
    }
    if (!$spy_detected) {
        doquery("UPDATE {{fleets}} SET `fleet_mess` = '1' WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
    }
    return $result;
}