Рассинхрон версий Tournament.

This commit is contained in:
Ivor Barhansky 2022-06-28 15:19:59 +03:00
parent dc710a8cb1
commit 3a12248bda
3 changed files with 151 additions and 71 deletions

View File

@ -1,12 +1,33 @@
<?php
/** todo
* В каком-то месте проверять по крону не протух ли турнир!
*/
namespace Insallah;
class Tournament
{
const IS_ENABLED = true;
const SEND_CHAT_MESSAGE = 3;
const START_TOURNAMENT = 6;
const PRIZE1 = 25;
const PRIZE2 = 10;
const PRIZE3 = 5;
const MIN_EXP = 175000;
const CHAT_MESSAGE = 'Внимание! Турнир для %d уровня открыт! Поспешите принять участие в Зале Воинов!';
const VICTORY_MESSAGE = 'Турнир для %d уровней завершён! Первое место: %s. Второе место: %s. Третье место: %s.';
const DELAY1 = '+12hour';
const DELAY2 = '+6hour';
const DELAY3 = '+3hour';
/** Формула рассчёта разрешённой стоимости одетых предметов.
*
* @param int $int
*
* @return float|int
*/
public static function ekrOverpriceFormula($int)
{
return ($int - 7) * 151;
}
/**
* Проверяем может ли игрок учавствовать в турнире и либо присоединяем его, либо обламываем.
*
@ -18,7 +39,13 @@ class Tournament
{
/** Возвращает level, или 0 если провалены проверки. */
$userLevel = TournamentModel::getUserLevel($user_id);
if ($userLevel === 0) {
if (
$userLevel === 0 ||
TournamentModel::isEkrOverpriced($user_id, $userLevel) ||
!TournamentModel::isEnoughExperience($user_id) ||
TournamentModel::IsRestrictedToJoin($user_id) ||
TournamentModel::isStarted($user_id)
) {
return;
}
@ -28,36 +55,35 @@ class Tournament
}
TournamentModel::joinTournament($user_id, $userLevel);
$mq++;
/** На третьем участнике пишем уведомление в чат. */
if ($mq === 2) {
TournamentModel::sysMessage("Внимание! Идёт набор бойцов на турнир " . $userLevel . " уровня! Поспешите!");
if ($mq == self::SEND_CHAT_MESSAGE) {
TournamentModel::sysMessage(sprintf(self::CHAT_MESSAGE, $userLevel));
}
/** На двенадцатом участнике начинаем турнир. */
if ($mq === 11) {
if ($mq == self::START_TOURNAMENT) {
TournamentModel::startTournament($userLevel);
$this->check_members($userLevel);
}
}
/**
* Проверяем есть ли ещё участники турнира. Если есть, отправляем драться. Если остался последний - значит он
* победитель.
* todo Обработать ничью!
*
* @param int $tournament_id
*
* Проверка для крона\конфига. Выбивает проигравших и перезапускает поединки во всех турнирах.
* @return void
*/
private function check_members($tournament_id)
public function startAllBattles()
{
$active_fighters = TournamentModel::getFreeFighters($tournament_id);
if (count($active_fighters) > 1) {
$this->start_battle($active_fighters);
} else {
TournamentModel::removeFighter($active_fighters[0]); // выбиваем победителя
$this->victory($tournament_id);
$db = new Db();
$db::sql('delete from tournaments where start_time + date_add(start_time,interval 30 minute) < unix_timestamp()');
TournamentModel::removeFighter(TournamentModel::getLooser());
$tournament_levels = $db::getColumn('select tid from tournaments where start_time = -1');
foreach ($tournament_levels as $level) {
$alive_fighters = TournamentModel::getFreeFighters($level);
if (count($alive_fighters) > 1) {
$this->start_battle($alive_fighters);
} elseif (count($alive_fighters) === 1) {
TournamentModel::removeFighter($alive_fighters[0]);
$this->victory($level);
}
}
}
@ -78,22 +104,6 @@ class Tournament
}
}
/**
* Вызывается при проигрыше боя или при уходе в оффлайн.
*
* @param int $user_id
*
* @return void
*/
public function kick_user($user_id)
{
if (empty($user_id)) {
return;
}
TournamentModel::removeFighter($user_id);
$this->check_members(TournamentModel::getTournamentIdByUserId($user_id)); //перезапуск выбора противника для поединка
}
/**
* Награждаем победителей турнира, чистим базу.
*
@ -104,9 +114,21 @@ class Tournament
private function victory($tournament_id)
{
$winners = TournamentModel::getWinners($tournament_id);
sleep(1);
TournamentModel::givePrizeItems($winners[1], self::PRIZE1);
TournamentModel::givePrizeItems($winners[2], self::PRIZE2);
TournamentModel::givePrizeItems($winners[3], self::PRIZE3);
sleep(1);
TournamentModel::giveDelay($winners[1], strtotime(self::DELAY1));
TournamentModel::giveDelay($winners[2], strtotime(self::DELAY2));
TournamentModel::giveDelay($winners[3], strtotime(self::DELAY3));
sleep(1);
TournamentModel::sysMessage(sprintf(self::VICTORY_MESSAGE,
$tournament_id,
TournamentModel::uidToLogin($winners[1]),
TournamentModel::uidToLogin($winners[2]),
TournamentModel::uidToLogin($winners[3])));
sleep(3);
TournamentModel::destroyTournament($tournament_id);
TournamentModel::givePrizeItems($winners[1], 25);
TournamentModel::givePrizeItems($winners[2], 10);
TournamentModel::givePrizeItems($winners[3], 5);
}
}

View File

@ -1,8 +1,6 @@
<?php
namespace Insallah;
use Achievements;
use user;
class TournamentModel
{
@ -17,18 +15,60 @@ class TournamentModel
*/
public static function getUserLevel($uid)
{
$db = new Db;
$db = new Db();
$level = $db::getValue('select level from users where id = ? and level between 8 and 12 and battle = 0', [$uid]);
if (!$level) {
return 0;
return $level ? $level : 0;
}
/**
* @param int $uid
* @param int $level
*
* @return bool
*/
public static function isEkrOverpriced($uid, $level = null)
{
$db = new Db();
if (is_null($level)) {
$level = $db::getValue('select level from users where id = ?', [$uid]);
}
$ekr_total = $db::getValue('select sum(2price) from items_users where inOdet > 0 and uid = ?', [$uid]);
$exp = $db::getValue('select exp from stats where id = ?', [$uid]);
// Вот правда не знаю проканает или нет.
if ($ekr_total > ($level - 7) * 150 || $exp < 250000) {
return 0;
$wearedItemsEkrPrice = $db::getValue('select sum(2price) from items_users where inOdet > 0 and uid = ?', [$uid]);
return $wearedItemsEkrPrice > Tournament::ekrOverpriceFormula($level);
}
/**
* @param int $uid
*
* @return bool
*/
public static function isEnoughExperience($uid)
{
$db = new Db();
return $db::getValue('select exp from stats where id = ?', [$uid]) >= Tournament::MIN_EXP;
}
return $level;
/**
* @param int $uid
*
* @return bool
*/
public static function IsRestrictedToJoin($uid)
{
$db = new Db();
$delayEffect = $db::getValue('select count(*) from eff_users where uid = ? and id_eff = 486 and `delete` = 0', [$uid]);
return (bool)$delayEffect;
}
/**
* @param $tid
*
* @return bool
*/
public static function isStarted($tid)
{
$db = new Db();
$status = $db::getValue('select count(*) from tournaments where start_time = -1 and tid = ?', [$tid]);
return (bool)$status;
}
/**
@ -111,7 +151,8 @@ class TournamentModel
public static function getFightersTeams(array $fighters_list)
{
$db = new Db();
return array_chunk($db::getRows('select id from users where battle = 0 and id in (?)', [implode(', ', $fighters_list)]), 2);
$query = sprintf("select id from users where battle = 0 and id in (%s)", implode(', ', $fighters_list));
return array_chunk($db::getColumn($query), 2);
}
/**
@ -124,7 +165,7 @@ class TournamentModel
public static function getFreeFighters($tid)
{
$db = new Db();
return $db::getRows('select uid from tournaments_users where tid = ? and death_time = 0 order by rand()', [$tid]);
return $db::getColumn('select uid from tournaments_users where tid = ? and death_time = 0 order by rand()', [$tid]);
}
/**
@ -137,14 +178,12 @@ class TournamentModel
public static function getWinners($tid)
{
$db = new Db();
$arr = [];
array_unshift($arr, '');
unset($arr[0]);
$winners = $db::getRows('select uid from tournaments_users where tid = ? order by death_time desc limit 3', [$tid]);
foreach ($winners as $winner) {
$arr[] = $winner['uid'];
}
return $arr;
$winners = $db::getColumn('select uid from tournaments_users where tid = ? order by death_time desc limit 3', [$tid]);
return [
1 => $winners[0],
2 => $winners[1],
3 => $winners[2]
];
}
/**
@ -166,10 +205,10 @@ class TournamentModel
limit 1) as last_battle
where
battle_users.battle = last_battle.id and
battle_users.team != last_battle.team_win';
battle_users.team != last_battle.team_win and
battle_users.uid in (select uid from tournaments_users where death_time = 0)';
$db = new Db;
$row = $db::getRow($query);
$db::sql('delete from battle where id = ?', [$row['battle']]);
return $row['uid'];
}
@ -182,10 +221,13 @@ class TournamentModel
*/
public static function removeFighter($uid)
{
if (!$uid) return;
$db = new Db();
$db::sql('update tournaments_users set death_time = unix_timestamp() where uid = ?', [$uid]);
$db::sql('update tournaments_users set death_time = unix_timestamp() where death_time = 0 and uid = ?', [$uid]);
self::teleport($uid, 9);
(new Achievements(user::start()))->updateCounter('trn');
//fixme: Классы не подключаются друг к другу. Нужно менять архитектуру игры. :(
Db::sql("update users_achiv set trn = trn + 1 where id = ?", [$uid]);
//(new Achievements(\user::start()))->updateCounter('trn');
}
/**
@ -252,15 +294,17 @@ class TournamentModel
/**
* Нет проверок $message потому что оно всегда задаётся в коде и игрок на него не влияет.
*
* @param string $city
* @param string $message
*
* @return void
*/
public static function sysMessage($message, $city = 'capitalcity')
public static function sysMessage($message)
{
if (!empty($message)) {
$db = new Db();
$db::sql('insert into chat (city, room, time, type, text, new, da) values (?, 0, unix_timestamp(), 6, ?, 1, 1)', [$city, $message]);
$message = "<span style='font-weight: bold; color: forestgreen;'>$message</span>";
$db::sql('insert into chat (time, type, text, new, da) values (unix_timestamp(), 6, ?, 1, 1)', [$message]);
}
}
/**
@ -285,4 +329,18 @@ class TournamentModel
$stmt->execute($args);
}
}
/** Эффект-ограничитель на участие в турнире.
* @param $uid
* @param $unix_time
*
* @return void
*/
public static function giveDelay($uid, $unix_time)
{
$db = new Db();
$query = 'insert into eff_users (id_eff, uid, name, timeUse) VALUES (?,?,?,?)';
$args = [486, $uid, 'Призёр городского турнира!', $unix_time];
$db::sql($query, $args);
}
}

View File

@ -1350,7 +1350,7 @@ $kp = array(
$ico[1] .= '<a href="#"><img src="https://img.new-combats.com/sporttrainers3.gif" onMouseOver="top.hi(this,\'<b>Начинающий Помощник Администрации</b>\',event,0,0,1,0,\'\');" onMouseOut="top.hic();" onMouseDown="top.hic();"></a>';
}
}
$ai = (new Achievements($u))->getInfo(); //Титулы $ico[3]
$ai = (new \Insallah\Achievements($u))->getInfo(); //Титулы $ico[3]
if(isset($ai['id']) && $inf['banned']==0 && ($ai['zb']>0 || $ai['vx']>0 || $ai['snt']>0 || $ai['rp']>0 || $ai['rn']>0 || $ai['rb']>0 || $ai['pg']>0 || $ai['bv']>0 || $ai['kw']>0 || $ai['pa']>0))
{