dev-php74 #30

Merged
lopar merged 17 commits from dev-php74 into master 2023-01-11 13:30:03 +00:00
13 changed files with 631 additions and 685 deletions
Showing only changes of commit 7a5dfd22a7 - Show all commits

View File

@ -1,5 +1,8 @@
<?php <?php
use Core\Config;
use Insallah\Tournaments\Tournament;
error_reporting(E_ALL ^ E_NOTICE); error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 'Off'); ini_set('display_errors', 'Off');
setlocale(LC_CTYPE, "ru_RU.CP1251"); setlocale(LC_CTYPE, "ru_RU.CP1251");
@ -33,9 +36,8 @@ spl_autoload_register(function ($className) {
}); });
$code = '1'; $code = '1';
\Core\Config::init(); Config::init();
$c = \Core\Config::get(); $c = Config::get();
//Tournament::startAllBattles();
if (isset($_GET['version'])) {
die('Version: ' . $c['ver']);
}

View File

@ -1567,87 +1567,20 @@ class FightRequest
echo '<br><br><br><b><font color="black"><center>Ïðèíèìàòü ó÷àñòèå â òóðíèðå òîëüêî ñ ïåðâîãî óðîâíÿ.</center></font></b>'; echo '<br><br><br><b><font color="black"><center>Ïðèíèìàòü ó÷àñòèå â òóðíèðå òîëüêî ñ ïåðâîãî óðîâíÿ.</center></font></b>';
$this->zv_see = 0; $this->zv_see = 0;
} elseif ($r == 10) { } elseif ($r == 10) {
if (\Insallah\Tournament::IS_ENABLED) {
/** Òóðíèðû by Insallah*/ /** Òóðíèðû by Insallah*/
# Çàùèòà îò F5 # Çàùèòà îò F5
if (!isset($_SESSION['bypass'])) { if (!isset($_SESSION['bypass'])) {
$_SESSION['bypass'] = mt_rand(); $_SESSION['bypass'] = mt_rand();
}
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['key'] == $_SESSION['bypass']) {
unset($_SESSION['bypass']);
if (array_key_exists('tournament_start', $_POST)) {
(new \Insallah\Tournament())->join($this->u->info['id']);
}
}
##
# Ôîðìèðóåì ñïèñîê èäóùèõ òóðíèðîâ.
$db = new Db();
$tournamentsList = $db::getRows('select * from tournaments');
$tournaments = '<ul>';
foreach ($tournamentsList as $tournament) {
$time = $tournament['start_time'] === -1 ? 'Òóðíèð óæå íà÷àëñÿ!' : date(
'G:i', $tournament['start_time']
);
$tournament_members_id = \Insallah\TournamentModel::getFreeFighters($tournament['tid']);
$members = [];
foreach ($tournament_members_id as $member) {
$members[] = \Insallah\TournamentModel::uidToLogin($member);
}
$tournaments .= sprintf(
"<li>Òóðíèð äëÿ %d óðîâíåé.<br>Âðåìÿ ïîäà÷è çàÿâêè: %s<br>Ó÷àñòíèêè: %s</li>",
$tournament['tid'], $time, implode(', ', $members)
);
}
$tournaments .= '</ul>';
?>
<div>
<strong style="color: red;">Âíèìàíèå!</strong>
<ul>
<li style="color: blue;"> ñëó÷àå ñîçäàíèÿ ëèáî ïðèñîåäèíåíèÿ ê Òóðíèðó, ïîêèíóòü åãî -
<u>íåâîçìîæíî</u>!
</li>
<?php if (\Insallah\TournamentModel::isEkrOverpriced($this->u->info['id'])): ?>
<li>Ñòîèìîñòü ïðåäìåòîâ, îäåòûõ íà âàñ íå äîëæíà
ïðåâûøàòü <?= \Insallah\Tournament::ekrOverpriceFormula(
$this->u->info['level']
) ?> åâðîêðåäèòîâ.
</li>
<?php endif; ?>
<?php if ($this->u->info['exp'] < \Insallah\Tournament::MIN_EXP): ?>
<li>Ó âàñ äîëæíî áûòü íå ìåíåå <?= \Insallah\Tournament::MIN_EXP ?> îïûòà.</li>
<?php endif; ?>
<li style="color: blue;">Òóðíèð íà÷í¸òñÿ, êîãäà â çàÿâêå
íàáåð¸òñÿ <?= \Insallah\Tournament::START_TOURNAMENT ?> ÷åëîâåê.
</li>
<li style="color: blue;">Èãðîêè çàíÿâøèå 1, 2 è 3 ìåñòà ïîëó÷àò 25, 15, 5 Ðåëèêâèé
Àíãåëà, à òàê æå çàäåðæêè íà ó÷àñòèå â òóðíèðå 12 ÷àñîâ, 6 è 3 ÷àñà ñîîòâåòñòâåííî!
</li>
</ul>
</div>
<?php if (!empty($tournamentsList)): ?>
<div>
<strong>Àêòèâíûå òóðíèðû.</strong><br>
<?= $tournaments ?>
</div>
<?php endif; ?>
<?php if (!\Insallah\TournamentModel::getTournamentIdByUserId(
$this->u->info['id']
) || !\Insallah\TournamentModel::isStarted($this->u->info['level'])): ?>
<form method="post">
<input type="submit" name="tournament_start" value="Ïðèíÿòü ó÷àñòèå â òóðíèðå">
<input type="hidden" name="key" value="<?= $_SESSION['bypass'] ?>">
</form>
<?php else: ?>
Âû ó÷àâñòâóåòå.
<?php endif; ?>
<?php
} else {
?>
<div>
<strong style="color: crimson;">Â äàííûé ìîìåíò òóðíèðû íå ïðîâîäÿòñÿ!</strong>
</div>
<?php
} }
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['key'] == $_SESSION['bypass']) {
unset($_SESSION['bypass']);
if (array_key_exists('tournament_start', $_POST)) {
(new Insallah\Tournaments\Tournament())->join($this->u->info['id']);
}
}
$tlist = new \Insallah\Tournaments\View\TList($this->u);
echo $tlist; # Ôîðìèðóåì ñïèñîê èäóùèõ òóðíèðîâ.
/** Êîíåö òóðíèðîâ îò Insallah. */ /** Êîíåö òóðíèðîâ îò Insallah. */
} elseif ($this->u->info['zv'] > 0 && $this->u->info['battle'] == 0 && $r != 8) { } elseif ($this->u->info['zv'] > 0 && $this->u->info['battle'] == 0 && $r != 8) {
if ($zi['razdel'] == 1 || $zi['razdel'] == 2 || $zi['razdel'] == 3) { if ($zi['razdel'] == 1 || $zi['razdel'] == 2 || $zi['razdel'] == 3) {

View File

@ -1,16 +1,7 @@
<?php <?php
use Insallah\Tournament; //require_once 'Core/Db.php';
require_once 'Core/Db.php';
require_once 'Core/Math.php'; require_once 'Core/Math.php';
require_once 'Core/Table.php'; require_once 'Core/Table.php';
require_once 'Runes/Runes.php'; require_once 'Runes/Runes.php';
require_once 'Tournament/Tournament.php';
require_once 'Tournament/TournamentModel.php';
require_once 'Achievements.php'; require_once 'Achievements.php';
//Âìåñòî êðîíà äëÿ òóðíèðà.
if (Tournament::IS_ENABLED) {
(new Tournament())->startAllBattles();
}

View File

@ -1,135 +0,0 @@
<?php
namespace Insallah;
class Tournament
{
const IS_ENABLED = true;
const SEND_CHAT_MESSAGE = 3;
const START_TOURNAMENT = 5;
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;
}
/**
* Ïðîâåðÿåì ìîæåò ëè èãðîê ó÷àâñòâîâàòü â òóðíèðå è ëèáî ïðèñîåäèíÿåì åãî, ëèáî îáëàìûâàåì.
*
* @param int $user_id
*
* @return void
*/
public function join($user_id)
{
/** Âîçâðàùàåò level, èëè 0 åñëè ïðîâàëåíû ïðîâåðêè. */
$userLevel = TournamentModel::getUserLevel($user_id);
if (
$userLevel === 0 ||
TournamentModel::isEkrOverpriced($user_id, $userLevel) ||
!TournamentModel::isEnoughExperience($user_id) ||
TournamentModel::IsRestrictedToJoin($user_id) ||
TournamentModel::isStarted($user_id)
) {
return;
}
$mq = TournamentModel::getWaitingMembersQuantity($userLevel);
if (empty($mq)) {
TournamentModel::createTournament($userLevel);
}
TournamentModel::joinTournament($user_id, $userLevel);
$mq++;
if ($mq == self::SEND_CHAT_MESSAGE) {
TournamentModel::sysMessage(sprintf(self::CHAT_MESSAGE, $userLevel));
}
if ($mq == self::START_TOURNAMENT) {
TournamentModel::startTournament($userLevel);
}
}
/**
* Ïðîâåðêà äëÿ êðîíà\êîíôèãà. Âûáèâàåò ïðîèãðàâøèõ è ïåðåçàïóñêàåò ïîåäèíêè âî âñåõ òóðíèðàõ.
* @return void
*/
public function startAllBattles()
{
$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) {
shuffle($alive_fighters);
$this->start_battle($alive_fighters);
} elseif (count($alive_fighters) === 1) {
TournamentModel::removeFighter($alive_fighters[0], true);
$this->victory($level);
}
}
}
/**
* Ïîëó÷àåì ïàðû áîéöîâ è íà÷èíàåì èõ ïîåäèíêè.
*
* @param array $fighters_list
*
* @return void
*/
private function start_battle(array $fighters_list)
{
$teams = TournamentModel::getFightersTeams($fighters_list);
foreach ($teams as $team) {
if (count($team) === 2) {
TournamentModel::startBattle($team[0], $team[1]);
}
}
}
/**
* Íàãðàæäàåì ïîáåäèòåëåé òóðíèðà, ÷èñòèì áàçó.
*
* @param int $tournament_id
*
* @return void
*/
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);
}
}

