game/_incl_data/class/Insallah/Tournaments/Model/GameConnector.php

178 lines
5.7 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?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;
}
$cmsg = new \ChatMessage();
$cmsg->setDa(1);
$cmsg->setType(6);
$cmsg->setText($message);
(new \Chat())->sendMsg($cmsg);
}
}