Exemple #1
0
function db_change_units(&$user, &$planet, $unit_list = array(), $query = null)
{
    $query = is_array($query) ? $query : array(LOC_USER => array(), LOC_PLANET => array());
    $group = sn_get_groups('resources_loot');
    foreach ($unit_list as $unit_id => $unit_amount) {
        if (!in_array($unit_id, $group)) {
            // TODO - remove later
            print '<h1>СООБЩИТЕ ЭТО АДМИНУ: db_change_units() вызван для не-ресурсов!</h1>';
            pdump(debug_backtrace());
            die('db_change_units() вызван для не-ресурсов!');
        }
        if (!$unit_amount) {
            continue;
        }
        $unit_db_name = pname_resource_name($unit_id);
        $unit_location = sys_get_unit_location($user, $planet, $unit_id);
        // Changing value in object
        switch ($unit_location) {
            case LOC_USER:
                $user[$unit_db_name] += $unit_amount;
                break;
            case LOC_PLANET:
                $planet[$unit_db_name] += $unit_amount;
                break;
        }
        $unit_amount = $unit_amount < 0 ? $unit_amount : "+{$unit_amount}";
        // Converting positive unit_amount to string '+unit_amount'
        $query[$unit_location][$unit_id] = "`{$unit_db_name}`=`{$unit_db_name}`{$unit_amount}";
    }
    db_change_units_perform($query[LOC_USER], 'users', $user['id']);
    db_change_units_perform($query[LOC_PLANET], 'planets', $planet['id']);
}
Exemple #2
0
/**
 * @param int        $Galaxy
 * @param int        $System
 * @param int        $Position
 * @param int        $PlanetOwnerID
 * @param string     $planet_name_unsafe
 * @param bool|false $HomeWorld
 * @param array      $options
 *
 * @return bool
 */
