function sn_RestoreFleetToPlanet(&$fleet_row, $start = true, $only_resources = false, $safe_fleet = false, &$result) { sn_db_transaction_check(true); $result = CACHE_NOTHING; if (!is_array($fleet_row)) { return $result; } $prefix = $start ? 'start' : 'end'; // Поскольку эта функция может быть вызвана не из обработчика флотов - нам надо всё заблокировать вроде бы НЕ МОЖЕТ!!! // TODO Проеверить от многократного срабатывания !!! // Тут не блокируем пока - сначала надо заблокировать пользователя, что бы не было дедлока // $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1", true); // Узнаем ИД владельца планеты - без блокировки // TODO поменять на владельца планеты - когда его будут возвращать всегда !!! $user_id = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", false, 'id_owner'); $user_id = $user_id['id_owner']; // Блокируем пользователя $user = db_user_by_id($user_id, true); // Блокируем планету $planet_arrival = db_planet_by_vector($fleet_row, "fleet_{$prefix}_", true); // Блокируем флот // $fleet_row = doquery("SELECT * FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1 FOR UPDATE;", true); // Если флот уже обработан - не существует или возращается - тогда ничего не делаем if (!$fleet_row || !is_array($fleet_row) || $fleet_row['fleet_mess'] == 1 && $only_resources) { return $result; } // Флот, который возвращается на захваченную планету, пропадает if ($start && $fleet_row['fleet_mess'] == 1 && $planet_arrival['id_owner'] != $fleet_row['fleet_owner']) { doquery("DELETE FROM {{fleets}} WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;"); return $result; } //pdump($planet_arrival); $db_changeset = array(); if (!$only_resources) { flt_destroy($fleet_row); if ($fleet_row['fleet_owner'] == $planet_arrival['id_owner']) { $fleet_array = sys_unit_str2arr($fleet_row['fleet_array']); foreach ($fleet_array as $ship_id => $ship_count) { if ($ship_count) { $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $planet_arrival['id']); } } } else { return CACHE_NOTHING; } } else { // flt_send_back($fleet_row); doquery("UPDATE {{fleets}} SET fleet_resource_metal = 0, fleet_resource_crystal = 0, fleet_resource_deuterium = 0, fleet_mess = 1 WHERE `fleet_id`='{$fleet_row['fleet_id']}' LIMIT 1;"); } if (!empty($db_changeset)) { db_changeset_apply($db_changeset); } db_planet_set_by_id($planet_arrival['id'], "`metal` = `metal` + '{$fleet_row['fleet_resource_metal']}', `crystal` = `crystal` + '{$fleet_row['fleet_resource_crystal']}', `deuterium` = `deuterium` + '{$fleet_row['fleet_resource_deuterium']}'"); $result = CACHE_FLEET | ($start ? CACHE_PLANET_SRC : CACHE_PLANET_DST); return $result; }
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; */ }
/** * 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 .= " {$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']}';"); } }
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); }
$TargetGate = db_planet_by_id($TargetPlanet, true, '`id`, `last_jump_time`'); if (mrc_get_level($user, $TargetGate, STRUC_MOON_GATE) > 0) { $NextDestTime = uni_get_time_to_jump($TargetGate); if (!$NextDestTime) { // $SubQueryOri = ""; // $SubQueryDes = ""; $ship_list = sys_get_param('ships'); $db_changeset = array(); foreach ($ship_list as $ship_id => $ship_count) { if (!in_array($ship_id, sn_get_groups('fleet'))) { continue; } $ship_count = max(0, min(floor($ship_count), mrc_get_level($user, $planetrow, $ship_id))); if ($ship_count) { $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, -$ship_count, $user, $planetrow['id']); $db_changeset['unit'][] = sn_db_unit_changeset_prepare($ship_id, $ship_count, $user, $TargetGate['id']); } } // Dit monsieur, y avait quelque chose a envoyer ??? if (!empty($db_changeset)) { db_planet_set_by_id($TargetGate['id'], "`last_jump_time` = " . SN_TIME_NOW . ""); db_planet_set_by_id($planetrow['id'], "`last_jump_time` = " . SN_TIME_NOW . ""); db_changeset_apply($db_changeset); db_user_set_by_id($user['id'], "`current_planet` = '{$TargetGate['id']}'"); $planetrow['last_jump_time'] = SN_TIME_NOW; $RetMessage = $lang['gate_jump_done'] . " - " . pretty_time(uni_get_time_to_jump($planetrow)); } else { $RetMessage = $lang['gate_wait_data']; } } else { $RetMessage = $lang['gate_wait_dest'] . " - " . pretty_time($NextDestTime);
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); if ($cant_attack != ATTACK_ALLOWED) { die($lang['fl_attack_error'][$cant_attack]); } $FleetDBArray = array(); $db_changeset = array(); foreach ($fleet_array as $unit_id => $unit_count) { $FleetDBArray[] = "{$unit_id},{$unit_count}"; // $db_changeset[] = "`{$unit_db_name}` = `{$unit_db_name}` - {$unit_count}"; $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, -$unit_count, $user, $planetrow); } $FleetDBArray = implode(';', $FleetDBArray); // $db_changeset = implode(',', $db_changeset); $fleet_ship_count = array_sum($fleet_array); if ($target_mission == MT_MISSILE) { $distance = abs($target_coord['system'] - $planetrow['system']); $duration = round((30 + 60 * $distance) / flt_server_flight_speed_multiplier()); $arrival = SN_TIME_NOW + $duration; $travel_data['consumption'] = 0; doquery("INSERT INTO `{{iraks}}` SET\n `fleet_target_owner` = '{$target_row['id_owner']}', `fleet_end_galaxy` = '{$target_coord['galaxy']}', `fleet_end_system` = '{$target_coord['system']}', `fleet_end_planet` = '{$target_coord['planet']}',\n `fleet_owner` = '{$user['id']}', `fleet_start_galaxy` = '{$planetrow['galaxy']}', `fleet_start_system` = '{$planetrow['system']}', `fleet_start_planet` = '{$planetrow['planet']}',\n `fleet_end_time` = '{$arrival}', `fleet_amount` = '{$fleet_ship_count}', `primaer` = '{$target_structure}';"); } else { $travel_data = flt_travel_data($user, $planetrow, $target_coord, $fleet_array, 10); if ($planetrow['deuterium'] < $travel_data['consumption']) { die($lang['gs_c13']); }
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};"); } }
lng_include('artifacts'); include 'includes/includes/art_artifact.php'; $sn_group_artifacts = sn_get_groups('artifacts'); if (($action = sys_get_param_int('action')) && in_array($unit_id = sys_get_param_int('unit_id'), $sn_group_artifacts)) { switch ($action) { case ACTION_BUY: sn_db_transaction_start(); $user = db_user_by_id($user['id'], true); $artifact_level = mrc_get_level($user, array(), $unit_id, true); $build_data = eco_get_build_data($user, $planetrow, $unit_id, $artifact_level, true); $darkmater_cost = $build_data[BUILD_CREATE][RES_DARK_MATTER]; // TODO: more correct check - with "FOR UPDATE" if (mrc_get_level($user, null, RES_DARK_MATTER) >= $darkmater_cost) { $unit_max_stack = get_unit_param($unit_id, P_MAX_STACK); if (!isset($unit_max_stack) || $unit_max_stack > mrc_get_level($user, $planetrow, $unit_id)) { $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, 1, $user); db_changeset_apply($db_changeset); rpg_points_change($user['id'], RPG_ARTIFACT, -$darkmater_cost, "Spent for artifact {$lang['tech'][$unit_id]} ID {$unit_id}"); sn_db_transaction_commit(); header("Location: artifacts.php#{$unit_id}"); ob_end_flush(); die; } else { $Message = $lang['off_maxed_out']; } } else { $Message = $lang['sys_no_points']; } sn_db_transaction_rollback(); break; case ACTION_USE:
function art_use(&$user, &$planetrow, $unit_id) { global $lang; if (!in_array($unit_id, sn_get_groups('artifacts'))) { return; } sn_db_transaction_start(); $user = db_user_by_id($user['id'], true); $unit_level = $artifact_level_old = mrc_get_level($user, array(), $unit_id, true); if ($unit_level > 0) { $db_changeset = array(); switch ($unit_id) { case ART_LHC: case ART_HOOK_SMALL: case ART_HOOK_MEDIUM: case ART_HOOK_LARGE: $has_moon = db_planet_by_parent($planetrow['id'], true, '`id`'); if ($planetrow['planet_type'] == PT_PLANET && !$has_moon['id']) { $unit_level--; $moon_chance = $unit_id == ART_LHC ? uni_calculate_moon_chance($planetrow['debris_metal'] + $planetrow['debris_crystal']) : ($unit_id == ART_HOOK_MEDIUM ? mt_rand(1100, 8999) : ($unit_id == ART_HOOK_SMALL ? 1100 : 8999)); $random = $unit_id == ART_LHC ? mt_rand(1, 100) : $moon_chance; if ($random <= $moon_chance) { $new_moon_row = uni_create_moon($planetrow['galaxy'], $planetrow['system'], $planetrow['planet'], $user['id'], $moon_chance); $message = sprintf($lang['art_moon_create'][$unit_id], $new_moon_row['name'], uni_render_coordinates($planetrow), pretty_number($moon_chance)); } else { $message = $lang['art_lhc_moon_fail']; } msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_ADMIN, $lang['art_lhc_from'], $lang['art_lhc_subj'], $message); } else { $message = $lang['art_moon_exists']; } break; case ART_RCD_SMALL: case ART_RCD_MEDIUM: case ART_RCD_LARGE: $planetrow = db_planet_by_id($planetrow['id'], true); if ($planetrow['planet_type'] != PT_PLANET) { $message = $lang['art_rcd_err_moon']; break; } $que = que_get($user['id'], $planetrow['id'], QUE_STRUCTURES, false); if (!empty($que['items'])) { $message = $lang['art_rcd_err_que']; break; } $artifact_deploy = get_unit_param($unit_id, P_DEPLOY); // $deployment_str = ''; $sectors_used = 0; foreach ($artifact_deploy as $deploy_unit_id => $deploy_unit_level) { if (!($levels_deployed = max(0, $deploy_unit_level - mrc_get_level($user, $planetrow, $deploy_unit_id, true, true)))) { continue; } $sectors_used += $levels_deployed; $db_changeset['unit'][] = sn_db_unit_changeset_prepare($deploy_unit_id, $levels_deployed, $user, $planetrow['id']); //$deploy_unit_name = get_unit_param($deploy_unit_id, P_NAME); //$deployment_str .= ",`{$deploy_unit_name}` = GREATEST(`{$deploy_unit_name}`, {$deploy_unit_level})"; } if ($sectors_used == 0) { $message = $lang['art_rcd_err_no_sense']; break; } $unit_level--; db_planet_set_by_id($planetrow['id'], "`field_current` = `field_current` + {$sectors_used}"); $message = sprintf($lang['art_rcd_ok'], $lang['tech'][$unit_id], $planetrow['name'], uni_render_coordinates($planetrow)); msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_rcd_subj'], $lang['art_rcd_subj'], $message); break; case ART_HEURISTIC_CHIP: $que_item = null; $que = que_get($user['id'], $planetrow['id'], QUE_RESEARCH, true); $current_que =& $que['ques'][QUE_RESEARCH][$user['id']][0]; if (!empty($current_que)) { reset($current_que); $que_item =& $que['ques'][QUE_RESEARCH][$user['id']][0][key($current_que)]; } if (!empty($que_item) && $que_item['que_time_left'] > 60) { $unit_level--; $old_time = $que_item['que_time_left']; $que_item['que_time_left'] = $que_item['que_time_left'] > PERIOD_HOUR ? ceil($que_item['que_time_left'] / 2) : 0; db_que_set_time_left_by_id($que_item['que_id'], $que_item['que_time_left']); $message = sprintf($lang['art_heurestic_chip_ok'], $lang['tech'][$que_item['que_unit_id']], $que_item['que_unit_level'], sys_time_human($old_time - $que_item['que_time_left'])); msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_heurestic_chip_subj'], $lang['art_heurestic_chip_subj'], $message); } else { $message = $lang['art_heurestic_chip_no_research']; } break; case ART_NANO_BUILDER: $planetrow = db_planet_by_id($planetrow['id'], true); $que_item = null; $que = que_get($user['id'], $planetrow['id'], QUE_STRUCTURES, true); $current_que =& $que['ques'][QUE_STRUCTURES][$user['id']][$planetrow['id']]; // $que_item = &$que['que'][QUE_STRUCTURES][0]; if (!empty($current_que)) { reset($current_que); $que_item =& $que['ques'][QUE_STRUCTURES][$user['id']][$planetrow['id']][key($current_que)]; } if (isset($que_item) && $que_item['que_time_left'] > 60) { $unit_level--; $old_time = $que_item['que_time_left']; $que_item['que_time_left'] = $que_item['que_time_left'] > PERIOD_HOUR ? ceil($que_item['que_time_left'] / 2) : 0; db_que_set_time_left_by_id($que_item['que_id'], $que_item['que_time_left']); $message = sprintf($lang['art_nano_builder_ok'], $que_item['que_unit_mode'] == BUILD_CREATE ? $lang['art_nano_builder_build'] : $lang['art_nano_builder_destroy'], $lang['tech'][$que_item['que_unit_id']], $que_item['que_unit_level'], $planetrow['name'], uni_render_coordinates($planetrow), sys_time_human($old_time - $que_item['que_time_left'])); msg_send_simple_message($user['id'], 0, 0, MSG_TYPE_QUE, $lang['art_nano_builder_subj'], $lang['art_nano_builder_subj'], $message); } else { $message = $lang['art_nano_builder_no_que']; } break; } if ($unit_level != $artifact_level_old) { $db_changeset['unit'][] = sn_db_unit_changeset_prepare($unit_id, $unit_level - $artifact_level_old, $user); db_changeset_apply($db_changeset); } } else { $message = $lang['art_err_no_artifact']; } sn_db_transaction_commit(); message($message, "{$lang['tech'][UNIT_ARTIFACTS]} - {$lang['tech'][$unit_id]}", ($request_uri = sys_get_param_str_unsafe('REQUEST_URI')) ? $request_uri : 'artifacts' . DOT_PHP_EX . '#' . $unit_id, 5); }