View File

@ -1,358 +0,0 @@
<?php
namespace Insallah;
class TournamentModel
{
/**
* ïðîâåðêà óðîâíÿ, ñòîèìîñòè ýêâèïà, ïðî÷èå ïðîâåðêè, ÷òî ïåðñîíàæ ñâîáîäåí
* òàéìåð îæèäàíèÿ 30 ìèíóò
*
* @param int $uid
*
* @return int
*/
public static function getUserLevel($uid)
{
$db = new Db();
$level = $db::getValue('select level from users where id = ? and level between 8 and 12 and battle = 0', [$uid]);
return $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]);
}
$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;
}
/**
* @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;
}
/**
* Ñ÷èòàåì ñêîëüêî èãðîêîâ æäóò â çàÿâêå íà òóðíèð.
*
* @param int $tid
*
* @return int
*/
public static function getWaitingMembersQuantity($tid)
{
$db = new Db();
return $db::getValue('select count(*) from tournaments_users where tid = ?', [$tid]);
}
/**
* Ñîçäàíèå íîâîãî òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function createTournament($tid)
{
$db = new Db();
$db::sql('insert into tournaments (tid) values (?)', [$tid]);
}
/**
* Èãðîê ïðèñîåäèíÿåòñÿ ê òóðíèðó è òåëåïîðòèðóåòñÿ â òóðíèðíóþ êîìíàòó.
*
* @param int $uid
* @param int $tid
*
* @return void
*/
public static function joinTournament($uid, $tid)
{
/** Êàñòîìíûå êîìíàòû 25008 - 25012. */
$room_id = 25000 + $tid;
$db = new Db();
$db::sql('insert into tournaments_users (tid, uid) values (?, ?)', [$tid, $uid]);
self::teleport($uid, $room_id);
}
/**
* Ñòàðò òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function startTournament($tid)
{
$db = new Db();
$db::sql('update tournaments set start_time = -1 where tid = ?', [$tid]);
}
/**
* ×èñòèì áàçû îò ïðîøåäøåãî òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function destroyTournament($tid)
{
$db = new Db();
//Óáåäèòüñÿ ÷òî â áàçå íàñòðîåí foreign_keys è ïîñëåäóåò àâòîî÷èñòêà tournaments_users !!!
$db::sql('delete from tournaments where tid = ?', [$tid]);
}
/**
* Ïîëó÷àåì ñïèñîê áîéöîâ è áü¸ì èõ íà ïàðû. Âîçâðàùàåì ñïèñêè ïàð + 1 ïîñëåäíèé áåç ïàðû åñëè åñòü.
*
* @param array $fighters_list
*
* @return array
*/
public static function getFightersTeams(array $fighters_list)
{
$db = new Db();
$query = sprintf("select id from users where battle = 0 and id in (%s)", implode(', ', $fighters_list));
return array_chunk($db::getColumn($query), 2);
}
/**
* Âûáèðàåì æèâûõ áîéöîâ íå ñðàæàþùèõñÿ â äàííûé ìîìåíò.
*
* @param int $tid
*
* @return array
*/
public static function getFreeFighters($tid)
{
$db = new Db();
return $db::getColumn('select uid from tournaments_users where tid = ? and death_time = 0 order by uid', [$tid]);
}
/**
* Âûáèðàåì ïîáåäèòåëåé. Ñìåùàåì ìàññèâ, ÷òîáû âîçâðàò ø¸ë ñ åäèíèöû.
*
* @param int $tid
*
* @return array
*/
public static function getWinners($tid)
{
$db = new Db();
$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]
];
}
/**
* Ïðîáóåì âûêóñèòü ïðîèãðàâøåãî â ïîñëåäíåé òóðíèðíîé áèòâå è óäàëèòü ýòó ñàìóþ áèòâó âî èçáåæàíèå.
* @return mixed
*/
public static function getLooser()
{
$query = '
select uid, battle
from
battle_users,
(select id, team_win
from battle
where
team_win > 0 and
typeBattle = 25000
order by time_over desc
limit 1) as last_battle
where
battle_users.battle = last_battle.id and
battle_users.team != last_battle.team_win and
battle_users.uid in (select uid from tournaments_users where death_time = 0)';
$query2 = 'select bu.uid from battle b
inner join battle_users bu on b.team_win != bu.team and b.id = bu.battle
inner join tournaments_users tu on bu.uid = tu.uid
where typeBattle = 25000 and death_time = 0 order by b.time_start desc limit 1';
$db = new Db;
$row = $db::getRow($query);
return $row['uid'];
}
/**
* Âûáûâøèé èç òóðíèðà ïîêèäàåò êîìíàòó è ïîëó÷àåò âðåìÿ ñìåðòè.
*
* @param int $uid
*
* @return void
*/
public static function removeFighter($uid, $winner = false)
{
if (!$uid) return;
//$winner_timer_add = $winner? 500 : 0; # Ïîñëåäíûé ÄÎËÆÅÍ áûòü ïîñëåäíèì.
$db = new Db();
$db::sql('update tournaments_users set death_time = unix_timestamp() + 500 where death_time = 0 and uid = ?', [$uid]);
self::teleport($uid, 9);
//fixme: Êëàññû íå ïîäêëþ÷àþòñÿ äðóã ê äðóãó. Íóæíî ìåíÿòü àðõèòåêòóðó èãðû. :(
Db::sql("update users_achiv set trn = trn + 1 where id = ?", [$uid]);
//(new Achievements(\user::start()))->updateCounter('trn');
}
/**
* Óçíà¸ì id òóðíèðà ïî id èãðîêà.
*
* @param int $uid
*
* @return mixed
*/
public static function getTournamentIdByUserId($uid)
{
$db = new Db();
return $db::getValue('select tid from tournaments_users where uid = ?', [$uid]);
}
/**
* Ïîïðîáóåì ñòàðòîíóòü ïîåäèíîê.
* 25000 - Óíèêàëüíûé id ïîåäèíêà ïîä òóðíèðû.
* noinc - çàïðåò íà âìåøàòåëüñòâî
* invis - íåâèäèìûé áîé
*
* @param int $uid1
* @param int $uid2
*
* @return void
*/
public static function startBattle($uid1, $uid2)
{
$db = new Db();
$check = Db::getValue('select count(*) from users where id in (?, ?) and battle = 0', [$uid1, $uid2]);
if ((int)$check !== 2) {
return;
}
$db::exec('insert into battle (city, time_start, timeout, type, invis, noinc, travmChance, typeBattle)
values (\'capitalcity\', unix_timestamp(), 60, 0, 1, 1, 0, 25000)');
$bid = $db::lastInsertId(); // ÂÀÆÍÎ!
$db::sql('update stats set team = 1, hpNow = hpAll, mpNow = mpAll where id = ?', [$uid1]);
$db::sql('update stats set team = 2, hpNow = hpAll, mpNow = mpAll where id = ?', [$uid2]);
$db::sql('update users set battle = ? where id in (?, ?)', [$bid, $uid1, $uid2]);
}
/**
* Óçíà¸ì ëîãèí ïåðñîíàæà ïî åãî id.
*
* @param int $uid
*
* @return mixed
*/
public static function uidToLogin($uid)
{
$db = new Db();
return $db::getValue('select login from users where id = ?', [$uid]);
}
/**
* Òåëåïîðò ïî êîìíàòàì.
*
* @param int $uid
* @param int $room_id
*
* @return void
*/
private static function teleport($uid, $room_id)
{
$db = new Db();
$db::sql('update users set room = ? where id = ?', [$room_id, $uid]);
}
/**
* Íåò ïðîâåðîê $message ïîòîìó ÷òî îíî âñåãäà çàäà¸òñÿ â êîäå è èãðîê íà íåãî íå âëèÿåò.
*
* @param string $message
*
* @return void
*/
public static function sysMessage($message)
{
if (!empty($message)) {
$db = new Db();
$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]);
}
}
/**
* Ãåíåðèðóåò ìíîæåñòâåííûé çàïðîñ ñðàçó íà $quantity îäíîòèïíûõ ïðåäìåòîâ â èíâåíòàðü ïîëüçîâàòåëÿ $uid.
*
* @param int $uid
* @param int $quantity
*
* @return void
*/
public static function givePrizeItems($uid, $quantity)
{
$query = 'insert into items_users (item_id, uid, data, iznosMAX, lastUPD, time_create)
values (4754, :uid, :data, 1, unix_timestamp(), unix_timestamp())';
$args = [
'uid' => $uid,
'data' => 'nosale=1|musor=1|sudba=' . self::uidToLogin($uid) . '|lvl=8|tr_s1=0|tr_s2=0|tr_s3=0|tr_s4=0'
];
$db = new Db();
$stmt = $db::prepare($query);
for ($i = 0; $i < $quantity; $i++) {
$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

@ -1,60 +0,0 @@
<?php
namespace Insallah;
class TournamentUserCheckModel
{
private $id;
private $level;
/**
* @param $id
*/
public function __construct($id)
{
$this->id = $id;
$this->level = Db::getValue('select level from users where id = ? and level between 8 and 12 and battle = 0', [$id]);
}
/**
* ïðîâåðêà óðîâíÿ, ñòîèìîñòè ýêâèïà, ïðî÷èå ïðîâåðêè, ÷òî ïåðñîíàæ ñâîáîäåí
* òàéìåð îæèäàíèÿ 30 ìèíóò
*
* @return int
*/
public function getLevel()
{
return $this->level;
}
/**
* @param int $price
* @return bool
*/
public function isEkrOverpriced($price)
{
$wearedItemsEkrPrice = Db::getValue('select sum(2price) from items_users where inOdet > 0 and uid = ?', [$this->id]);
return $wearedItemsEkrPrice > $price;
}
/**
* @param int $minExp
* @return bool
*/
public function isEnoughExperience($minExp)
{
return Db::getValue('select exp from stats where id = ?', [$this->id]) >= $minExp;
}
/**
* @return bool
*/
public function IsRestrictedToJoin()
{
$delayEffect = Db::getValue(
'select count(*) from eff_users where uid = ? and id_eff = 486 and `delete` = 0', [$this->id]
);
return (bool)$delayEffect;
}
}

View File

@ -0,0 +1,35 @@
<?php
namespace Insallah\Tournaments;
class Config
{
const IS_ENABLED = true;
const SEND_CHAT_MESSAGE = 3;
const START_TOURNAMENT = 5;
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';
const STEP_EKR = 151;
const DELAY_EFFECT_ID = 486;
const CUSTOM_BATTLE_ID = 25000;
const PRIZE_ITEM_ID = 4754;
const RETURN_ROOM = 9;
const MINIMUM_USER_LEVEL = 8;
/** Ôîðìóëà ðàññ÷¸òà ðàçðåø¸ííîé ñòîèìîñòè îäåòûõ ïðåäìåòîâ.
*
* @param $level
* @return float|int
*/
public static function ekrOverpriceFormula($level)
{
return max(($level - ($level - 1)) * self::STEP_EKR, 0);
}
}

View File

@ -0,0 +1,173 @@
<?php
namespace Insallah\Tournaments\Model;
use Insallah\Db;
use Insallah\Tournaments\Config;
class GameConnector
{
private array $u;
public function setUser(int $uid): GameConnector
{
$this->u = Db::getRow('select id, `level`, login, battle from users where id = ?', [$uid]);
return $this;
}
public function getAllowedLevel(): int
{
return $this->u['level'] >= Config::MINIMUM_USER_LEVEL && $this->u['battle'] === 0 ? $this->u['level'] : 0;
}
/**
* @return bool
*/
public function isEkrOverpriced(): bool
{
return Db::getValue('select sum(2price) from items_users where inOdet > 0 and uid = ?', [$this->u['id']])
> Config::ekrOverpriceFormula($this->u['level']);
}
/**
* @return bool
*/
public function isEnoughExperience(): bool
{
return Db::getValue('select exp from stats where id = ?', [$this->u['id']]) >= Config::MIN_EXP;
}
/**
* @return bool
*/
public function isRestrictedToJoin(): bool
{
return Db::getValue('select count(*) from eff_users where uid = ? and id_eff = ? and `delete` = 0', [
$this->u['id'], Config::DELAY_EFFECT_ID,]
) > 0;
}
/**
* Óçíà¸ì ëîãèí ïåðñîíàæà ïî åãî id.
*
* @return mixed
*/
public function uidToLogin()
{
return $this->u['login'];
}
/**
* Òåëåïîðò ïî êîìíàòàì.
*
* @param bool $out - îáðàòíûé òåëåïîðò.
*
* @return void
*/
public function teleport(bool $out = false)
{
$roomId = $out ? Config::RETURN_ROOM : Config::CUSTOM_BATTLE_ID + $this->u['level'];
Db::sql('update users set room = ? where id = ?', [$roomId, $this->u['id']]);
}
/**
* Ïîëó÷àåì ñïèñîê áîéöîâ è áü¸ì èõ íà ïàðû, ìåæäó êîòîðûìè ñòàðòóþò ïîåäèíêè 1õ1.
* noinc - çàïðåò íà âìåøàòåëüñòâî
* invis - íåâèäèìûé áîé
*
* @param array $fightersList
*
* @return void
*/
public static function startBattle(array $fightersList)
{
$teamsq = sprintf("select id from users where battle = 0 and id in (%s)", implode(', ', $fightersList));
$teams = array_chunk(Db::getColumn($teamsq), 2);
foreach ($teams as $team) {
if (count($team) !== 2) {
continue;
}
Db::exec(
'insert into battle (city, time_start, timeout, type, invis, noinc, travmChance, typeBattle)
values (\'capitalcity\', unix_timestamp(), 60, 0, 1, 1, 0, ' . Config::CUSTOM_BATTLE_ID . ')'
);
$battleId = Db::lastInsertId();
Db::sql('update stats set team = 1, zv = 0, hpNow = hpAll, mpNow = mpAll where id = ?', [$team[0]]);
Db::sql('update stats set team = 2, zv = 0, hpNow = hpAll, mpNow = mpAll where id = ?', [$team[1]]);
$query = sprintf('update users set battle = %d where id in (%d, %d)', $battleId, $team[0], $team[1]);
Db::exec($query);
}
}
/**
* Ãåíåðèðóåò ìíîæåñòâåííûé çàïðîñ ñðàçó íà $quantity îäíîòèïíûõ ïðåäìåòîâ â èíâåíòàðü ïîëüçîâàòåëÿ $uid.
*
* @param int $quantity
*
* @return void
*/
public function givePrizeItems(int $quantity)
{
$query = 'insert into items_users (item_id, uid, `data`, iznosMAX, lastUPD, time_create)
values (' . Config::PRIZE_ITEM_ID . ', :uid, :data, 1, unix_timestamp(), unix_timestamp())';
$args = [
'uid' => $this->u['id'],
'data' => 'nosale=1|musor=1|sudba=' . $this->uidToLogin() . '|lvl=8|tr_s1=0|tr_s2=0|tr_s3=0|tr_s4=0',
];
$stmt = Db::prepare($query);
for ($i = 0; $i < $quantity; $i++) {
$stmt->execute($args);
}
}
/** Ýôôåêò-îãðàíè÷èòåëü íà ó÷àñòèå â òóðíèðå.
*
* @param int $unixtime
*
* @return void
*/
public function giveDelay(int $unixtime)
{
$query = 'insert into eff_users (id_eff, uid, `name`, timeUse) select id2, ?, mname, ? from eff_main where id2 = ?';
$args = [Config::DELAY_EFFECT_ID, $this->u['id'], strtotime($unixtime)];
Db::sql($query, $args);
}
/**
* Ïðîáóåì âûêóñèòü ïðîèãðàâøåãî â ïîñëåäíåé òóðíèðíîé áèòâå è óäàëèòü ýòó ñàìóþ áèòâó âî èçáåæàíèå.
* @return mixed
*/
public static function getLooser(): int
{
$query = '
select uid
from
battle_users,
(select id, team_win
from battle
where
team_win > 0 and
typeBattle = ' . Config::CUSTOM_BATTLE_ID . '
order by time_over desc
limit 1) as last_battle
where
battle_users.battle = last_battle.id and
battle_users.team != last_battle.team_win';
return Db::getValue($query);
}
/**
* Íåò ïðîâåðîê $message ïîòîìó ÷òî îíî âñåãäà çàäà¸òñÿ â êîäå è èãðîê íà íåãî íå âëèÿåò.
*
* @param string $message
*
* @return void
*/
public static function sysMessage(string $message)
{
if (empty($message)) {
return;
}
Db::sql('insert into chat (`time`, type, `text`, new, da) values (unix_timestamp(), 6, ?, 1, 1)', [$message]);
}
}

View File

@ -0,0 +1,114 @@
<?php
namespace Insallah\Tournaments\Model;
use Insallah\Db;
class Tournament
{
private array $t;
public function __construct()
{
$this->t = Db::getRows('select * from tournaments') ?? [];
}
public function getAllStarted(): array
{
$tidList = [];
foreach ($this->t as $row) {
if ($row['start_time'] === -1) {
$tidList[] = $row['tid'];
}
}
return $tidList;
}
public function isStarted(int $tid): bool
{
foreach ($this->t as $row) {
if ($row['start_time'] === -1 && $row['tid'] === $tid) {
return true;
}
}
return false;
}
public function getList(): string
{
$list = '';
$tournamentMembersId = new User();
foreach ($this->t as $row) {
$time = $row['start_time'] === -1 ? 'Òóðíèð óæå íà÷àëñÿ!' : date('G:i', $row['start_time']);
$members = [];
foreach ($tournamentMembersId->getAlive($row['tid']) as $member) {
$members[] = (new GameConnector())->setUser($member)->uidToLogin();
}
$list .= sprintf(
"<li>Òóðíèð äëÿ %d óðîâíåé.<br>Âðåìÿ ïîäà÷è çàÿâêè: %s<br>Ó÷àñòíèêè: %s</li>",
$row['tid'],
$time,
implode(', ', $members)
);
}
return $list ? "<div><strong>Àêòèâíûå òóðíèðû.</strong><br><ul>$list</ul></div>" : '';
}
public function getOne(int $tid): string
{
$str = '';
$tournamentMembersId = new User();
foreach ($this->t as $row) {
if ($this->t['tid'] === $tid) {
$time = $row['start_time'] === -1 ? 'Òóðíèð óæå íà÷àëñÿ!' : date('G:i', $row['start_time']);
$members = [];
foreach ($tournamentMembersId->getAlive($row['tid']) as $member) {
$members[] = (new GameConnector())->setUser($member)->uidToLogin();
}
$str = sprintf(
"<div>Òóðíèð äëÿ %d óðîâíåé.<br>Âðåìÿ ïîäà÷è çàÿâêè: %s<br>Ó÷àñòíèêè: %s</div>",
$row['tid'],
$time,
implode(', ', $members)
);
}
}
return $str;
}
/**
* Ñîçäàíèå íîâîãî òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function create(int $tid)
{
Db::sql('insert into tournaments (tid) values (?)', [$tid]);
}
/**
* Ñòàðò òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function start(int $tid)
{
Db::sql('update tournaments set start_time = -1 where tid = ?', [$tid]);
}
/**
* ×èñòèì áàçû îò ïðîøåäøåãî òóðíèðà.
*
* @param int $tid
*
* @return void
*/
public static function destroy(int $tid)
{
Db::sql('delete from tournaments where tid = ?', [$tid]);
}
}

View File

@ -0,0 +1,128 @@
<?php
namespace Insallah\Tournaments\Model;
use Insallah\Db;
class User
{
private array $u;
private int $waitingUsers = 0;
public function __construct()
{
$this->u = Db::getRows('select * from tournaments_users');
}
/**
* Ñ÷èòàåì ñêîëüêî èãðîêîâ æäóò â çàÿâêå íà òóðíèð.
*
* @param int $tid
*
* @return int
*/
public function getWaitingQuantity(int $tid): int
{
foreach ($this->u as $row) {
if ($row['tid'] === $tid) {
$this->addWaitingUser();
}
}
return $this->waitingUsers;
}
public function addWaitingUser()
{
$this->waitingUsers++;
}
/**
* Èãðîê ïðèñîåäèíÿåòñÿ ê òóðíèðó è òåëåïîðòèðóåòñÿ â òóðíèðíóþ êîìíàòó.
*
* @param int $uid
* @param int $tid
*
* @return void
*/
public function joinTournament(int $uid, int $tid)
{
Db::sql('insert into tournaments_users (tid, uid) values (?, ?)', [$tid, $uid]);
(new GameConnector())->setUser($uid)->teleport();
}
/**
* Âûáèðàåì æèâûõ áîéöîâ íå ñðàæàþùèõñÿ â äàííûé ìîìåíò.
*
* @param int $tid
* @param bool $shuffle - óñòàíîâèòü true åñëè íóæíî ïåðåòàñîâàòü ìàññèâ.
*
* @return array
*/
public function getAlive(int $tid, bool $shuffle = false): array
{
$arr = [];
foreach ($this->u as $row) {
if ($row['tid'] === $tid && $row['death_time'] === 0) {
$arr[] = $row['uid'];
}
}
if ($shuffle) {
shuffle($arr);
}
return $arr;
}
/**
* Âûáèðàåì ïîáåäèòåëåé.
*
* @param int $tid
*
* @return array
*/
public function getWinners(int $tid): array
{
$users = [];
$dt = [];
foreach ($this->u as $item) {
if ($item['tid'] === $tid) {
$users[]['uid'] = $item['uid'];
$users[]['death_time'] = $item['death_time'];
}
}
foreach ($users as $k => $v) {
$dt[$k] = $v['death_time'];
}
array_multisort($dt, SORT_DESC, $users);
return [
1 => $users[0],
2 => $users[1],
3 => $users[2]
];
}
/**
* Âûáûâøèé èç òóðíèðà ïîêèäàåò êîìíàòó è ïîëó÷àåò âðåìÿ ñìåðòè.
*
* @param int $uid
*
* @return void
*/
public static function remove(int $uid)
{
Db::sql('update tournaments_users set death_time = unix_timestamp() where death_time = 0 and uid = ?', [$uid]);
(new GameConnector())->setUser($uid)->teleport(true);
}
/**
* Óçíà¸ì id òóðíèðà ïî id èãðîêà.
*
* @param int $uid
*
* @return mixed
*/
public static function getTournamentIdByUserId(int $uid): int
{
return Db::getValue('select tid from tournaments_users where uid = ?', [$uid]);
}
}

View File

@ -0,0 +1,104 @@
<?php
namespace Insallah\Tournaments;
class Tournament
{
/**
* Ïðîâåðÿåì ìîæåò ëè èãðîê ó÷àâñòâîâàòü â òóðíèðå è ëèáî ïðèñîåäèíÿåì åãî, ëèáî îáëàìûâàåì.
*
* @param int $uid
*
* @return void
*/
public function join(int $uid)
{
/** Âîçâðàùàåò level, èëè 0 åñëè ïðîâàëåíû ïðîâåðêè. */
$checks = new Model\GameConnector();
$tournament = new Model\Tournament();
$userLevel = $checks->setUser($uid)->getAllowedLevel();
if (
$userLevel === 0 ||
$checks->isEkrOverpriced() ||
!$checks->isEnoughExperience() ||
$checks->isRestrictedToJoin() ||
$tournament->isStarted($uid)
) {
return;
}
$user = new Model\User();
if (empty($user->getWaitingQuantity($userLevel))) {
Model\Tournament::create($userLevel);
}
$user->joinTournament($uid, $userLevel);
$user->addWaitingUser();
if ($user->getWaitingQuantity($userLevel) == Config::SEND_CHAT_MESSAGE) {
Model\GameConnector::sysMessage(sprintf(Config::CHAT_MESSAGE, $userLevel));
}
if ($user->getWaitingQuantity($userLevel) == Config::START_TOURNAMENT) {
Model\Tournament::start($userLevel);
}
}
/**
* Ïðîâåðêà äëÿ êðîíà\êîíôèãà. Âûáèâàåò ïðîèãðàâøèõ è ïåðåçàïóñêàåò ïîåäèíêè âî âñåõ òóðíèðàõ.
* @return void
*/
public static function startAllBattles()
{
if (!Config::IS_ENABLED) {
return;
}
$tournamentlevels = new Model\Tournament();
$alivefighters = new Model\User();
Model\User::remove(Model\GameConnector::getLooser());
foreach ($tournamentlevels->getAllStarted() as $level) {
$count = count($alivefighters->getAlive($level, true));
if ($count > 1) {
Model\GameConnector::startBattle($alivefighters->getAlive($level, true));
} elseif ($count === 1) {
Model\User::remove($alivefighters->getAlive($level, true)[0]);
self::victory($level);
}
}
}
/**
* Íàãðàæäàåì ïîáåäèòåëåé òóðíèðà, ÷èñòèì áàçó.
*
* @param int $tid
*
* @return void
*/
private static function victory(int $tid)
{
$u = new Model\User();
$uid = new Model\GameConnector();
sleep(1);
$uid->setUser($u->getWinners($tid)[1])->givePrizeItems(Config::PRIZE1);
$uid->setUser($u->getWinners($tid)[2])->givePrizeItems(Config::PRIZE2);
$uid->setUser($u->getWinners($tid)[3])->givePrizeItems(Config::PRIZE3);
sleep(1);
$uid->setUser($u->getWinners($tid)[1])->giveDelay(Config::DELAY1);
$uid->setUser($u->getWinners($tid)[2])->giveDelay(Config::DELAY2);
$uid->setUser($u->getWinners($tid)[3])->giveDelay(Config::DELAY3);
sleep(1);
Model\GameConnector::sysMessage(
sprintf(
Config::VICTORY_MESSAGE,
$tid,
$uid->setUser($u->getWinners($tid)[1])->uidToLogin(),
$uid->setUser($u->getWinners($tid)[2])->uidToLogin(),
$uid->setUser($u->getWinners($tid)[3])->uidToLogin()
)
);
sleep(3);
Model\Tournament::destroy($tid);
}
}

View File

@ -0,0 +1,54 @@
<?php
namespace Insallah\Tournaments\View;
use Insallah\Tournaments\Config;
use Insallah\Tournaments\Model\GameConnector;
use Insallah\Tournaments\Model\Tournament;
use Insallah\Tournaments\Model\User;
class TList
{
private string $str;
public function __construct($user)
{
if (!Config::IS_ENABLED) {
$this->str = '<div><strong style="color: crimson;">Â äàííûé ìîìåíò òóðíèðû íå ïðîâîäÿòñÿ!</strong></div>';
return;
}
$tournamentstatus = new Tournament();
$this->str = '<div>
<strong style="color: crimson;">Âíèìàíèå!</strong>
<ul>
<li>Ïðèñîåäèíÿÿñü ê òóðíèðó ïîêèíóòü çàÿâêó <u>íåâîçìîæíî</u>!</li>';
if ((new GameConnector())->setUser($user->info['id'])->isEkrOverpriced()) {
$this->str .= '<li>Ñòîèìîñòü ïðåäìåòîâ, îäåòûõ íà âàñ íå äîëæíà
ïðåâûøàòü ' . Config::ekrOverpriceFormula($user->info['level']) . ' åâðîêðåäèòîâ.
</li>';
}
if ($user->info['exp'] < Config::MIN_EXP) {
$this->str .= '<li>Ó âàñ äîëæíî áûòü íå ìåíåå ' . Config::MIN_EXP . ' îïûòà.</li>';
}
$this->str .= '<li>Òóðíèð íà÷í¸òñÿ, êîãäà â çàÿâêå
íàáåð¸òñÿ ' . Config::START_TOURNAMENT . ' ÷åëîâåê.</li>';
$this->str .= '<li>Èãðîêè çàíÿâøèå 1, 2 è 3 ìåñòà ïîëó÷àò ' . Config::PRIZE1 . ', ' . Config::PRIZE2 . ',
' . Config::PRIZE3 . ' Ðåëèêâèé Àíãåëà, à òàê æå çàäåðæêè íà ó÷àñòèå â òóðíèðå
12 ÷àñîâ, 6 è 3 ÷àñà ñîîòâåòñòâåííî!</li>';
$this->str .= '</ul></div>';
$this->str .= $tournamentstatus->getList();
if (!User::getTournamentIdByUserId($user->info['id']) || !$tournamentstatus->isStarted($user->info['level'])) {
$this->str .= '<form method="post">
<input type="submit" name="tournament_start" value="Ïðèíÿòü ó÷àñòèå â òóðíèðå">
<input type="hidden" name="key" value="' . $_SESSION['bypass'] . '">
</form>';
} else {
$this->str .= 'Âû ó÷àâñòâóåòå.';
}
}
public function __toString()
{
return $this->str;
}
}

View File

@ -1,40 +1,5 @@
<?php <?php
use Insallah\Db, Insallah\TournamentModel; use Insallah\Tournaments\Model\Tournament;
$db = new Db();
$members = [];
$user = $db::getRow('select id, room, level, login from users where login = ?', [$_COOKIE['login']]);
$tournamentStartTime = $db::getValue('select start_time from tournaments where tid = ?', [$user['level']]);
foreach (TournamentModel::getFreeFighters($user['level']) as $member) {
$members[] = TournamentModel::uidToLogin($member);
}
?>
<strong>Òóðíèð äëÿ <?= $user['level'] ?> óðîâíåé.</strong><br>
<?php
if (empty($members) || empty($tournamentStartTime)): ?>
Òóðíèðà - íåò. Ó÷àñòíèêîâ - íåò. Êàê âû ñþäà çàáðåëè? Íå-åò, ñâîèì õîäîì âû îòñþäà íå âûáåðåòåñü!
<?php
exit(); endif; ?>
<?php
if ((int)$tournamentStartTime === -1): ?>
Òóðíèð íà÷àëñÿ!
<?php
else: ?>
Âðåìÿ ïîäà÷è çàÿâêè: <?= date('G:i', $tournamentStartTime) ?>
<?php
if (date('j', time()) !== date('j', $tournamentStartTime)): ?>
(íå ñåãîäíÿ!)
<?php
endif; ?>
<?php
endif; ?>
<br>
<?= $user['login'] ?><br>
Ó÷àñòíèêè: <?= implode(', ', $members) ?>
echo (new Tournament())->getOne($u->info['level']);