function uni_create_planet($Galaxy, $System, $Position, $PlanetOwnerID, $planet_name_unsafe = '', $HomeWorld = false, $options = array())
{
    global $lang, $config;
    $Position = intval($Position);
    if (!isset($options['skip_check']) && db_planet_by_gspt($Galaxy, $System, $Position, PT_PLANET, true, '`id`')) {
        return false;
    }
    $user_row = !empty($options['user_row']) && is_array($options['user_row']) ? $options['user_row'] : db_user_by_id($PlanetOwnerID);
    $planet_generator = sn_get_groups('planet_generator');
    if ($HomeWorld) {
        $position_data = $planet_generator[0];
    } else {
        $position_data = $planet_generator[$Position >= UNIVERSE_RANDOM_PLANET_START || $Position < 1 ? UNIVERSE_RANDOM_PLANET_START : $Position];
        if ($Position >= UNIVERSE_RANDOM_PLANET_START) {
            // Корректируем температуру для планеты-странника
            $position_data['t_max_max'] -= UNIVERSE_RANDOM_PLANET_TEMPERATURE_DECREASE * ($Position - UNIVERSE_RANDOM_PLANET_START);
        }
    }
    $planet_images = sn_get_groups('planet_images');
    $planet_image = $position_data['planet_images'][mt_rand(0, count($position_data['planet_images']) - 1)];
    $planet_image .= 'planet' . $planet_images[$planet_image][mt_rand(0, count($planet_images[$planet_image]) - 1)];
    $t_max = sn_rand_gauss_range($position_data['t_max_min'], $position_data['t_max_max'], true, 1.3, true);
    $t_min = $t_max - sn_rand_gauss_range($position_data['t_delta_min'], $position_data['t_delta_max'], true, 1.3, true);
    $planet_sectors = sn_rand_gauss_range($position_data['size_min'], $position_data['size_max'], true, 1.7, true);
    //  $planet_diameter = round(pow($planet_sectors, 2) * 1000);
    $planet_diameter = round(sqrt($planet_sectors) * 1000);
    $core_info = uni_create_planet_get_density($position_data, $user_row, $planet_sectors);
    $planet_name_unsafe = $user_row['username'] . ' ' . ($planet_name_unsafe ? $planet_name_unsafe : $lang['sys_colo_defaultname']);
    $planet['name'] = db_escape(strip_tags(trim($planet_name_unsafe)));
    $planet['id_owner'] = $PlanetOwnerID;
    $planet['last_update'] = SN_TIME_NOW;
    $planet['image'] = $planet_image;
    $planet['galaxy'] = $Galaxy;
    $planet['system'] = $System;
    $planet['planet'] = $planet['position_original'] = $Position;
    $planet['planet_type'] = PT_PLANET;
    $planet['diameter'] = $planet_diameter;
    $planet['field_max'] = $planet['field_max_original'] = $planet_sectors;
    $planet['density'] = $core_info[UNIT_PLANET_DENSITY];
    $planet['density_index'] = $core_info[UNIT_PLANET_DENSITY_INDEX];
    $planet['temp_min'] = $planet['temp_min_original'] = $t_min;
    $planet['temp_max'] = $planet['temp_max_original'] = $t_max;
    $planet['metal'] = $config->eco_planet_starting_metal;
    $planet['crystal'] = $config->eco_planet_starting_crystal;
    $planet['deuterium'] = $config->eco_planet_starting_deuterium;
    $planet['metal_max'] = $config->eco_planet_storage_metal;
    $planet['crystal_max'] = $config->eco_planet_storage_crystal;
    $planet['deuterium_max'] = $config->eco_planet_storage_deuterium;
    $density_info_resources =& $density_list[$core_info[UNIT_PLANET_DENSITY_INDEX]][UNIT_RESOURCES];
    $planet['metal_perhour'] = $config->metal_basic_income * $density_info_resources[RES_METAL];
    $planet['crystal_perhour'] = $config->crystal_basic_income * $density_info_resources[RES_CRYSTAL];
    $planet['deuterium_perhour'] = $config->deuterium_basic_income * $density_info_resources[RES_DEUTERIUM];
    $RetValue = classSupernova::db_ins_record(LOC_PLANET, "`name` = '{$planet['name']}', `id_owner` = '{$planet['id_owner']}', `last_update` = '{$planet['last_update']}', `image` = '{$planet['image']}',\n      `galaxy` = '{$planet['galaxy']}', `system` = '{$planet['system']}', `planet` = '{$planet['planet']}', `planet_type` = '{$planet['planet_type']}', `position_original` = '{$planet['position_original']}',\n      `diameter` = '{$planet['diameter']}', `field_max` = '{$planet['field_max']}', `field_max_original` = '{$planet['field_max_original']}',\n      `density` = '{$planet['density']}', `density_index` = '{$planet['density_index']}',\n      `temp_min` = '{$planet['temp_min']}', `temp_max` = '{$planet['temp_max']}', `temp_min_original` = '{$planet['temp_min_original']}', `temp_max_original` = '{$planet['temp_max_original']}',\n      `metal` = '{$planet['metal']}', `metal_perhour` = '{$planet['metal_perhour']}', `metal_max` = '{$planet['metal_max']}',\n      `crystal` = '{$planet['crystal']}', `crystal_perhour` = '{$planet['crystal_perhour']}', `crystal_max` = '{$planet['crystal_max']}',\n      `deuterium` = '{$planet['deuterium']}', `deuterium_perhour` = '{$planet['deuterium_perhour']}', `deuterium_max` = '{$planet['deuterium_max']}'");
    return is_array($RetValue) ? $RetValue['id'] : false;
    // OK
}
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;
}
function eco_bld_tech($que_type, &$user, &$planet)
{
    global $config, $lang;
    lng_include('buildings');
    lng_include('infos');
    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]);
    }
    switch ($action = sys_get_param_escaped('action')) {
        case 'build':
            $operation_result = que_build($user, $planet);
            break;
        case 'trim':
            que_delete(QUE_RESEARCH, $user, $planet, false);
            break;
        case 'clear':
            que_delete(QUE_RESEARCH, $user, $planet, true);
            break;
            //case 'build':$operation_result = eco_bld_tech_research($user, $planet);break;
    }
    $template = gettemplate('buildings_research', true);
    if (!empty($operation_result)) {
        $template->assign_block_vars('result', $operation_result);
    }
    $fleet_list = flt_get_fleets_to_planet($planet);
    $ques = que_get($user['id'], QUE_RESEARCH);
    $que =& $ques['ques'][QUE_RESEARCH][$user['id']][0];
    que_tpl_parse($template, QUE_RESEARCH, $user, null, $que);
    $in_que =& $ques['in_que'][QUE_RESEARCH][$user['id']][0];
    foreach (sn_get_groups('tech') as $unit_id) {
        if (eco_can_build_unit($user, $planet, $unit_id) != BUILD_ALLOWED) {
            continue;
        }
        $level_base = mrc_get_level($user, '', $unit_id, false, true);
        $level_effective = mrc_get_level($user, '', $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;
        $build_data = eco_get_build_data($user, $planet, $unit_id, $level_base_and_que);
        $temp[RES_METAL] = floor($planet['metal'] - $build_data[BUILD_CREATE][RES_METAL]);
        $temp[RES_CRYSTAL] = floor($planet['crystal'] - $build_data[BUILD_CREATE][RES_CRYSTAL]);
        $temp[RES_DEUTERIUM] = floor($planet['deuterium'] - $build_data[BUILD_CREATE][RES_DEUTERIUM]);
        $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, 'BUILD_CAN' => $build_data['CAN'][BUILD_CREATE], 'TIME' => pretty_time($build_data[RES_TIME][BUILD_CREATE]), 'METAL' => $build_data[BUILD_CREATE][RES_METAL], 'CRYSTAL' => $build_data[BUILD_CREATE][RES_CRYSTAL], 'DEUTERIUM' => $build_data[BUILD_CREATE][RES_DEUTERIUM], 'METAL_PRINT' => pretty_number($build_data[BUILD_CREATE][RES_METAL], true, $planet['metal']), 'CRYSTAL_PRINT' => pretty_number($build_data[BUILD_CREATE][RES_CRYSTAL], true, $planet['crystal']), 'DEUTERIUM_PRINT' => pretty_number($build_data[BUILD_CREATE][RES_DEUTERIUM], true, $planet['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), 'METAL_REST_NUM' => $temp[RES_METAL], 'CRYSTAL_REST_NUM' => $temp[RES_CRYSTAL], 'DEUTERIUM_REST_NUM' => $temp[RES_DEUTERIUM], 'METAL_FLEET' => pretty_number($temp[RES_METAL] + $fleet_list['own']['total'][RES_METAL], true, true), 'CRYSTAL_FLEET' => pretty_number($temp[RES_CRYSTAL] + $fleet_list['own']['total'][RES_CRYSTAL], true, true), 'DEUTERIUM_FLEET' => pretty_number($temp[RES_DEUTERIUM] + $fleet_list['own']['total'][RES_DEUTERIUM], true, true), 'BUILD_CAN2' => $build_data['CAN'][BUILD_CREATE]));
    }
    //  if(count($que['ques'][$que_id][$user['id']][$planet_id]) >= que_get_max_que_length($user, $planet, $que_id, $que_data))
    $template->assign_vars(array('QUE_ID' => QUE_RESEARCH, 'FLEET_OWN_COUNT' => $fleet_list['own']['count'], 'ARTIFACT_ID' => ART_HEURISTIC_CHIP, 'ARTIFACT_LEVEL' => mrc_get_level($user, array(), ART_HEURISTIC_CHIP), 'ARTIFACT_NAME' => $lang['tech'][ART_HEURISTIC_CHIP], 'REQUEST_URI' => $_SERVER['REQUEST_URI'], 'PAGE_HEADER' => $page_header = $lang['tech'][UNIT_TECHNOLOGIES] . ($user['user_as_ally'] ? "&nbsp;{$lang['sys_of_ally']}&nbsp;{$user['username']}" : ''), 'CONFIG_RESEARCH_QUE' => $config->server_que_length_research));
    display(parsetemplate($template), $page_header);
}
Exemple #5
0
function que_process(&$user, $planet = null, $on_time = SN_TIME_NOW)
{
    sn_db_transaction_check(true);
    $que = array();
    // Блокируем пользователя. Собственно, запись о нём нам не нужна - будем использовать старую
    $user = db_user_by_id($user['id'], true);
    $time_left[$user['id']][0] = max(0, $on_time - $user['que_processed']);
    if ($planet === null && !$time_left[$user['id']][0]) {
        // TODO
        return $que;
    }
    // Определяем, какие очереди нам нужны и получаем их
    $que_type_id = $planet === null ? QUE_RESEARCH : false;
    $planet = intval(is_array($planet) ? $planet['id'] : $planet);
    // В $planet у нас теперь только её ID или шаблон null/0/false
    $que = que_get($user['id'], $planet, $que_type_id, true);
    //pdump($que);
    if (empty($que['items'])) {
        return $que;
    }
    $planet_list = array();
    if ($planet !== null) {
        // Если нужно изменять данные на планетах - блокируем планеты и получаем данные о них
        // TODO - от них не надо ничего, кроме ID и que_processed
        // $planet_query = db_planet_list_by_user_or_planet($user['id'], $planet);
        // foreach($planet_query as $planet_row)
        $planet_row = db_planet_list_by_user_or_planet($user['id'], $planet);
        $planet_list[$planet_row['id']] = $planet_row;
        $time_left[$planet_row['id_owner']][$planet_row['id']] = max(0, $on_time - $planet_row['que_processed']);
    }
    // pdump($time_left);
    // Теперь в $time_left лежит время обсчета всех очередей по каждой из планеты
    if (array_sum($time_left[$user['id']]) == 0) {
        return $que;
    }
    // pdump($que);
    $db_changeset = array();
    $unit_changes = array();
    foreach ($que['items'] as &$que_item) {
        $que_player_id =& $que_item['que_player_id'];
        $que_planet_id = intval($que_item['que_planet_id']);
        // $que_type = &$que_item['que_type'];
        $que_time_left =& $que['time_left'][$que_player_id][$que_planet_id][$que_item['que_type']];
        if (!isset($que_time_left)) {
            $que_time_left = $time_left[$que_player_id][$que_planet_id];
        }
        if ($que_time_left <= 0 || $que_item['que_unit_amount'] <= 0) {
            continue;
        }
        // Дальше мы идем, если только осталось время в очереди И юниты к постройке
        // Вычисляем, сколько целых юнитов будет построено - от 0 до количества юнитов в очереди
        $unit_processed = min($que_item['que_unit_amount'] - 1, floor($que_time_left / $que_item['que_unit_time']));
        // Вычитаем это время из остатков
        $que_time_left -= $unit_processed * $que_item['que_unit_time'];
        // Теперь работаем с остатком времени на юните. Оно не может быть равно или меньше нуля
        // Если времени в очереди осталось не меньше, чем время текущего юнита - значит мы достроили юнит
        if ($que_time_left >= $que_item['que_time_left']) {
            // Увеличиваем количество отстроенных юнитов
            $unit_processed++;
            // Вычитаем из времени очереди потраченное на постройку время
            $que_time_left -= $que_item['que_time_left'];
            // Полное время юнита равно времени нового юнита
            $que_item['que_time_left'] = $que_item['que_unit_time'];
            // Тут у нас может остатся время очереди - если постройка была не последняя
        }
        // Изменяем количество оставшихся юнитов
        $que_item['que_unit_amount'] -= $unit_processed;
        // Если еще остались юниты - значит ВСЁ оставшееся время приходится на достройку следующего юнита
        if ($que_item['que_unit_amount'] > 0) {
            $que_item['que_time_left'] = $que_item['que_time_left'] - $que_time_left;
            $que_time_left = 0;
        }
        if ($que_item['que_unit_amount'] <= 0) {
            $db_changeset['que'][] = array('action' => SQL_OP_DELETE, P_VERSION => 1, 'where' => array("que_id" => $que_item['que_id']));
        } else {
            $db_changeset['que'][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array("que_id" => $que_item['que_id']), 'fields' => array('que_unit_amount' => array('delta' => -$unit_processed), 'que_time_left' => array('set' => $que_item['que_time_left'])));
        }
        if ($unit_processed) {
            $unit_processed_delta = $unit_processed * ($que_item['que_unit_mode'] == BUILD_CREATE ? 1 : -1);
            $unit_changes[$que_player_id][$que_planet_id][$que_item['que_unit_id']] += $unit_processed_delta;
        }
    }
    foreach ($time_left as $player_id => $planet_data) {
        foreach ($planet_data as $planet_id => $time_on_planet) {
            $table = $planet_id ? 'planets' : 'users';
            $id = $planet_id ? $planet_id : $player_id;
            $db_changeset[$table][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array("id" => $id), 'fields' => array('que_processed' => array('set' => $on_time)));
            if (is_array($unit_changes[$player_id][$planet_id])) {
                foreach ($unit_changes[$player_id][$planet_id] as $unit_id => $unit_amount) {
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_amount, $user, $planet_id ? $planet_id : null);
                }
            }
        }
    }
    //pdump($db_changeset, '$db_changeset');
    $que = que_recalculate($que);
    //pdump($que, '$que');
    // TODO: Re-enable quests for Alliances
    if (!empty($unit_changes) && !$user['user_as_ally']) {
        $quest_list = qst_get_quests($user['id']);
        $quest_triggers = qst_active_triggers($quest_list);
        $quest_rewards = array();
        $xp_incoming = array();
        foreach ($unit_changes as $user_id => $planet_changes) {
            foreach ($planet_changes as $planet_id => $changes) {
                $planet_this = $planet_id ? classSupernova::db_get_record_by_id(LOC_PLANET, $planet_id) : array();
                foreach ($changes as $unit_id => $unit_value) {
                    $que_id = que_get_unit_que($unit_id);
                    $unit_level_new = mrc_get_level($user, $planet_this, $unit_id, false, true) + $unit_value;
                    if ($que_id == QUE_STRUCTURES || $que_id == QUE_RESEARCH) {
                        $build_data = eco_get_build_data($user, $planet_this, $unit_id, $unit_level_new - 1);
                        $build_data = $build_data[BUILD_CREATE];
                        foreach (sn_get_groups('resources_loot') as $resource_id) {
                            $xp_incoming[$que_id] += $build_data[$resource_id];
                            // TODO - добавить конверсию рейтов обмена
                        }
                    }
                    if (is_array($quest_triggers)) {
                        // TODO: Check mutiply condition quests
                        $quest_trigger_list = array_keys($quest_triggers, $unit_id);
                        if (is_array($quest_trigger_list)) {
                            foreach ($quest_trigger_list as $quest_id) {
                                if ($quest_list[$quest_id]['quest_status_status'] != QUEST_STATUS_COMPLETE && $quest_list[$quest_id]['quest_unit_amount'] <= $unit_level_new) {
                                    $quest_rewards[$quest_id][$user_id][$planet_id] = $quest_list[$quest_id]['quest_rewards_list'];
                                    $quest_list[$quest_id]['quest_status_status'] = QUEST_STATUS_COMPLETE;
                                }
                            }
                        }
                    }
                }
            }
        }
        // TODO: Изменить начисление награды за квесты на ту планету, на которой происходил ресеч
        qst_reward($user, $quest_rewards, $quest_list);
        foreach ($xp_incoming as $que_id => $xp) {
            rpg_level_up($user, $que_id == QUE_RESEARCH ? RPG_TECH : RPG_STRUCTURE, $xp / 1000);
        }
    }
    db_changeset_apply($db_changeset);
    // TODO Сообщения о постройке
    // $user = db_user_by_id($user['id'], true);
    return $que;
    /*
    
    
    
      // $local_que['time_left'][QUE_RESEARCH][0] = $time_left[QUE_RESEARCH][0];
    
    //pdump($user_time_left, '$user_time_left');
    
      print('1');
      //foreach($local_que as $que_id => &$que_data)
      //{
      //  if(!intval($que_id))continue;
      foreach(sn_get_groups('que') as $que_id => $que_info)
      {
        if(!isset($que['ques'][$que_id]))continue;
    
        foreach($que_data as $owner_id => &$que_items)
        {
          foreach($que_items as &$que_item)
          {
            // Вычисляем, сколько целых юнитов будет построено - от 0 до количества юнитов в очереди
            $unit_processed = min($que_item['que_unit_amount'] - 1, floor($local_que['time_left'][$que_id][$owner_id] / $que_item['que_unit_time']));
            // Вычитаем это время из остатков
            $local_que['time_left'][$que_id][$owner_id] -= $unit_processed * $que_item['que_unit_time'];
    
            // Теперь работаем с остатком времени на юните. Оно не может быть равно или меньше нуля
    
            // Вычитаем остаток времени работы очереди с времени постройки юнита
            if($que_item['que_time_left'] <= $local_que['time_left'][$que_id][$owner_id])
            {
              // Если время постройки - неположительное, значит мы достроили юнит
              // Увеличиваем количество отстроенных юнитов
              $unit_processed++;
              // Вычитаем из времени очереди потраченное на постройку время
              $local_que['time_left'][$que_id][$owner_id] -= $que_item['que_time_left'];
              $que_item['que_time_left'] = $que_item['que_unit_time'];
              // Тут у нас может остатся время очереди - если постройка была не последняя
            }
    
            // Изменяем количество оставшихся юнитов
            $que_item['que_unit_amount'] -= $unit_processed;
    
            if($que_item['que_unit_amount'])
            {
              $que_item['que_time_left'] = $que_item['que_time_left'] - $local_que['time_left'][$que_id][$owner_id];
              $local_que['time_left'][$que_id][$owner_id] = 0;
            }
    
            if(!$que_item['que_unit_amount'])
            {
              $db_changeset['que'][$que_item['que_id']] = array(
                'action' => SQL_OP_DELETE,
                'where' => array(
                  "`que_id` = {$que_item['que_id']}",
                ),
              );
            }
            else
            {
              $db_changeset['que'][$que_item['que_id']] = array(
                'action' => SQL_OP_UPDATE,
                'where' => array(
                  "`que_id` = {$que_item['que_id']}",
                ),
                'fields' => array(
                  'que_unit_amount' => array(
                    'delta' => -$unit_processed
                  ),
                  'que_time_left' => array(
                    'set' => $que_item['que_time_left']
                  ),
                ),
              );
            }
    
            if($unit_processed)
            {
              $unit_processed_delta = $unit_processed * ($que_item['que_unit_mode'] == BUILD_CREATE ? 1 : -1);
              $unit_changes[$owner_id][$que_item['que_unit_id']] += $unit_processed_delta;
            }
            // Если на очереди времени не осталось - выходим
            if(!$local_que['time_left'][$que_id][$owner_id])
            {
              break;
            }
          }
        }
      }
    
      die();
    
    
      // TODO: Re-enable quests for Alliances
      if(!empty($unit_changes) && !$user['user_as_ally'] && $user['id_planet'])
      {
        $planet = db_planet_by_id($user['id_planet'], true);
        $quest_list = qst_get_quests($user['id']);
        $quest_triggers = qst_active_triggers($quest_list);
      }
      else
      {
        $planet = array();
      }
    
      $quest_rewards = array();
      $xp_incoming = 0;
      foreach($unit_changes as $owner_id => $changes)
      {
        // $user_id_sql = $owner_id ? $owner_id : $user['id'];
        $planet_id_sql = $owner_id ? $owner_id : null;
        foreach($changes as $unit_id => $unit_value)
        {
    
          $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_value, $user, $planet_id_sql);
    
          // TODO: Изменить согласно типу очереди
          $unit_level_new = mrc_get_level($user, array(), $unit_id, false, true) + $unit_value;
          $build_data = eco_get_build_data($user, array(), $unit_id, $unit_level_new - 1);
          $build_data = $build_data[BUILD_CREATE];
          foreach(sn_get_groups('resources_loot') as $resource_id)
          {
            $xp_incoming += $build_data[$resource_id];
          }
    
          if($planet['id'])
          {
            // TODO: Check mutiply condition quests
            $quest_trigger_list = array_keys($quest_triggers, $unit_id);
            foreach($quest_trigger_list as $quest_id)
            {
              if($quest_list[$quest_id]['quest_status_status'] != QUEST_STATUS_COMPLETE && $quest_list[$quest_id]['quest_unit_amount'] <= $unit_level_new)
              {
                $quest_rewards[$quest_id] = $quest_list[$quest_id]['quest_rewards'];
                $quest_list[$quest_id]['quest_status_status'] = QUEST_STATUS_COMPLETE;
              }
            }
          }
    
        }
      }
    
      // TODO: Изменить согласно типу очереди
      rpg_level_up($user, RPG_TECH, $xp_incoming / 1000);
      // TODO: Изменить начисление награды за квесты на ту планету, на которой происходил ресеч
      qst_reward($user, $planet, $quest_rewards, $quest_list);
    
      db_changeset_apply($db_changeset);
    
      // Сообщения о постройке
      $user = db_user_by_id($user['id'], true);
      // TODO Так же пересчитывать планеты
    
      // sn_db_transaction_commit();
    
      // TODO поменять que_processed у планеты и юзера
    
    
      return $local_que;
    */
}
Exemple #6
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);
}
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'] ? "&nbsp;{$lang['sys_of_ally']}&nbsp;{$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'] ? "&nbsp;{$lang['sys_of_ally']}&nbsp;{$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']
}
Exemple #8
0
    }
    if (sys_get_param_str('reload')) {
        $combat_data = sn_ube_report_load($combat_data[UBE_REPORT_CYPHER]);
    }
    //debug($combat_data);
    // Рендерим их в темплейт
    sn_ube_report_generate($combat_data, $template_result);
    $template_result['MICROTIME'] = $combat_data[UBE_TIME_SPENT];
    $template = gettemplate('ube_combat_report', true);
    $template->assign_recursive($template_result);
    display($template, '', false, '', false, false, true);
} else {
    $template = gettemplate('simulator', true);
    $techs_and_officers = array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR, MRC_ADMIRAL);
    foreach ($techs_and_officers as $tech_id) {
        if (!$sym_attacker[1][$tech_id]) {
            $sym_attacker[1][$tech_id] = mrc_get_level($user, false, $tech_id);
        }
    }
    $show_groups = array(UNIT_TECHNOLOGIES => array(TECH_WEAPON, TECH_SHIELD, TECH_ARMOR), UNIT_MERCENARIES => array(MRC_ADMIRAL), UNIT_SHIPS => sn_get_groups('fleet'), UNIT_RESOURCES => sn_get_groups('resources_loot'), UNIT_GOVERNORS => array(MRC_FORTIFIER), UNIT_DEFENCE => sn_get_groups('defense_active'));
    foreach ($show_groups as $unit_group_id => $unit_group) {
        $template->assign_block_vars('simulator', array('GROUP' => $unit_group_id, 'NAME' => $lang['tech'][$unit_group_id]));
        foreach ($unit_group as $unit_id) {
            $tab++;
            $value = mrc_get_level($user, $planetrow, $unit_id);
            $template->assign_block_vars('simulator', array('NUM' => $tab < 9 ? "0{$tab}" : $tab, 'ID' => $unit_id, 'GROUP' => $unit_group_id, 'NAME' => $lang['tech'][$unit_id], 'ATTACKER' => intval($sym_attacker[1][$unit_id]), 'DEFENDER' => intval($sym_defender[0][$unit_id]), 'VALUE' => $value));
        }
    }
    $template->assign_vars(array('BE_DEBUG' => BE_DEBUG, 'UNIT_DEFENCE' => UNIT_DEFENCE, 'UNIT_GOVERNORS' => UNIT_GOVERNORS));
    display($template, $lang['coe_combatSimulator'], false);
}
Exemple #9
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;
}
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));
    }
}
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;
}
function flt_flying_fleet_handler($skip_fleet_update = false)
{
    /*
    [*] Нужно ли заворачивать ВСЕ в одну транзакцию?
          С одной стороны - да, что бы данные были гарантированно на момент снапшота
          С другой стороны - нет, потому что при большой активности это все будет блокировать слишком много рядов, да и таймаут будет большой для ожидания всего разлоченного
          Стоит завернуть каждую миссию отдельно? Это сильно увеличит количество запросов, зато так же сильно снизит количество блокировок.
        Resume: НЕТ! Надо оставить все в одной транзакции! Так можно будет поддерживать consistency кэша. Там буквально сантисекунды блокировки
    [*] Убрать кэшированние данных о пользователях и планета. Офигенно освободит память - проследить!
          НЕТ! Считать, скольким флотам нужна будет инфа и кэшировать только то, что используется больше раза!
          Заодно можно будет исключить перересчет очередей/ресурсов - сильно ускорит дело!
          Особенно будет актуально, когда все бонусы будут в одной таблице
          Ну и никто не заставляет как сейчас брать ВСЕ из таблицы - только по полям. Гемор, но не сильный - сделать запрос по группам sn_data
          И писать в БД только один раз результат
    [*] Нужно ли на этом этапе знать полную информацию о флотах?
          Заблокировать флоты можно и неполным запросом. Блокировка флотов - это не страшно. Ну, не пройдет одна-две отмены - так никто и не гарантировал реалтайма!
          С одной стороны - да, уменьшит количество запросов
          С другой стооны - расход памяти
          Все равно надо будет знать полную инфу о флоте в момент обработки
    [*] Сделать тестовую БД для расчетов
    [*] Но не раньше, чем переписать все миссии
    */
    global $config, $debug;
    if ($config->game_disable != GAME_DISABLE_NONE || $skip_fleet_update) {
        return;
    }
    sn_db_transaction_start();
    if ($config->db_loadItem('game_disable') != GAME_DISABLE_NONE || SN_TIME_NOW - strtotime($config->db_loadItem('fleet_update_last')) <= $config->fleet_update_interval) {
        sn_db_transaction_rollback();
        return;
    }
    // Watchdog timer
    if ($config->db_loadItem('fleet_update_lock')) {
        if (SN_TIME_NOW - strtotime($config->fleet_update_lock) <= mt_rand(240, 300)) {
            sn_db_transaction_rollback();
            return;
        } else {
            $debug->warning('Flying fleet handler was locked too long - watchdog unlocked', 'FFH Error', 504);
        }
    }
    $config->db_saveItem('fleet_update_lock', SN_TIME_SQL);
    $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
    sn_db_transaction_commit();
    //log_file('Начинаем обсчёт флотов');
    //log_file('Обсчёт ракет');
    sn_db_transaction_start();
    coe_o_missile_calculate();
    sn_db_transaction_commit();
    $fleet_list = array();
    $fleet_event_list = array();
    $missions_used = array();
    sn_db_transaction_start();
    //log_file('Запрос на флоты');
    $_fleets = doquery("SELECT * FROM `{{fleets}}` WHERE\n    (`fleet_start_time` <= " . SN_TIME_NOW . " AND `fleet_mess` = 0)\n    OR (`fleet_end_stay` <= " . SN_TIME_NOW . " AND fleet_end_stay > 0 AND `fleet_mess` = 0)\n    OR (`fleet_end_time` <= " . SN_TIME_NOW . ")\n  FOR UPDATE;");
    //log_file('Выборка флотов');
    while ($fleet_row = db_fetch($_fleets)) {
        set_time_limit(15);
        // Унифицировать код с темплейтным разбором эвентов на планете!
        $fleet_list[$fleet_row['fleet_id']] = $fleet_row;
        $missions_used[$fleet_row['fleet_mission']] = 1;
        if ($fleet_row['fleet_start_time'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_start_time'], 'fleet_event' => EVENT_FLT_ARRIVE);
        }
        if ($fleet_row['fleet_end_stay'] > 0 && $fleet_row['fleet_end_stay'] <= SN_TIME_NOW && $fleet_row['fleet_mess'] == 0) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_end_stay'], 'fleet_event' => EVENT_FLT_ACOMPLISH);
        }
        if ($fleet_row['fleet_end_time'] <= SN_TIME_NOW) {
            $fleet_event_list[] = array('fleet_row' => &$fleet_list[$fleet_row['fleet_id']], 'fleet_time' => $fleet_list[$fleet_row['fleet_id']]['fleet_end_time'], 'fleet_event' => EVENT_FLT_RETURN);
        }
    }
    sn_db_transaction_commit();
    //log_file('Сортировка и подгрузка модулей');
    uasort($fleet_event_list, 'flt_flyingFleetsSort');
    unset($_fleets);
    // TODO: Грузить только используемые модули из $missions_used
    $mission_files = array(MT_ATTACK => 'flt_mission_attack', MT_AKS => 'flt_mission_attack', MT_DESTROY => 'flt_mission_attack', MT_TRANSPORT => 'flt_mission_transport', MT_RELOCATE => 'flt_mission_relocate', MT_HOLD => 'flt_mission_hold', MT_SPY => 'flt_mission_spy', MT_COLONIZE => 'flt_mission_colonize', MT_RECYCLE => 'flt_mission_recycle', MT_EXPLORE => 'flt_mission_explore');
    foreach ($missions_used as $mission_id => $cork) {
        require_once SN_ROOT_PHYSICAL . "includes/includes/{$mission_files[$mission_id]}" . DOT_PHP_EX;
    }
    //log_file('Обработка миссий');
    $sn_groups_mission = sn_get_groups('missions');
    foreach ($fleet_event_list as $fleet_event) {
        // TODO: Указатель тут потом сделать
        // TODO: СЕЙЧАС НАДО ПРОВЕРЯТЬ ПО БАЗЕ - А ЖИВОЙ ЛИ ФЛОТ?!
        $fleet_row = $fleet_event['fleet_row'];
        if (!$fleet_row) {
            // Fleet was destroyed in course of previous actions
            continue;
        }
        //log_file('Миссия');
        // TODO Обернуть всё в транзакции. Начинать надо заранее, блокируя все таблицы внутренним локом SELECT 1 FROM {{users}}
        sn_db_transaction_start();
        $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
        $mission_data = $sn_groups_mission[$fleet_row['fleet_mission']];
        // Формируем запрос, блокирующий сразу все нужные записи
        db_flying_fleet_lock($mission_data, $fleet_row);
        $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE fleet_id = {$fleet_row['fleet_id']} FOR UPDATE", true);
        if (!$fleet_row || empty($fleet_row)) {
            // Fleet was destroyed in course of previous actions
            sn_db_transaction_commit();
            continue;
        }
        if ($fleet_event['fleet_event'] == EVENT_FLT_RETURN) {
            // Fleet returns to planet
            RestoreFleetToPlanet($fleet_row, true, false, true);
            sn_db_transaction_commit();
            continue;
        }
        if ($fleet_event['fleet_event'] == EVENT_FLT_ARRIVE && $fleet_row['fleet_mess'] != 0) {
            // При событии EVENT_FLT_ARRIVE флот всегда должен иметь fleet_mess == 0
            // В противном случае это означает, что флот уже был обработан ранее - например, при САБе
            sn_db_transaction_commit();
            continue;
        }
        // TODO: Здесь тоже указатели
        // TODO: Кэширование
        // TODO: Выбирать только нужные поля
        // шпионаж не дает нормальный ID fleet_end_planet_id 'dst_planet'
        $mission_data = array('fleet' => &$fleet_row, 'dst_user' => $mission_data['dst_user'] || $mission_data['dst_planet'] ? db_user_by_id($fleet_row['fleet_target_owner'], true) : null, 'dst_planet' => $mission_data['dst_planet'] ? db_planet_by_vector($fleet_row, 'fleet_end_', true, '`id`, `id_owner`, `name`') : null, 'src_user' => $mission_data['src_user'] || $mission_data['src_planet'] ? db_user_by_id($fleet_row['fleet_owner'], true) : null, 'src_planet' => $mission_data['src_planet'] ? db_planet_by_vector($fleet_row, 'fleet_start_', true, '`id`, `id_owner`, `name`') : null, 'fleet_event' => $fleet_event['fleet_event']);
        if ($mission_data['dst_planet']) {
            // $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_user'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
            if ($mission_data['dst_planet']['id_owner']) {
                $mission_data['dst_planet'] = sys_o_get_updated($mission_data['dst_planet']['id_owner'], $mission_data['dst_planet']['id'], $fleet_row['fleet_start_time']);
            }
            $mission_data['dst_user'] = $mission_data['dst_user'] ? $mission_data['dst_planet']['user'] : null;
            $mission_data['dst_planet'] = $mission_data['dst_planet']['planet'];
        }
        switch ($fleet_row['fleet_mission']) {
            // Для боевых атак нужно обновлять по САБу и по холду - таки надо возвращать данные из обработчика миссий!
            case MT_AKS:
            case MT_ATTACK:
            case MT_DESTROY:
                $attack_result = flt_mission_attack($mission_data);
                $mission_result = CACHE_COMBAT;
                break;
                /*
                case MT_DESTROY:
                  $attack_result = flt_mission_destroy($mission_data);
                  $mission_result = CACHE_COMBAT;
                break;
                */
            /*
            case MT_DESTROY:
              $attack_result = flt_mission_destroy($mission_data);
              $mission_result = CACHE_COMBAT;
            break;
            */
            case MT_TRANSPORT:
                $mission_result = flt_mission_transport($mission_data);
                break;
            case MT_HOLD:
                $mission_result = flt_mission_hold($mission_data);
                break;
            case MT_RELOCATE:
                $mission_result = flt_mission_relocate($mission_data);
                break;
            case MT_EXPLORE:
                $mission_result = flt_mission_explore($mission_data);
                break;
            case MT_RECYCLE:
                $mission_result = flt_mission_recycle($mission_data);
                break;
            case MT_COLONIZE:
                $mission_result = flt_mission_colonize($mission_data);
                break;
            case MT_SPY:
                $mission_result = flt_mission_spy($mission_data);
                break;
            case MT_MISSILE:
                // Missiles !!
                break;
                //      default:
                //        doquery("DELETE FROM `{{fleets}}` WHERE `fleet_id` = '{$fleet_row['fleet_id']}' LIMIT 1;");
                //      break;
        }
        sn_db_transaction_commit();
    }
    sn_db_transaction_start();
    $config->db_saveItem('fleet_update_last', SN_TIME_SQL);
    $config->db_saveItem('fleet_update_lock', '');
    sn_db_transaction_commit();
    //  log_file('Закончили обсчёт флотов');
}
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]);
}
Exemple #14
0
$planetrow = db_planet_by_id($user['current_planet'], true);
$target_planet_type = sys_get_param_int('planet_type');
$target_planet_check = $target_planet_type == PT_DEBRIS ? PT_PLANET : $target_planet_type;
$target_coord['planet_type'] = $target_planet_check;
$target_row = db_planet_by_vector($target_coord);
if (empty($target_row)) {
    $target_row = array('galaxy' => $target_coord['galaxy'], 'system' => $target_coord['system'], 'planet' => $target_coord['planet'], 'planet_type' => $target_planet_check, 'id_owner' => 0);
}
$fleet_array = array();
switch ($target_mission) {
    case MT_SPY:
        $fleet_array[SHIP_SPY] = min(mrc_get_level($user, $planetrow, SHIP_SPY), abs($user['spio_anz']));
        $unit_group = 'flt_spies';
        break;
    case MT_RECYCLE:
        foreach (sn_get_groups('flt_recyclers') as $unit_id) {
            if ($unit_count = mrc_get_level($user, $planetrow, $unit_id)) {
                $fleet_array[$unit_id] = $unit_count;
            }
        }
        $transport_data = flt_calculate_fleet_to_transport($fleet_array, $target_row['debris_metal'] + $target_row['debris_crystal'], $planetrow, $target_row);
        $fleet_array = $transport_data['fleet'];
        $unit_group = 'flt_recyclers';
        break;
    case MT_MISSILE:
        $fleet_array[UNIT_DEF_MISSILE_INTERPLANET] = min(mrc_get_level($user, $planetrow, UNIT_DEF_MISSILE_INTERPLANET), abs(sys_get_param_float('missiles')));
        $unit_group = 'missile';
        break;
}
$options = array('target_structure' => $target_structure = sys_get_param_int('structures'));
$cant_attack = flt_can_attack($planetrow, $target_row, $fleet_array, $target_mission, $options);
Exemple #15
0
function qst_reward(&$user, &$rewards, &$quest_list)
{
    if (empty($rewards)) {
        return;
    }
    global $lang;
    $db_changeset = array();
    $total_rewards = array();
    $comment_dm = '';
    foreach ($rewards as $quest_id => $user_data) {
        foreach ($user_data as $user_id => $planet_data) {
            foreach ($planet_data as $planet_id => $reward_list) {
                $comment = sprintf($lang['qst_msg_complete_body'], $quest_list[$quest_id]['quest_name']);
                $comment_dm .= isset($reward_list[RES_DARK_MATTER]) ? $comment : '';
                $comment_reward = array();
                foreach ($reward_list as $unit_id => $unit_amount) {
                    $comment_reward[] = $unit_amount . ' ' . $lang['tech'][$unit_id];
                    $total_rewards[$user_id][$planet_id][$unit_id] += $unit_amount;
                }
                $comment .= " {$lang['qst_msg_your_reward']} " . implode(',', $comment_reward);
                msg_send_simple_message($user['id'], 0, SN_TIME_NOW, MSG_TYPE_ADMIN, $lang['msg_from_admin'], $lang['qst_msg_complete_subject'], $comment);
                sn_db_perform('{{quest_status}}', array('quest_status_quest_id' => $quest_id, 'quest_status_user_id' => $user_id, 'quest_status_status' => QUEST_STATUS_COMPLETE));
            }
        }
    }
    $group_resources = sn_get_groups('resources_loot');
    $quest_rewards_allowed = sn_get_groups('quest_rewards');
    if (!empty($total_rewards)) {
        foreach ($total_rewards as $user_id => $planet_data) {
            $user_row = classSupernova::db_get_record_by_id(LOC_USER, $user_id);
            foreach ($planet_data as $planet_id => $unit_data) {
                $local_changeset = array();
                foreach ($unit_data as $unit_id => $unit_amount) {
                    if (!isset($quest_rewards_allowed[$unit_id])) {
                        continue;
                    }
                    if ($unit_id == RES_DARK_MATTER) {
                        rpg_points_change($user['id'], RPG_QUEST, $unit_amount, $comment_dm);
                    } elseif (isset($group_resources[$unit_id])) {
                        $local_changeset[pname_resource_name($unit_id)] = array('delta' => $unit_amount);
                    } else {
                        $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_amount, $user_row, $planet_id);
                    }
                    // unit
                }
                if (!empty($local_changeset)) {
                    $planet_id = $planet_id == 0 && isset($user_row['id_planet']) ? $user_row['id_planet'] : $planet_id;
                    $db_changeset[$planet_id ? 'planets' : 'users'][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array("id" => $planet_id ? $planet_id : $user_id), 'fields' => $local_changeset);
                }
            }
        }
        classSupernova::db_changeset_apply($db_changeset);
    }
}
function sn_ube_combat_result_apply(&$combat_data)
{
    // TODO: Поменять все отладки на запросы
    $destination_user_id = $combat_data[UBE_FLEETS][0][UBE_OWNER];
    $outcome =& $combat_data[UBE_OUTCOME];
    $planet_info =& $outcome[UBE_PLANET];
    $planet_id = $planet_info[PLANET_ID];
    // Обновляем поле обломков на планете
    if (!$combat_data[UBE_OPTIONS][UBE_COMBAT_ADMIN] && !empty($outcome[UBE_DEBRIS])) {
        db_planet_set_by_gspt($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], PT_PLANET, "`debris_metal` = `debris_metal` + " . floor($outcome[UBE_DEBRIS][RES_METAL]) . ", `debris_crystal` = `debris_crystal` + " . floor($outcome[UBE_DEBRIS][RES_CRYSTAL]));
    }
    $db_save = array(UBE_FLEET_GROUP => array());
    $fleets_outcome =& $outcome[UBE_FLEETS];
    foreach ($combat_data[UBE_FLEETS] as $fleet_id => &$fleet_info) {
        if ($fleet_info[UBE_FLEET_GROUP]) {
            $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
        }
        $fleet_info[UBE_COUNT] = $fleet_info[UBE_COUNT] ? $fleet_info[UBE_COUNT] : array();
        $fleets_outcome[$fleet_id][UBE_UNITS_LOST] = $fleets_outcome[$fleet_id][UBE_UNITS_LOST] ? $fleets_outcome[$fleet_id][UBE_UNITS_LOST] : array();
        $fleet_query = array();
        $db_changeset = array();
        $old_fleet_count = array_sum($fleet_info[UBE_COUNT]);
        $new_fleet_count = $old_fleet_count - array_sum($fleets_outcome[$fleet_id][UBE_UNITS_LOST]);
        // Перебираем юниты если во время боя количество юнитов изменилось и при этом во флоту остались юниты или это планета
        if ($new_fleet_count != $old_fleet_count && (!$fleet_id || $new_fleet_count)) {
            // Просматриваем результаты изменения флотов
            foreach ($fleet_info[UBE_COUNT] as $unit_id => $unit_count) {
                // Перебираем аутком на случай восстановления юнитов
                $units_lost = (double) $fleets_outcome[$fleet_id][UBE_UNITS_LOST][$unit_id];
                $units_left = $unit_count - $units_lost;
                if ($fleet_id) {
                    // Не планета - всегда сразу записываем строку итогов флота
                    $fleet_query[$unit_id] = "{$unit_id},{$units_left}";
                } elseif ($units_lost) {
                    // Планета - записываем в ИД юнита его потери только если есть потери
                    // $unit_db_name = get_unit_param($unit_id, P_NAME);
                    // $fleet_query[$unit_id] = "`{$unit_db_name}` = `{$unit_db_name}` - {$units_lost}";
                    // pdump($fleet_info);
                    // die();
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$units_lost, $combat_data[UBE_PLAYERS][$destination_user_id][UBE_PLAYER_DATA], $planet_id);
                }
            }
            if ($fleet_id) {
                // Для флотов перегенерируем массив как одно вхождение в SET SQL-запроса
                $fleet_query = implode(';', $fleet_query);
                $fleet_query = array("`fleet_array` = '{$fleet_query}'");
            }
        }
        // Если во флоте остались юниты или это планета - генерируем изменение ресурсов
        if ($new_fleet_count || !$fleet_id) {
            foreach (sn_get_groups('resources_loot') as $resource_id) {
                $resource_change = (double) $fleets_outcome[$fleet_id][UBE_RESOURCES_LOOTED][$resource_id] + (double) $fleets_outcome[$fleet_id][UBE_CARGO_DROPPED][$resource_id];
                if ($resource_change) {
                    $resource_db_name = ($fleet_id ? 'fleet_resource_' : '') . pname_resource_name($resource_id);
                    $fleet_query[] = "`{$resource_db_name}` = `{$resource_db_name}` - ({$resource_change})";
                }
            }
        }
        /*
            if(empty($fleet_query))
            {
              continue;
            }
        */
        if ($fleet_id && $new_fleet_count) {
            // Если защитник и не РМФ - отправляем флот назад
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_DEFENDERS && !$outcome[UBE_SFR] || $fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS) {
                $fleet_query[] = '`fleet_mess` = 1';
            }
            // Если флот в группе - помечаем нулем
            //      if($fleet_info[UBE_FLEET_GROUP])
            //      {
            //        $fleet_query[] = '`fleet_group` = 0';
            //      }
        }
        //global $debug;
        $fleet_query = implode(',', $fleet_query);
        if ($fleet_id) {
            if ($fleet_info[UBE_FLEET_TYPE] == UBE_ATTACKERS && $outcome[UBE_MOON_REAPERS] == UBE_MOON_REAPERS_DIED) {
                $new_fleet_count = 0;
            }
            if ($new_fleet_count) {
                if ($fleet_query) {
                    doquery("UPDATE {{fleets}} SET {$fleet_query}, `fleet_amount` = '{$new_fleet_count}' WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                }
            } else {
                // Удаляем пустые флоты
                doquery("DELETE FROM {{fleets}} WHERE `fleet_id` = {$fleet_id} LIMIT 1");
                db_unit_list_delete(0, LOC_FLEET, $fleet_id, 0);
            }
        } else {
            // Сохраняем изменения ресурсов - если они есть
            if ($fleet_query) {
                db_planet_set_by_id($planet_id, $fleet_query);
            }
            if (!empty($db_changeset)) {
                db_changeset_apply($db_changeset);
            }
        }
    }
    // TODO: Связать сабы с флотами констраинтами ON DELETE SET NULL
    // $db_save[UBE_FLEET_GROUP][$fleet_info[UBE_FLEET_GROUP]] = $fleet_info[UBE_FLEET_GROUP];
    if (!empty($db_save[UBE_FLEET_GROUP])) {
        $db_save[UBE_FLEET_GROUP] = implode(',', $db_save[UBE_FLEET_GROUP]);
        doquery("DELETE FROM {{aks}} WHERE `id` IN ({$db_save[UBE_FLEET_GROUP]})");
    }
    if ($outcome[UBE_MOON] == UBE_MOON_CREATE_SUCCESS) {
        $moon_row = uni_create_moon($planet_info[PLANET_GALAXY], $planet_info[PLANET_SYSTEM], $planet_info[PLANET_PLANET], $destination_user_id, $outcome[UBE_MOON_SIZE], '', false);
        $outcome[UBE_MOON_NAME] = $moon_row['name'];
        unset($moon_row);
    } elseif ($outcome[UBE_MOON] == UBE_MOON_DESTROY_SUCCESS) {
        db_planet_delete_by_id($planet_id);
    }
    $bashing_list = array();
    foreach ($combat_data[UBE_PLAYERS] as $player_id => $player_info) {
        if ($player_info[UBE_ATTACKER]) {
            if ($outcome[UBE_MOON] != UBE_MOON_DESTROY_SUCCESS) {
                $bashing_list[] = "({$player_id}, {$planet_id}, {$combat_data[UBE_TIME]})";
            }
            if ($combat_data[UBE_OPTIONS][UBE_MISSION_TYPE] == MT_ATTACK && $combat_data[UBE_OPTIONS][UBE_DEFENDER_ACTIVE]) {
                $str_loose_or_win = $outcome[UBE_COMBAT_RESULT] == UBE_COMBAT_RESULT_WIN ? 'raidswin' : 'raidsloose';
                db_user_set_by_id($player_id, "`xpraid` = `xpraid` + 1, `raids` = `raids` + 1, `{$str_loose_or_win}` = `{$str_loose_or_win}` + 1");
            }
        }
    }
    $bashing_list = implode(',', $bashing_list);
    if ($bashing_list) {
        doquery("INSERT INTO {{bashing}} (bashing_user_id, bashing_planet_id, bashing_time) VALUES {$bashing_list};");
    }
}
Exemple #17
0
 }
 upd_alter_table('fleets', array('MODIFY COLUMN `fleet_owner` BIGINT(20) UNSIGNED DEFAULT NULL', "ADD CONSTRAINT `FK_fleet_owner` FOREIGN KEY (`fleet_owner`) REFERENCES `{$config->db_prefix}users` (`id`) ON DELETE CASCADE ON UPDATE CASCADE"), strtoupper($update_tables['fleets']['fleet_owner']['Type']) != 'BIGINT(20) UNSIGNED');
 upd_check_key('chat_highlight_developer', '<span class="nick_developer">$1</span>', !$config->chat_highlight_developer);
 if (!$update_tables['player_name_history']) {
     upd_check_key('game_user_changename_cost', 100000, !$config->game_user_changename_cost);
     upd_check_key('game_user_changename', SERVER_PLAYER_NAME_CHANGE_PAY, $config->game_user_changename != SERVER_PLAYER_NAME_CHANGE_PAY);
     upd_alter_table('users', array("CHANGE COLUMN `username` `username` VARCHAR(32) NOT NULL DEFAULT '' COMMENT 'Player name'"));
     upd_create_table('player_name_history', "(\n          `player_id` BIGINT(20) UNSIGNED NULL DEFAULT NULL COMMENT 'Player ID',\n          `player_name` VARCHAR(32) NOT NULL COMMENT 'Historical player name',\n          `timestamp` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT 'When player changed name',\n\n          PRIMARY KEY (`player_name`),\n          KEY `I_player_name_history_id_name` (`player_id`, `player_name`),\n\n          CONSTRAINT `FK_player_name_history_id` FOREIGN KEY (`player_id`) REFERENCES `{$config->db_prefix}users` (`id`) ON UPDATE CASCADE ON DELETE CASCADE\n        ) ENGINE=InnoDB DEFAULT CHARSET=utf8;");
     upd_do_query("REPLACE INTO {{player_name_history}} (`player_id`, `player_name`) SELECT `id`, `username` FROM {{users}} WHERE `user_as_ally` IS NULL;");
 }
 upd_alter_table('planets', array("ADD `density` SMALLINT NOT NULL DEFAULT 5500 COMMENT 'Planet average density kg/m3'", "ADD `density_index` TINYINT NOT NULL DEFAULT " . PLANET_DENSITY_STANDARD . " COMMENT 'Planet cached density index'"), !$update_tables['planets']['density_index']);
 if ($update_tables['users']['player_artifact_list']) {
     upd_alter_table('unit', "DROP KEY `unit_id`", $update_indexes['unit']['unit_id']);
     upd_alter_table('unit', "ADD KEY `I_unit_player_location_snid` (`unit_player_id`, `unit_location_type`, `unit_location_id`, `unit_snid`)", !$update_indexes['unit']['I_unit_player_location_snid']);
     upd_alter_table('unit', "DROP KEY `I_unit_player_id_temporary`", $update_indexes['unit']['I_unit_player_id_temporary']);
     $sn_data_artifacts = sn_get_groups('artifacts');
     $db_changeset = array();
     $query = upd_do_query("SELECT `id`, `player_artifact_list` FROM {{users}} WHERE `player_artifact_list` IS NOT NULL AND `player_artifact_list` != '' FOR UPDATE");
     while ($row = db_fetch($query)) {
         $artifact_list = explode(';', $row['player_artifact_list']);
         if (!$row['player_artifact_list'] || empty($artifact_list)) {
             continue;
         }
         foreach ($artifact_list as $key => &$value) {
             $value = explode(',', $value);
             if (!isset($value[1]) || $value[1] <= 0 || !isset($sn_data_artifacts[$value[0]])) {
                 unset($artifact_list[$key]);
                 continue;
             }
             $db_changeset['unit'][] = upd_db_unit_changeset_prepare($value[0], $value[1], $row);
         }
Exemple #18
0
function sn_sys_planet_core_transmute(&$user, &$planetrow)
{
    if (!sys_get_param_str('transmute')) {
        return array();
    }
    global $lang;
    try {
        if ($planetrow['planet_type'] != PT_PLANET) {
            throw new exception($lang['ov_core_err_not_a_planet'], ERR_ERROR);
        }
        if ($planetrow['density_index'] == ($new_density_index = sys_get_param_id('density_type'))) {
            throw new exception($lang['ov_core_err_same_density'], ERR_WARNING);
        }
        sn_db_transaction_start();
        $user = db_user_by_id($user['id'], true, '*');
        $planetrow = db_planet_by_id($planetrow['id'], true, '*');
        //    $global_data = sys_o_get_updated($user, $planetrow['id'], SN_TIME_NOW);
        //    $user = $global_data['user'];
        //    $planetrow = $global_data['planet'];
        $planet_density_index = $planetrow['density_index'];
        $density_price_chart = planet_density_price_chart($planet_density_index);
        if (!isset($density_price_chart[$new_density_index])) {
            // Hack attempt
            throw new exception($lang['ov_core_err_denisty_type_wrong'], ERR_ERROR);
        }
        $user_dark_matter = mrc_get_level($user, false, RES_DARK_MATTER);
        $transmute_cost = get_unit_param(UNIT_PLANET_DENSITY, 'cost');
        $transmute_cost = $transmute_cost[RES_DARK_MATTER] * $density_price_chart[$new_density_index];
        if ($user_dark_matter < $transmute_cost) {
            throw new exception($lang['ov_core_err_no_dark_matter'], ERR_ERROR);
        }
        $sn_data_planet_density = sn_get_groups('planet_density');
        foreach ($sn_data_planet_density as $key => $value) {
            if ($key == $new_density_index) {
                break;
            }
            $prev_density_index = $key;
        }
        $new_density = round(($sn_data_planet_density[$new_density_index][UNIT_PLANET_DENSITY] + $sn_data_planet_density[$prev_density_index][UNIT_PLANET_DENSITY]) / 2);
        rpg_points_change($user['id'], RPG_PLANET_DENSITY_CHANGE, -$transmute_cost, array('Planet %1$s ID %2$d at coordinates %3$s changed density type from %4$d "%5$s" to %6$d "%7$s". New density is %8$d kg/m3', $planetrow['name'], $planetrow['id'], uni_render_coordinates($planetrow), $planet_density_index, $lang['uni_planet_density_types'][$planet_density_index], $new_density_index, $lang['uni_planet_density_types'][$new_density_index], $new_density));
        db_planet_set_by_id($planetrow['id'], "`density` = {$new_density}, `density_index` = {$new_density_index}");
        sn_db_transaction_commit();
        $planetrow['density'] = $new_density;
        $planetrow['density_index'] = $new_density_index;
        $result = array('STATUS' => ERR_NONE, 'MESSAGE' => sprintf($lang['ov_core_err_none'], $lang['uni_planet_density_types'][$planet_density_index], $lang['uni_planet_density_types'][$new_density_index], $new_density));
    } catch (exception $e) {
        sn_db_transaction_rollback();
        $result = array('STATUS' => $e->getCode(), 'MESSAGE' => $e->getMessage());
    }
    return $result;
}
/**
 * Copyright (c) 2009-2010 by Gorlum for http://supernova.ws
 *       OpenSource as long as you don't remove this Copyright
 * V3 2009-11-13
 * V2 2009-10-10
 */
function coe_o_missile_calculate()
{
    sn_db_transaction_check(true);
    global $lang;
    $iraks = doquery("SELECT * FROM {{iraks}} WHERE `fleet_end_time` <= " . SN_TIME_NOW . " FOR UPDATE;");
    while ($fleetRow = db_fetch($iraks)) {
        set_time_limit(15);
        $db_changeset = array();
        $targetUser = db_user_by_id($fleetRow['fleet_target_owner'], true);
        $target_planet_row = sys_o_get_updated($targetUser, array('galaxy' => $fleetRow['fleet_end_galaxy'], 'system' => $fleetRow['fleet_end_system'], 'planet' => $fleetRow['fleet_end_planet'], 'planet_type' => PT_PLANET), SN_TIME_NOW);
        $target_planet_row = $target_planet_row['planet'];
        $rowAttacker = db_user_by_id($fleetRow['fleet_owner'], true);
        if ($target_planet_row['id']) {
            $planetDefense = array();
            foreach (sn_get_groups('defense_active') as $unit_id) {
                $planetDefense[$unit_id] = array(mrc_get_level($targetUser, $target_planet_row, $unit_id, true, true));
            }
            $message = '';
            $interceptors = mrc_get_level($targetUser, $target_planet_row, UNIT_DEF_MISSILE_INTERCEPTOR, true, true);
            //$target_planet_row[$interceptor_db_name]; // Number of interceptors
            $missiles = $fleetRow['fleet_amount'];
            // Number of MIP
            if ($interceptors >= $missiles) {
                $message = $lang['mip_all_destroyed'];
                $db_changeset['unit'][] = sn_db_unit_changeset_prepare(UNIT_DEF_MISSILE_INTERCEPTOR, -$missiles, $targetUser, $target_planet_row['id']);
            } else {
                if ($interceptors) {
                    $message = sprintf($lang['mip_destroyed'], $interceptors);
                    $db_changeset['unit'][] = sn_db_unit_changeset_prepare(UNIT_DEF_MISSILE_INTERCEPTOR, -$interceptors, $targetUser, $target_planet_row['id']);
                }
                //        $message .= $lang['mip_defense_destroyed'];
                $attackResult = COE_missileAttack($targetUser, $rowAttacker, $missiles - $interceptors, $planetDefense, $fleetRow['primaer']);
                foreach ($attackResult['structures'] as $key => $structure) {
                    $destroyed = $planetDefense[$key][0] - $structure[0];
                    if ($destroyed) {
                        $db_changeset['unit'][] = sn_db_unit_changeset_prepare($key, -$destroyed, $targetUser, $target_planet_row['id']);
                        $message .= "&nbsp;&nbsp;{$lang['tech'][$key]} - {$destroyed} {$lang['quantity']}<br>";
                    }
                }
                if (!empty($message)) {
                    $message = $lang['mip_defense_destroyed'] . $message . "{$lang['mip_recycled']}{$lang['Metal']}: {$attackResult['metal']}, {$lang['Crystal']}: {$attackResult['crystal']}<br>";
                    db_planet_set_by_id($target_planet_row['id'], "`metal` = `metal` + {$attackResult['metal']}, `crystal` = `crystal` + {$attackResult['crystal']}");
                }
                //        $message .= "{$lang['mip_recycled']}{$lang['Metal']}: {$attackResult['metal']}, {$lang['Crystal']}: {$attackResult['crystal']}<br>";
            }
            db_changeset_apply($db_changeset);
            $fleetRow['fleet_start_type'] = PT_PLANET;
            $sourcePlanet = db_planet_by_vector($fleetRow, 'fleet_start_', false, 'name');
            $message_vorlage = sprintf($lang['mip_body_attack'], $fleetRow['fleet_amount'], addslashes($sourcePlanet['name']), $fleetRow['fleet_start_galaxy'], $fleetRow['fleet_start_system'], $fleetRow['fleet_start_planet'], addslashes($target_planet_row['name']), $fleetRow['fleet_end_galaxy'], $fleetRow['fleet_end_system'], $fleetRow['fleet_end_planet']);
            empty($message) ? $message = $lang['mip_no_defense'] : false;
            // empty($message) && ($message = $lang['mip_no_defense']);
            msg_send_simple_message($fleetRow['fleet_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
            msg_send_simple_message($fleetRow['fleet_target_owner'], '', SN_TIME_NOW, MSG_TYPE_SPY, $lang['mip_sender_amd'], $lang['mip_subject_amd'], $message_vorlage . $message);
        }
        doquery("DELETE FROM {{iraks}} WHERE id = '{$fleetRow['id']}';");
    }
}
Exemple #20
0
function stat_tpl_assign(&$template, $selected, $array_name, $array, $sn_group_stat_common)
{
    global $who, $lang;
    // $sn_group_stat_common = sn_get_groups('STAT_COMMON');
    foreach ($array as $key => $value) {
        if ($array_name == 'type' && $who == 2 && !in_array($key, $sn_group_stat_common)) {
            continue;
        }
        $header = isset($value['header']) ? $value['header'] : $lang['stat_type'][$key];
        $template->assign_block_vars($array_name, array('ID' => $key, 'HEADER' => $header, 'SELECTED' => $key == $selected));
    }
}
$allow_anonymous = true;
include 'common.' . substr(strrchr(__FILE__, '.'), 1);
lng_include('stat');
$sn_group_stat_common = sn_get_groups('STAT_COMMON');
$who = sys_get_param_int('who', 1);
$type = sys_get_param_int('type');
$type = $who != 1 && !in_array($type, $sn_group_stat_common) ? 1 : $type;
$range = sys_get_param_int('range', 1);
$source = sys_get_param_str('source');
$template = gettemplate('stat_statistics', true);
$subject_list = array(1 => array('header' => $lang['stat_player']));
if (!$source) {
    $subject_list[2] = array('header' => $lang['stat_allys']);
}
stat_tpl_assign($template, $who, 'subject', $subject_list, $sn_group_stat_common);
$stat_types = array(STAT_TOTAL => array('type' => 'total'), STAT_FLEET => array('type' => 'fleet'), STAT_TECH => array('type' => 'tech'), STAT_BUILDING => array('type' => 'build'), STAT_DEFENSE => array('type' => 'defs'), STAT_RESOURCE => array('type' => 'res'), STAT_RAID_TOTAL => array('type' => 'raids'), STAT_RAID_WON => array('type' => 'raidswin'), STAT_RAID_LOST => array('type' => 'raidsloose'), STAT_LVL_BUILDING => array('type' => 'lvl_minier'), STAT_LVL_TECH => array('type' => 'player_rpg_tech_level'), STAT_LVL_RAID => array('type' => 'lvl_raid'));
stat_tpl_assign($template, $type, 'type', $stat_types, $sn_group_stat_common);
$Rank = $stat_types[$type]['type'];
$is_common_stat = in_array($type, $sn_group_stat_common);
Exemple #21
0
include 'common.' . substr(strrchr(__FILE__, '.'), 1);
function int_calc_storage_bar($resource_id)
{
    global $lang, $template, $caps_real, $planetrow, $user;
    $totalProduction = $caps_real['total'][$resource_id];
    $storage_fill = $caps_real['total_storage'][$resource_id] ? floor(mrc_get_level($user, $planetrow, $resource_id) / $caps_real['total_storage'][$resource_id] * 100) : 0;
    $template->assign_block_vars('resources', array('NAME' => $lang["sys_" . pname_resource_name($resource_id)], 'HOURLY' => pretty_number($totalProduction, true, true), 'WEEKLY' => pretty_number($totalProduction * 24 * 7, true, true), 'DAILY' => pretty_number($totalProduction * 24, true, true), 'MONTHLY' => pretty_number($totalProduction * 24 * 30, true, true), 'STORAGE' => intval($storage_fill), 'BAR' => min($storage_fill, 100)));
}
$ValidList['percent'] = array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100);
$template = gettemplate('resources', true);
$transmutation_result = sn_sys_planet_core_transmute($user, $planetrow);
if (!empty($transmutation_result)) {
    $template->assign_block_vars('result', $transmutation_result);
    // array('STATUS' => $transmutation_result['STATUS'], 'MESSAGE' => $transmutation_result['MESSAGE']));
}
$sn_group_factories = sn_get_groups('factories');
$production = $_POST['production'];
//$SubQry     = '';
$SubQry = array();
if (is_array($production)) {
    foreach ($production as $prod_id => $percent) {
        if ($percent > 100 || $percent < 0) {
            $debug->warning('Supplying wrong production percent (less then 0 or greater then 100)', 'Hack attempt', 302, array('base_dump' => true));
            die;
        }
        $prod_id = intval($prod_id);
        if (in_array($prod_id, $sn_group_factories) && get_unit_param($prod_id, P_MINING_IS_MANAGED)) {
            $field_name = pname_factory_production_field_name($prod_id);
            $percent = floor($percent / 10);
            $planetrow[$field_name] = $percent;
            //$SubQry                 .= "`{$field_name}` = '{$percent}',";
/**
 * 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;
}
function sn_eco_unit_busy(&$user, &$planet, $unit_id, &$result)
{
    global $config;
    $result = isset($result) ? $result : false;
    if (!$result) {
        if (($unit_id == STRUC_LABORATORY || $unit_id == STRUC_LABORATORY_NANO) && !$config->BuildLabWhileRun) {
            $global_que = que_get($user['id'], $planet['id'], QUE_RESEARCH, false);
            if (is_array($global_que['ques'][QUE_RESEARCH][$user['id']])) {
                $first_element = reset($global_que['ques'][QUE_RESEARCH][$user['id']]);
                if (is_array($first_element)) {
                    $result = true;
                }
            }
            //if(!empty($global_que['ques'][QUE_RESEARCH][$user['id']][0]))
            //{
            //  $result = true;
            //}
        } elseif (($unit_id == UNIT_TECHNOLOGIES || in_array($unit_id, sn_get_groups('tech'))) && !$config->BuildLabWhileRun && $planet['que']) {
            $result = eco_is_builds_in_que($planet['que'], array(STRUC_LABORATORY, STRUC_LABORATORY_NANO));
        }
    }
    //  switch($unit_id)
    //  {
    //    case STRUC_FACTORY_HANGAR:
    //      $hangar_busy = $planet['b_hangar'] && $planet['b_hangar_id'];
    //      $return = $hangar_busy;
    //    break;
    //  }
    return $result;
}
Exemple #24
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;
}
Exemple #25
0
 upd_log_version_update();
 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));
function flt_t_send_fleet($user, &$from, $to, $fleet, $mission, $options = array())
{
    //ini_set('error_reporting', E_ALL);
    $internal_transaction = !sn_db_transaction_check(false) ? sn_db_transaction_start() : false;
    //pdump($internal_transaction);
    // TODO Потенциальный дедлок - если успела залочится запись пользователя - хозяина планеты
    $user = db_user_by_id($user['id'], true);
    $from = sys_o_get_updated($user, $from['id'], SN_TIME_NOW);
    $from = $from['planet'];
    $can_attack = flt_can_attack($from, $to, $fleet, $mission, $options);
    if ($can_attack != ATTACK_ALLOWED) {
        $internal_transaction ? sn_db_transaction_rollback() : false;
        return $can_attack;
    }
    $fleet_group = isset($options['fleet_group']) ? floatval($options['fleet_group']) : 0;
    $travel_data = flt_travel_data($user, $from, $to, $fleet, $options['fleet_speed_percent']);
    $fleet_start_time = SN_TIME_NOW + $travel_data['duration'];
    if ($mission == MT_EXPLORE || $mission == MT_HOLD) {
        $stay_duration = $options['stay_time'] * 3600;
        $stay_time = $fleet_start_time + $stay_duration;
    } else {
        $stay_duration = 0;
        $stay_time = 0;
    }
    $fleet_end_time = $fleet_start_time + $travel_data['duration'] + $stay_duration;
    $fleet_ship_count = 0;
    $fleet_string = '';
    $db_changeset = array();
    $planet_fields = array();
    foreach ($fleet as $unit_id => $amount) {
        if (!$amount || !$unit_id) {
            continue;
        }
        if (in_array($unit_id, sn_get_groups('fleet'))) {
            $fleet_ship_count += $amount;
            $fleet_string .= "{$unit_id},{$amount};";
            $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$amount, $user, $from['id']);
        } elseif (in_array($unit_id, sn_get_groups('resources_loot'))) {
            $planet_fields[pname_resource_name($unit_id)]['delta'] -= $amount;
        }
    }
    $to['id_owner'] = intval($to['id_owner']);
    $QryInsertFleet = "INSERT INTO {{fleets}} SET ";
    $QryInsertFleet .= "`fleet_owner` = '{$user['id']}', ";
    $QryInsertFleet .= "`fleet_mission` = '{$mission}', ";
    $QryInsertFleet .= "`fleet_amount` = '{$fleet_ship_count}', ";
    $QryInsertFleet .= "`fleet_array` = '{$fleet_string}', ";
    $QryInsertFleet .= "`fleet_start_time` = '{$fleet_start_time}', ";
    if ($from['id']) {
        $QryInsertFleet .= "`fleet_start_planet_id` = '{$from['id']}', ";
    }
    $QryInsertFleet .= "`fleet_start_galaxy` = '{$from['galaxy']}', ";
    $QryInsertFleet .= "`fleet_start_system` = '{$from['system']}', ";
    $QryInsertFleet .= "`fleet_start_planet` = '{$from['planet']}', ";
    $QryInsertFleet .= "`fleet_start_type` = '{$from['planet_type']}', ";
    $QryInsertFleet .= "`fleet_end_time` = '{$fleet_end_time}', ";
    $QryInsertFleet .= "`fleet_end_stay` = '{$stay_time}', ";
    if ($to['id']) {
        $QryInsertFleet .= "`fleet_end_planet_id` = '{$to['id']}', ";
    }
    $QryInsertFleet .= "`fleet_end_galaxy` = '{$to['galaxy']}', ";
    $QryInsertFleet .= "`fleet_end_system` = '{$to['system']}', ";
    $QryInsertFleet .= "`fleet_end_planet` = '{$to['planet']}', ";
    $QryInsertFleet .= "`fleet_end_type` = '{$to['planet_type']}', ";
    $QryInsertFleet .= "`fleet_resource_metal` = " . floatval($fleet[RES_METAL]) . ", ";
    $QryInsertFleet .= "`fleet_resource_crystal` = " . floatval($fleet[RES_CRYSTAL]) . ", ";
    $QryInsertFleet .= "`fleet_resource_deuterium` = " . floatval($fleet[RES_DEUTERIUM]) . ", ";
    $QryInsertFleet .= "`fleet_target_owner` = '{$to['id_owner']}', ";
    $QryInsertFleet .= "`fleet_group` = '{$fleet_group}', ";
    $QryInsertFleet .= "`start_time` = " . SN_TIME_NOW . ";";
    doquery($QryInsertFleet);
    $planet_fields[pname_resource_name(RES_DEUTERIUM)]['delta'] -= $travel_data['consumption'];
    $db_changeset['planets'][] = array('action' => SQL_OP_UPDATE, P_VERSION => 1, 'where' => array('id' => $from['id']), 'fields' => $planet_fields);
    db_changeset_apply($db_changeset);
    $internal_transaction ? sn_db_transaction_commit() : false;
    $from = db_planet_by_id($from['id']);
    return ATTACK_ALLOWED;
    //ini_set('error_reporting', E_ALL ^ E_NOTICE);
}
Exemple #27
0
 }
 sn_db_transaction_commit();
 tpl_assign_fleet($template, $fleets_to_planet);
 tpl_assign_fleet($template, $fleets);
 $lune = $planetrow['planet_type'] == PT_PLANET ? db_planet_by_parent($planetrow['id']) : db_planet_by_id($planetrow['parent_planet']);
 if ($lune) {
     $template->assign_vars(array('MOON_ID' => $lune['id'], 'MOON_IMG' => $lune['image'], 'MOON_NAME' => $lune['name']));
 }
 $planet_fill = floor($planetrow['field_current'] / eco_planet_fields_max($planetrow) * 100);
 $planet_fill = $planet_fill > 100 ? 100 : $planet_fill;
 $planet_recyclers_orbiting = 0;
 foreach (sn_get_groups('flt_recyclers') as $recycler_id) {
     $planet_recyclers_orbiting += mrc_get_level($user, $planetrow, $recycler_id);
 }
 int_planet_pretemplate($planetrow, $template);
 $sn_group_ques = sn_get_groups('ques');
 foreach (array(QUE_STRUCTURES => $sn_group_ques[QUE_STRUCTURES]) as $que_id => $que_type_data) {
     $this_que = $que['ques'][$que_id][$user['id']][$planetrow['id']];
     $template->assign_block_vars('ques', array('ID' => $que_id, 'NAME' => $lang['sys_ques'][$que_id], 'LENGTH' => empty($this_que) ? 0 : count($this_que)));
     if (!empty($this_que)) {
         foreach ($this_que as $que_item) {
             $template->assign_block_vars('que', que_tpl_parse_element($que_item));
         }
     }
 }
 $que_hangar_length = tpl_assign_hangar($template, $planetrow, SUBQUE_FLEET);
 $template->assign_block_vars('ques', array('ID' => QUE_HANGAR, 'NAME' => $lang['sys_ques'][QUE_HANGAR], 'LENGTH' => $que_hangar_length));
 $que_hangar_length = tpl_assign_hangar($template, $planetrow, SUBQUE_DEFENSE);
 $template->assign_block_vars('ques', array('ID' => SUBQUE_DEFENSE, 'NAME' => $lang['sys_ques'][SUBQUE_DEFENSE], 'LENGTH' => $que_hangar_length));
 $overview_planet_rows = $user['opt_int_overview_planet_rows'];
 $overview_planet_columns = $user['opt_int_overview_planet_columns'];
Exemple #28
0
        $RetMessage = $lang['gate_wait_star'] . " - " . pretty_time($NextJumpTime);
    }
    sn_db_transaction_commit();
    message($RetMessage, $lang['tech'][STRUC_MOON_GATE], "jumpgate.php", 10);
} else {
    $template = gettemplate('jumpgate', true);
    if (mrc_get_level($user, $planetrow, STRUC_MOON_GATE) > 0) {
        $Combo = '';
        $MoonList = db_planet_list_moon_other($user['id'], $planetrow['id']);
        // while($CurMoon = db_fetch($MoonList))
        foreach ($MoonList as $CurMoon) {
            if (mrc_get_level($user, $CurMoon, STRUC_MOON_GATE) >= 1) {
                $NextJumpTime = uni_get_time_to_jump($CurMoon);
                $template->assign_block_vars('moon', array('ID' => $CurMoon['id'], 'GALAXY' => $CurMoon['galaxy'], 'SYSTEM' => $CurMoon['system'], 'PLANET' => $CurMoon['planet'], 'NAME' => $CurMoon['name'], 'NEXT_JUMP_TIME' => $NextJumpTime ? pretty_time($NextJumpTime) : ''));
            }
        }
        foreach (sn_get_groups('fleet') as $Ship) {
            if (($ship_count = mrc_get_level($user, $planetrow, $Ship)) <= 0) {
                continue;
            }
            $template->assign_block_vars('fleet', array('SHIP_ID' => $Ship, 'SHIP_NAME' => $lang['tech'][$Ship], 'SHIP_COUNT' => $ship_count, 'SHIP_COUNT_TEXT' => pretty_number($ship_count)));
        }
        $template->assign_vars(array('GATE_JUMP_REST_TIME' => uni_get_time_to_jump($planetrow), 'gate_start_name' => $planetrow['name'], 'gate_start_link' => uni_render_coordinates_href($planetrow, '', 3)));
        display($template, $lang['tech'][STRUC_MOON_GATE]);
    } else {
        message($lang['gate_no_src_ga'], $lang['tech'][STRUC_MOON_GATE], "overview.php", 10);
    }
}
// -----------------------------------------------------------------------------------------------------------
// History version
// 1.0 - Version from scrap .. y avait pas ... bin maintenant y a !!
Exemple #29
0
 case 38:
     upd_log_version_update();
     if (!isset($update_tables['planets']['que_processed'])) {
         upd_alter_table('planets', array("ADD COLUMN `que_processed` INT(11) UNSIGNED NOT NULL DEFAULT 0 AFTER `last_update`"), true);
         upd_do_query("UPDATE {{planets}} SET que_processed = last_update;");
     }
     if (!isset($update_tables['users']['que_processed'])) {
         upd_alter_table('users', array("ADD COLUMN `que_processed` INT(11) UNSIGNED NOT NULL DEFAULT 0 AFTER `onlinetime`"), true);
         upd_do_query("UPDATE {{users}} SET que_processed = onlinetime;");
     }
     if (isset($update_tables['planets']['que'])) {
         $sn_data_aux = array(SHIP_SMALL_FIGHTER_WRATH => array('name' => 'ship_fighter_wrath', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 4000, RES_CRYSTAL => 1500, RES_DEUTERIUM => 500)), SHIP_CARGO_GREED => array('name' => 'ship_cargo_greed', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 40000, RES_CRYSTAL => 10000, RES_DEUTERIUM => 10000)), SHIP_SATTELITE_SLOTH => array('name' => 'ship_sattelite_sloth', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 1000, RES_CRYSTAL => 1000, RES_DEUTERIUM => 1000)), SHIP_LARGE_BATTLESHIP_PRIDE => array('name' => 'ship_battleship_pride', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 40000, RES_CRYSTAL => 40000, RES_DEUTERIUM => 20000)), SHIP_RECYCLER_GLUTTONY => array('name' => 'ship_recycler_gluttony', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 10000, RES_CRYSTAL => 10000, RES_DEUTERIUM => 3000)), SHIP_MEDIUM_BOMBER_ENVY => array('name' => 'ship_bomber_envy', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 35000, RES_CRYSTAL => 15000, RES_DEUTERIUM => 10000)), SHIP_LARGE_ORBITAL_HEAVY => array('name' => 'ship_orbital_heavy', 'type' => UNIT_SHIPS, 'cost' => array(RES_METAL => 40000, RES_CRYSTAL => 30000, RES_DEUTERIUM => 40000)));
         $aux_group = array_combine(array_keys($sn_data_aux), array_keys($sn_data_aux));
         $ques_info = sn_get_groups('ques');
         $group_resource_loot = sn_get_groups('resources_loot');
         $planet_unit_list = sn_get_groups(array('structures', 'fleet', 'defense'));
         $planet_unit_list += $aux_group;
         $drop = array('DROP COLUMN `que`', 'DROP COLUMN `b_hangar`', 'DROP COLUMN `b_hangar_id`');
         $unit_data_max = 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])) {
Exemple #30
0
        $consumption = $travel_data['consumption'];
        // No Break
    // No Break
    case 1:
        if ($galaxy && $system && $planet) {
            $check_type = $planet_type == PT_MOON ? PT_MOON : PT_PLANET;
            $TargetPlanet = db_planet_by_gspt($galaxy, $system, $planet, $check_type);
        }
    case 0:
        $template_result += array('thisgalaxy' => $planetrow['galaxy'], 'thissystem' => $planetrow['system'], 'thisplanet' => $planetrow['planet'], 'thisplanet_type' => $planetrow['planet_type']);
        // no break
}
$template_result += array('galaxy' => $galaxy, 'system' => $system, 'planet' => $planet, 'planet_type' => $planet_type, 'target_mission' => $target_mission ? $target_mission : 0, 'MISSION_NAME' => $target_mission ? $lang['type_mission'][$target_mission] : '');
$is_transport_missions = false;
if ($missiontype) {
    $sn_group_missions = sn_get_groups('missions');
    foreach ($missiontype as $mission_data_id => $mission_data) {
        $is_transport_missions = $is_transport_missions || isset($sn_group_missions[$mission_data_id]['transport']) && $sn_group_missions[$mission_data_id]['transport'];
    }
}
switch ($fleet_page) {
    case 1:
        require 'includes/includes/flt_page1.inc';
        break;
    case 2:
        require_once 'includes/includes/flt_page2.inc';
        sn_fleet_page2();
        break;
    case 3:
        require_once 'includes/includes/flt_page3.inc';
        sn_fleet_page3();