Основные классы переехали на обёртку PDO. Плановое №16.

This commit is contained in:
lopar 2021-01-28 23:05:34 +02:00
parent 0099c235a7
commit 8402912098
22 changed files with 284 additions and 1940 deletions

View File

@ -17,7 +17,7 @@ class Bank
public $user_id; public $user_id;
private $money; private $money;
private $user; private $user;
private $db; private static $db;
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
@ -31,11 +31,11 @@ class Bank
'clanRegister' => 'Оплата стоимости регистрации клана.', 'clanRegister' => 'Оплата стоимости регистрации клана.',
]; ];
public function __construct($row) public function __construct(int $user_id)
{ {
$this->db = new DBPDO(); self::$db = DBPDO::INIT();
$bank_row = $this->db->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $row); $bank_row = self::$db->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id);
$this->user = $this->db->fetch('SELECT money FROM users WHERE id = ?', $row); $this->user = self::$db->fetch('SELECT money FROM users WHERE id = ?', $user_id);
foreach ($this as $key => $value) { foreach ($this as $key => $value) {
if (isset($bank_row[$key])) { if (isset($bank_row[$key])) {
$this->$key = $bank_row[$key]; $this->$key = $bank_row[$key];
@ -98,7 +98,7 @@ class Bank
*/ */
public function sendMoney(int $receiver, int $amount): int public function sendMoney(int $receiver, int $amount): int
{ {
$receiverWallet = $this->db->fetch('SELECT money FROM bank WHERE user_id = ?', $receiver); $receiverWallet = self::$db->fetch('SELECT money FROM bank WHERE user_id = ?', $receiver);
if ($amount <= 0) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
@ -134,7 +134,7 @@ class Bank
if ($amount <= 0) { if ($amount <= 0) {
throw new GameException(self::ERROR_WRONG_AMOUNT); throw new GameException(self::ERROR_WRONG_AMOUNT);
} }
$wallet = $this->db->fetch('SELECT money FROM users WHERE id = ?', $this->user_id); $wallet = self::$db->fetch('SELECT money FROM users WHERE id = ?', $this->user_id);
if ($wallet->money < $amount) { if ($wallet->money < $amount) {
throw new GameException(self::ERROR_NO_MONEY_IN_WALLET); throw new GameException(self::ERROR_NO_MONEY_IN_WALLET);
} }
@ -195,10 +195,9 @@ class Bank
public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void
{ {
try { try {
$db = new DBPDO(); self::$db->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]);
$db->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]);
if ($operationType) { if ($operationType) {
(new Bank($user_id))->bankLogs(0, $amount, $operationType); GameLogs::addBankLog(0, 0, $amount, $operationType, self::LOG[$operationType]);
} }
} catch (Throwable $e) { } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
@ -217,8 +216,7 @@ class Bank
public static function setWalletMoney(int $amount, int $user_id): void public static function setWalletMoney(int $amount, int $user_id): void
{ {
try { try {
$db = new DBPDO(); self::$db->execute('UPDATE users SET money = ? WHERE id = ?', [$amount, $user_id]);
$db->execute('UPDATE users SET money = ? WHERE id = ?', [$amount, $user_id]);
} catch (Throwable $e) { } catch (Throwable $e) {
echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})";
} }

View File

@ -13,13 +13,20 @@ class DBPDO
public $pdo; public $pdo;
private $error; private $error;
private static $_instance = null;
function __construct() function __construct()
{ {
$this->connect(); $this->connect();
} }
public static function INIT(): DBPDO
{
if (!self::$_instance) {
self::$_instance = new DBPDO();
}
return self::$_instance;
}
function prep_query($query) function prep_query($query)
{ {
@ -102,6 +109,39 @@ class DBPDO
return $results; return $results;
} }
function ofetch($query, $values = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
return $stmt->fetch(PDO::FETCH_OBJ);
}
function ofetchAll($query, $values = null, $key = null)
{
if ($values == null) {
$values = array();
} else if (!is_array($values)) {
$values = array($values);
}
$stmt = $this->execute($query, $values);
$results = $stmt->fetchAll(PDO::FETCH_OBJ);
// Allows the user to retrieve results using a
// column from the results as a key for the array
if ($key != null && $results[0][$key]) {
$keyed_results = array();
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
}
$results = $keyed_results;
}
return $results;
}
function lastInsertId() function lastInsertId()
{ {
return $this->pdo->lastInsertId(); return $this->pdo->lastInsertId();

View File

@ -4,49 +4,45 @@
* Date: 06.07.2020 * Date: 06.07.2020
* Time: 22:41 * Time: 22:41
*/ */
namespace Battles; namespace Battles;
use db;
use Krugozor\Database\Mysql\Exception; use Battles\Database\DBPDO;
class DressedItems class DressedItems
{ {
private $DB;
private $DBSUM;
private $USERID; private $USERID;
private $dressedItem; private $dressedItem;
private static $db;
/** /**
* DressedItems constructor. * DressedItems constructor.
* * @param int $user_id ID игрока.
* @param $user_id - ID игрока.
*/ */
public function __construct($user_id) public function __construct(int $user_id)
{ {
self::$db = DBPDO::INIT();
$this->USERID = $user_id; $this->USERID = $user_id;
} }
private function getDressedItems()
{
try {
$this->DB = db::c()->query('SELECT * FROM inventory WHERE owner_id = ?i AND dressed_slot > 0', $this->USERID);
} catch (\Exception $e) {
echo '<div class="debug">Не прогрузилась таблица inventory (*) для класса DressedItems.</div>';
}
}
private static function getDressedItemById($item_id)
{
return db::c()->query('SELECT * FROM inventory WHERE item_id = ?i AND dressed_slot > 0', $item_id)->fetch_assoc();
}
public static function getDressedItemBySlot($itemSlot, $ownerId) public static function getDressedItemBySlot($itemSlot, $ownerId)
{ {
return db::c()->query('SELECT * FROM battles.inventory WHERE owner_id = ?i AND dressed_slot = ?i', $ownerId, $itemSlot)->fetch_assoc(); return self::$db->fetch('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]);
} }
private function getBonusesFromDressedItems() public function getItemsInSlots()
{
$items = self::$db->fetchALL('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot > 0', $this->USERID);
$i = 0;
while ($i < count($items)) {
$this->dressedItem[$items['dressed_slot']] = $items;
$i++;
}
return $this->dressedItem;
}
private function getBonuses(): array
{ {
try {
$query = <<<SQL $query = <<<SQL
SELECT SUM(add_strength) as sum_strength, SELECT SUM(add_strength) as sum_strength,
SUM(add_dexterity) as sum_dexterity, SUM(add_dexterity) as sum_dexterity,
@ -59,74 +55,62 @@ SELECT SUM(add_strength) as sum_strength,
SUM(add_criticals) as sum_criticals, SUM(add_criticals) as sum_criticals,
SUM(add_min_physical_damage) as sum_min_phys_damage, SUM(add_min_physical_damage) as sum_min_phys_damage,
SUM(add_max_physical_damage) as sum_max_phys_damage SUM(add_max_physical_damage) as sum_max_phys_damage
FROM inventory WHERE owner_id = ?i AND dressed_slot > 0 FROM inventory WHERE owner_id = ? AND dressed_slot > 0
SQL; SQL;
$this->DBSUM = db::c()->query($query, $this->USERID)->fetch_assoc(); return self::$db->fetch($query, $this->USERID);
} catch (\Exception $e) {
echo '<div class="debug">Не прогрузилась таблица inventory (SUM) для класса DressedItems:' . $e . '</div>';
}
} }
public function getItemsInSlots() public function getStrengthBonus(): int
{
if (!$this->DB) {
self::getDressedItems();
}
while ($row = $this->DB->fetch_assoc()) {
$this->dressedItem[$row['dressed_slot']] = $row;
}
return $this->dressedItem;
}
private function getBonuses()
{
if (!$this->DBSUM) {
self::getBonusesFromDressedItems();
}
return $this->DBSUM;
}
public function getStrengthBonus()
{ {
return self::getBonuses()['sum_strength']; return self::getBonuses()['sum_strength'];
} }
public function getDexterityBonus()
public function getDexterityBonus(): int
{ {
return self::getBonuses()['sum_dexterity']; return self::getBonuses()['sum_dexterity'];
} }
public function getIntuitionBonus()
public function getIntuitionBonus(): int
{ {
return self::getBonuses()['sum_intuition']; return self::getBonuses()['sum_intuition'];
} }
public function getEnduranceBonus()
public function getEnduranceBonus(): int
{ {
return self::getBonuses()['sum_endurance']; return self::getBonuses()['sum_endurance'];
} }
public function getIntelliganceBonus()
public function getIntelliganceBonus(): int
{ {
return self::getBonuses()['sum_intelligence']; return self::getBonuses()['sum_intelligence'];
} }
public function getWisdomBonus()
public function getWisdomBonus(): int
{ {
return self::getBonuses()['sum_wisdom']; return self::getBonuses()['sum_wisdom'];
} }
public function getAccuracyBonus()
public function getAccuracyBonus(): int
{ {
return self::getBonuses()['sum_accuracy'] ?? 0; return self::getBonuses()['sum_accuracy'] ?? 0;
} }
public function getEvasionBonus()
public function getEvasionBonus(): int
{ {
return self::getBonuses()['sum_evasion'] ?? 0; return self::getBonuses()['sum_evasion'] ?? 0;
} }
public function getCriticalsBonus()
public function getCriticalsBonus(): int
{ {
return self::getBonuses()['sum_criticals'] ?? 0; return self::getBonuses()['sum_criticals'] ?? 0;
} }
public function getMinPhysDamage()
public function getMinPhysDamage(): int
{ {
return self::getBonuses()['sum_min_phys_damage']; return self::getBonuses()['sum_min_phys_damage'];
} }
public function getMaxPhysDamage()
public function getMaxPhysDamage(): int
{ {
return self::getBonuses()['sum_max_phys_damage']; return self::getBonuses()['sum_max_phys_damage'];
} }
@ -134,23 +118,13 @@ SQL;
/** /**
* Снимает с предмета статус одетого на персонажа в определённом слоте персонажа. * Снимает с предмета статус одетого на персонажа в определённом слоте персонажа.
* @param $slot_id - номер слота. * @param $slot_id - номер слота.
*
* @throws Exception
*/ */
public function undressItem($slot_id) public function undressItem($slot_id)
{ {
self::getItemsInSlots(); self::getItemsInSlots();
// Проверяем, что используется один из 12 слотов и наличие предмета в слоте. // Проверяем, что используется один из 12 слотов и наличие предмета в слоте.
if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem[$slot_id]) { if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem[$slot_id]) {
db::c()->query('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ?i AND owner_id = ?i', $slot_id, $this->USERID); self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$slot_id, $this->USERID]);
}
}
public function slotStatus($slot_id)
{
self::getItemsInSlots();
if ($this->dressedItem[$slot_id]) {
} }
} }
} }

View File

@ -30,20 +30,4 @@ class InventoryItem extends Item
parent::printImage(); parent::printImage();
} }
} }
/**
* Для кнопок управления под картинкой предмета в зависимости от ситуации.
*/
public function printControls()
{
//FIXME Сменить заглушку на нормальную функцию!!
echo <<<BTN
<p><button class="button danger" onclick="location.href='/admin.php'">Выбросить</button>
BTN;
}
public function getId()
{
return $this->item_id;
}
} }

View File

@ -38,8 +38,9 @@ abstract class Item
public const ITEM_TYPE_RING = 9; public const ITEM_TYPE_RING = 9;
public const ITEM_TYPE_AMULET = 10; public const ITEM_TYPE_AMULET = 10;
public const ITEM_TYPE_CONSUMABLE = 20; public const ITEM_TYPE_CONSUMABLE = 20;
const ITEM_TYPE_OTHER = 50; public const ITEM_TYPE_OTHER = 50;
const ITEM_TYPE_TRASH = 100; public const ITEM_TYPE_TRASH = 100;
private $typename;
/** /**
* Item constructor. * Item constructor.
@ -102,7 +103,7 @@ abstract class Item
IMG; IMG;
} }
protected function wrap($number) protected function wrap(int $number):string
{ {
if ($number > 0) { if ($number > 0) {
return ": <b>" . $number . "</b>"; return ": <b>" . $number . "</b>";
@ -113,6 +114,9 @@ IMG;
protected function printAllInfo() protected function printAllInfo()
{ {
$lines = [
"Долговечность" => $this->durability,
];
echo "<b>" . $this->name . "</b> (Масса: " . $this->weight . ")"; echo "<b>" . $this->name . "</b> (Масса: " . $this->weight . ")";
if ($this->durability) { if ($this->durability) {
echo "<br> Долговечность: " . $this->durability; echo "<br> Долговечность: " . $this->durability;

View File

@ -2,52 +2,49 @@
# Date: 16.09.2020 (08:23) # Date: 16.09.2020 (08:23)
// Магия лечения травм // Магия лечения травм
namespace Battles\Magic; namespace Battles\Magic;
use Battles\UserEffects;
use Battles\User; use Battles\UserEffects, Battles\Database\DBPDO, Battles\User;
use db;
use Krugozor\Database\Mysql\Exception;
class CureInjury extends Magic class CureInjury extends Magic
{ {
private $target; private $target;
private $login;
use UserEffects; use UserEffects;
/** /**
* Магия лечения травм. Если у персонажа несколько травм, лечится самая тяжёлая. * Магия лечения травм. Если у персонажа несколько травм, лечится самая тяжёлая.
* @param $target - кого лечим. * @param int $target - кого лечим.
* @param $injuryType - тип травмы, которую лечим. 11 лёгкая, 12 средняя, 13 тяжёлая, 14 неизлечимая. * @param int $injuryType - тип травмы, которую лечим. 11 лёгкая, 12 средняя, 13 тяжёлая, 14 неизлечимая, 15 все травмы.
* @throws Exception
*/ */
public function __construct($target, $injuryType) public function __construct(int $target, int $injuryType)
{ {
$db = DBPDO::INIT();
$this->target = $target; $this->target = $target;
if ($target && $this->isUsable()) { if (!$this->isUsable()) {
$injury = db::c()->query('SELECT effect_id, type, name FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ?i ORDER BY type DESC LIMIT 1', $target)->fetch_object(); return $this->status;
$targetName = $this->target->login; }
if (in_array($injury->effect_id, [11, 12, 13, 14]) && $injuryType >= $injury->type) { $ok = null;
db::c()->query('DELETE FROM users_effects WHERE effect_id = ?i', $injury->effect_id); $injury = $db->ofetch('SELECT effect_id, type, name FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ? ORDER BY type DESC LIMIT 1', $target);
if (in_array($injury->type, [11, 12, 13, 14]) && $injuryType >= $injury->type) {
$db->execute('DELETE FROM users_effects WHERE effect_id = ?', $injury->effect_id);
if (empty($injury->name) || $injury->name == 'Неизвестный эффект') { if (empty($injury->name) || $injury->name == 'Неизвестный эффект') {
$injuryName = self::$effectName[$injury->type]; $injuryName = self::$effectName[$injury->type];
} else { } else {
$injuryName = $injury->name; $injuryName = $injury->name;
} }
return "Вы вылечили повреждение ${injuryName} персонажу ${targetName}."; $ok = "Вы вылечили повреждение ${injuryName} персонажу $this->login.";
} elseif ($injury->effect_id && $injuryType == 15) { } elseif ($injury->effect_id && $injuryType == 15) {
db::c()->query('DELETE FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ?i', $target); $db->execute('DELETE FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ?', $target);
return "Вы вылечили все повреждения персонажу ${targetName}."; $ok = "Вы вылечили все повреждения персонажу $this->login.";
} else {
return false;
}
} else {
return $this->status;
} }
return $ok;
} }
/** /**
* Проверки на успех. * Проверки на успех.
* @return bool * @return bool
*/ */
private function isUsable() private function isUsable(): bool
{ {
$caster = new User($_SESSION['uid']); $caster = new User($_SESSION['uid']);
if ($this->target == $_SESSION['uid']) { if ($this->target == $_SESSION['uid']) {
@ -55,6 +52,7 @@ class CureInjury extends Magic
} else { } else {
$this->target = new User($this->target); $this->target = new User($this->target);
} }
$this->login = $this->target->login;
return ($this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isNotInBattle($caster)); return ($this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isNotInBattle($caster));
} }
} }

View File

@ -2,7 +2,8 @@
// Магия восстановления здоровья // Магия восстановления здоровья
use Battles\Magic\Magic; use Battles\Magic\Magic;
use Battles\User; use Battles\User;
use Krugozor\Database\Mysql\Exception; use Battles\Database\DBPDO;
class Healing extends Magic class Healing extends Magic
{ {
private $target; private $target;
@ -13,14 +14,14 @@ class Healing extends Magic
* @param $target - кого лечим. * @param $target - кого лечим.
* @param $power - на сколько лечим. * @param $power - на сколько лечим.
* @param null $isPercentage - если включён, считает $power в процентах, иначе, по-умолчанию просто как число. * @param null $isPercentage - если включён, считает $power в процентах, иначе, по-умолчанию просто как число.
*
* @throws Exception
*/ */
public function __construct($target, $power, $isPercentage = null) public function __construct($target, $power, $isPercentage = null)
{ {
$this->magicPower = $power; $this->magicPower = $power;
$this->target = $target; $this->target = $target;
if ($target && $this->isUsable()) { if (!$this->isUsable()) {
return $this->status;
}
if ($isPercentage) { if ($isPercentage) {
$healHealthAmount = $this->target->health + $this->target->maxHealth / 100 * $this->magicPower; $healHealthAmount = $this->target->health + $this->target->maxHealth / 100 * $this->magicPower;
} else { } else {
@ -29,12 +30,9 @@ class Healing extends Magic
if ($healHealthAmount > $this->target->maxHealth) { if ($healHealthAmount > $this->target->maxHealth) {
$healHealthAmount = $this->target->maxHealth; $healHealthAmount = $this->target->maxHealth;
} }
db::c()->query('UPDATE users SET health = ?i WHERE id = ?i', $healHealthAmount, $this->target->id); DBPDO::INIT()->execute('UPDATE users SET health = ? WHERE id = ?', [$healHealthAmount, $this->target->id]);
$targetName = $this->target->login; $targetName = $this->target->login;
return "Вы восстановили ${healHealthAmount} здоровья персонажу ${targetName}."; return "Вы восстановили ${healHealthAmount} здоровья персонажу ${targetName}.";
} else {
return $this->status;
}
} }
/** /**
@ -49,6 +47,6 @@ class Healing extends Magic
} else { } else {
$this->target = new User($this->target); $this->target = new User($this->target);
} }
return $this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->skillCheck($caster); return $this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isSuccess($caster);
} }
} }

View File

@ -52,7 +52,7 @@ class Magic
* *
* @return bool * @return bool
*/ */
protected function skillCheck($caster, int $difficulty = 40):bool protected function isSuccess($caster, int $difficulty = 40):bool
{ {
# 40 - потолок стата. # 40 - потолок стата.
if ($difficulty > 40) { if ($difficulty > 40) {

View File

@ -3,12 +3,10 @@
namespace Battles\Magic; namespace Battles\Magic;
use Battles\Database\DBPDO;
use Battles\DressedItems; use Battles\DressedItems;
use Battles\Item; use Battles\Item;
use Battles\User; use Battles\User;
use Krugozor\Database\Mysql\Exception;
use db;
class Sharpen extends Magic class Sharpen extends Magic
{ {
@ -20,12 +18,13 @@ class Sharpen extends Magic
* @param int $sharpenStrength * @param int $sharpenStrength
* @param int $magicDifficulty * @param int $magicDifficulty
* *
* @throws Exception
*/ */
public function __construct(int $sharpenStrength, int $magicDifficulty) public function __construct(int $sharpenStrength, int $magicDifficulty)
{ {
$this->magicDifficulty = $magicDifficulty; $this->magicDifficulty = $magicDifficulty;
if ($this->isUsable()) { if (!$this->isUsable()) {
return $this->status;
}
$item = DressedItems::getDressedItemBySlot(Item::ITEM_TYPE_WEAPON, $_SESSION['uid']); $item = DressedItems::getDressedItemBySlot(Item::ITEM_TYPE_WEAPON, $_SESSION['uid']);
// Проверяем, что в названии предмета нет цифр и плюсов. // Проверяем, что в названии предмета нет цифр и плюсов.
if (preg_match('/[\W\S]+\+\[?[\d]]?/', $item['name'])) { if (preg_match('/[\W\S]+\+\[?[\d]]?/', $item['name'])) {
@ -35,15 +34,13 @@ class Sharpen extends Magic
$newMaxPhysicalDamage = $item['add_max_physical_damage'] + $sharpenStrength; $newMaxPhysicalDamage = $item['add_max_physical_damage'] + $sharpenStrength;
$newItemName = $item['name'] . " [+$sharpenStrength]"; $newItemName = $item['name'] . " [+$sharpenStrength]";
db::c()->query('UPDATE battles.inventory SET name = "?s", add_min_physical_damage = "?s", add_max_physical_damage = "?s" WHERE item_id = ?i ', $newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item['item_id']); DBPDO::INIT()->execute('UPDATE battles.inventory SET name = ?, add_min_physical_damage = ?, add_max_physical_damage = ? WHERE item_id = ? ', [$newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item['item_id']]);
return "У вас получилось изготовить предмет $newItemName!"; return "У вас получилось изготовить предмет $newItemName!";
} else {
return $this->status;
}
} }
private function isUsable(): bool private function isUsable(): bool
{ {
$caster = new User($_SESSION['uid']); $caster = new User($_SESSION['uid']);
return $this->isNotInBattle($caster) && $this->skillCheck($caster, $this->magicDifficulty); return $this->isNotInBattle($caster) && $this->isSuccess($caster, $this->magicDifficulty);
} }
} }

View File

@ -1,41 +0,0 @@
<?php
namespace Battles\Magic;
use db;
class attack
{
private $target_user;
private $caster;
private function __construct($target_user_id)
{
if (!$this->caster) {
$this->caster = db::c()->query('SELECT * FROM `users` WHERE `id` = ?i', $_SESSION['uid']);
}
if (!$this->target_user) {
$this->target_user = db::c()->query('SELECT * FROM `users` WHERE `id` = ?i', $target_user_id);
}
if ($this->checks() == 1) {
return 'Done!';
}
}
private function checks()
{
if ($this->caster['battle']) {
return 'Не в бою...';
}
else {
return 1;
}
}
public static function id($playerId)
{
return new self($playerId);
}
}

View File

@ -4,33 +4,34 @@
* Date: 05.07.2020 * Date: 05.07.2020
* Time: 23:32 * Time: 23:32
*/ */
namespace Battles\Models; namespace Battles\Models;
use Battles\Database\DBPDO;
class EffectsModel class EffectsModel
{ {
protected $DB; protected $DB;
const EFFECT_HIDEUSERINFO = 5; // Обезлик const EFFECT_HIDEUSERINFO = 5; // Обезлик
public function __construct(int $user_id) {
try {
$this->DB = \db::c()->query('SELECT * FROM users_effects WHERE owner_id = ?i', $user_id);
} catch (\Throwable $e) {echo '<div class="debug">class EffectsModel: Не могу подключиться к таблице effects!</div>';}
}
private function getEffects($user_id) public function __construct(int $user_id)
{ {
$this->DB = DBPDO::INIT()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id);
} }
/** /**
* Проверка обезличен ли персонаж. * Проверка обезличен ли персонаж.
* @return int date() до конца эффекта или 0. * @return int date() до конца эффекта или 0.
*/ */
public function getHideUserInfoStatus() public function getHideUserInfoStatus(): int
{ {
if ($this->DB) { if ($this->DB) {
while ($row = $this->DB->fetch_object()) { $i = 0;
if ($row->type == self::EFFECT_HIDEUSERINFO) { while ($i < count($this->DB)) {
return $row->time; if ($this->DB->type == self::EFFECT_HIDEUSERINFO) {
return $this->DB->remaining_time;
} }
$i++;
} }
} }
return 0; return 0;

View File

@ -5,7 +5,8 @@
* Time: 13:17 * Time: 13:17
*/ */
namespace Battles\Models; namespace Battles\Models;
use Exceptions\GameException;
use Battles\Database\DBPDO;
class PresentsModel class PresentsModel
{ {
@ -14,7 +15,7 @@ class PresentsModel
public function __construct(int $user_id) public function __construct(int $user_id)
{ {
if (!$this->DB) { if (!$this->DB) {
$this->DB = \db::c()->query('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?i', $user_id); $this->DB = DBPDO::INIT()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id);
} }
} }
@ -22,9 +23,4 @@ class PresentsModel
{ {
return $this->DB; return $this->DB;
} }
public function getPresentsSum()
{
return $this->DB->getNumRows();
}
} }

View File

@ -1,27 +1,26 @@
<?php <?php
namespace Battles; namespace Battles;
use db;
/** /**
* Разные способы отображения строки с логином персонажа. * Разные способы отображения строки с логином персонажа.
*/ */
const INVIS = '<i>невидимка</i>';
class Nick extends User class Nick extends User
{ {
private function getInvisibilityStatus() private function getInvisibilityStatus()
{ {
return db::c()->query('SELECT 1 FROM users_effects WHERE type = 1022 AND owner_id = ?i', $this->id); return self::$db->fetch('SELECT 1 FROM users_effects WHERE type = 1022 AND owner_id = ?', $this->id);
} }
/** /**
* Отображение иконки склонности. * Отображение иконки склонности.
* @return string * @return string
*/ */
private function getAlign():string private function getAlign():?string
{ {
if (isset($this->align)) { if (isset($this->align)) {
return sprintf('<img src="i/align_%s.gif">', $this->align); return sprintf('<img src="i/align_%s.gif">', $this->align);
} else { } else {
return ''; return null;
} }
} }
@ -29,12 +28,12 @@ class Nick extends User
* Отображение иконки клана. * Отображение иконки клана.
* @return string * @return string
*/ */
private function getClan():string private function getClan():?string
{ {
if (isset($this->clan)) { if (isset($this->clan)) {
return sprintf('<img src="i/clan/%s.png">', $this->clan); return sprintf('<img src="i/clan/%s.png">', $this->clan);
} else { } else {
return ''; return null;
} }
} }
@ -44,7 +43,7 @@ class Nick extends User
* *
* @return Nick * @return Nick
*/ */
public static function id($playerId) public static function id($playerId): Nick
{ {
return new self($playerId); return new self($playerId);
} }
@ -59,7 +58,7 @@ class Nick extends User
public function full($showInvisibility = 0):string public function full($showInvisibility = 0):string
{ {
if ($showInvisibility && $this->getInvisibilityStatus()) { if ($showInvisibility && $this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return INVIS;
} }
return $this->getAlign().$this->getClan().sprintf('<b>%s</b> [%s] <a href="inf.php?%s" target="_blank"><img src="i/inf.gif" style="width:12px;height:11px"></a>', $this->login, $this->level, $this->login); return $this->getAlign().$this->getClan().sprintf('<b>%s</b> [%s] <a href="inf.php?%s" target="_blank"><img src="i/inf.gif" style="width:12px;height:11px"></a>', $this->login, $this->level, $this->login);
} }
@ -72,7 +71,7 @@ class Nick extends User
public function short($showInvisibility = 0):string public function short($showInvisibility = 0):string
{ {
if ($showInvisibility && $this->getInvisibilityStatus()) { if ($showInvisibility && $this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return INVIS;
} else { } else {
return htmlspecialchars($this->login); return htmlspecialchars($this->login);
} }
@ -96,7 +95,7 @@ class Nick extends User
public function battleShort($textstyle):string public function battleShort($textstyle):string
{ {
if ($this->getInvisibilityStatus()) { if ($this->getInvisibilityStatus()) {
return '<i>невидимка</i>'; return INVIS;
} }
else { else {
return sprintf('<span style="%s">%s</span> [_hp_/_maxhp_]', $textstyle, $this->login); return sprintf('<span style="%s">%s</span> [_hp_/_maxhp_]', $textstyle, $this->login);

View File

@ -1,5 +1,7 @@
<?php <?php
namespace Battles; namespace Battles;
use Battles\Database\DBPDO;
class ShopItem extends Item class ShopItem extends Item
{ {
public function printInfo() public function printInfo()
@ -10,54 +12,61 @@ class ShopItem extends Item
public function buyItem($owner) public function buyItem($owner)
{ {
if ($owner) { if ($owner) {
db::c()->query(' $db = new DBPDO();
INSERT INTO `inventory` (`prototype`,`owner`,`name`,`type`,`massa`,`cost`,`img`,`maxdur`,`isrep`,`gsila`,`glovk`,`ginta`,`gintel`, $query = "INSERT INTO inventory (
`ghp`,`gnoj`,`gtopor`,`gdubina`,`gmech`,`gfire`,`gwater`,`gair`,`gearth`,`glight`,`ggray`,`gdark`, owner_id, name, item_type, durability, price,
`needident`,`nsila`,`nlovk`,`ninta`,`nintel`,`nmudra`,`nvinos`,`nnoj`,`ntopor`,`ndubina`,`nmech`, need_strength, need_dexterity, need_intuition,
`nfire`,`nwater`,`nair`,`nearth`,`nlight`,`ngray`,`ndark`,`mfkrit`,`mfakrit`,`mfuvorot`,`mfauvorot`, need_endurance, need_intelligence, need_wisdom,
`bron1`,`bron2`,`bron3`,`bron4`,`maxu`,`minu`,`magic`,`nlevel`,`nalign`,`dategoden`,`goden`,`otdel`, add_strength, add_dexterity, add_intuition,
`artefact`, `koll`) VALUES (?i,?i,"?s",?i,?i,?i,"?s",?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i, add_endurance, add_intelligence, add_wisdom,
?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,?i,"?s",?i,?i) add_accuracy, add_evasion, add_criticals,
', $this->id, $owner, $this->name, $this->type, $this->massa, $this->cost, $this->img, $this->maxdur, $this->isrep, $this->gsila, $this->glovk, $this->ginta, $this->gintel, add_min_physical_damage, add_max_physical_damage,
$this->ghp, $this->gnoj, $this->gtopor, $this->gdubina, $this->gmech, $this->gfire, $this->gwater, $this->gair, $this->gearth, $this->glight, $this->ggray, $this->gdark, image, weight)
$this->needident, $this->nsila, $this->nlovk, $this->ninta, $this->nintel, $this->nmudra, $this->nvinos, $this->nnoj, $this->ntopor, $this->ndubina, $this->nmech, VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
$this->nfire, $this->nwater, $this->nair, $this->nearth, $this->nlight, $this->ngray, $this->ndark, $this->mfkrit, $this->mfakrit, $this->mfuvorot, $this->mfauvorot, $values = [
$this->bron1, $this->bron2, $this->bron3, $this->bron4, $this->maxu, $this->minu, $this->magic, $this->nlevel, $this->nalign, $this->dategoden, $this->goden, $this->razdel, $owner, $this->name, $this->item_type, $this->durability, $this->price,
$this->artefact, $this->koll); $this->need_strength, $this->need_dexterity, $this->need_intuition,
$this->need_endurance, $this->need_intelligence, $this->need_wisdom,
$this->add_strength, $this->add_dexterity, $this->add_intuition,
$this->add_endurance, $this->add_intelligence, $this->add_wisdom,
$this->add_accuracy, $this->add_evasion, $this->add_criticals,
$this->add_min_physical_damage, $this->add_max_physical_damage,
$this->image, $this->weight
];
$db->execute($query, $values);
} }
} }
/** /**
* Для кнопок управления под картинкой прелмета в зависимости от ситуации. * Для кнопок управления под картинкой предмета в зависимости от ситуации.
*/ */
public function printControls($shopType = false) public function printControls($shopType = false)
{ {
if ($shopType === 'marketput') { if ($shopType === 'marketput') {
echo <<<BTN echo <<<BTN
<form method="post"> <form method="post">
<input placeholder="{$this->cost}" name="cost"> <input placeholder="{$this->price}" name="cost">
<input type="hidden" name="putId" value="{$this->id}"> <input type="hidden" name="putId" value="{$this->item_id}">
<br><input type="submit" name="putToMarket" value="ать в магазин"> <br><input type="submit" name="putToMarket" value="ать в магазин">
</form> </form>
BTN; BTN;
} else { } else {
switch ($shopType) { switch ($shopType) {
default: default:
$btnValue = "Купить за " . intval($this->cost) . " кр."; $btnValue = "Купить за " . intval($this->price) . " кр.";
$btnLink = "/shop.php?buy={$this->id}&rnd=" . mt_rand(); $btnLink = "/shop.php?buy={$this->item_id}&rnd=" . mt_rand();
break; break;
case 'sell': case 'sell':
$btnValue = "Продать"; $btnValue = "Продать";
$btnLink = "/shop.php?sell={$this->id}&rnd=" . mt_rand(); $btnLink = "/shop.php?sell={$this->item_id}&rnd=" . mt_rand();
break; break;
case 'marketgetback': case 'marketgetback':
$btnValue = "Снять с продажи"; $btnValue = "Снять с продажи";
$btnLink = "?back={$this->id}&rnd=" . mt_rand(); $btnLink = "?back={$this->item_id}&rnd=" . mt_rand();
break; break;
case 'marketbuy': case 'marketbuy':
$btnValue = "Купить за " . intval($this->setsale) . " кр."; $btnValue = "Купить за " . intval($this->setsale) . " кр.";
$btnLink = "?otdel={$this->otdel}&set={$this->id}&rnd=" . mt_rand(); $btnLink = "?otdel={$this->item_type}&set={$this->item_id}&rnd=" . mt_rand();
break; break;
} }
@ -65,7 +74,6 @@ BTN;
<p><input type="button" style="background: darkgrey; border: 1px solid grey; border-radius: 2px;" value="{$btnValue}" <p><input type="button" style="background: darkgrey; border: 1px solid grey; border-radius: 2px;" value="{$btnValue}"
onclick="location='{$btnLink}'"> onclick="location='{$btnLink}'">
BTN; BTN;
if ($this->count > 0) echo "<br><small>В наличии: {$this->count} штук</small>";
} }
} }
} }

View File

@ -36,7 +36,7 @@ HTML_HEADER;
/** /**
* @param string $buildingName название здания * @param string $buildingName название здания
* @param string $streetName служебное название улицы на которой стоит здание для кнопки возврата. * @param string $streetName служебное название улицы на которой стоит здание для кнопки возврата.
* @return string * @return void
*/ */
public static function buildingTop(string $buildingName, string $streetName): void public static function buildingTop(string $buildingName, string $streetName): void
{ {

View File

@ -1,6 +1,8 @@
<?php <?php
# Date: 26.10.2020 (16:08) # Date: 26.10.2020 (16:08)
namespace Battles; namespace Battles;
use Battles\Database\DBPDO;
class Travel class Travel
{ {
/** /**
@ -57,12 +59,13 @@ class Travel
* Перемещение по комнатам. * Перемещение по комнатам.
* @param int $roomId ID куда идём. * @param int $roomId ID куда идём.
* @param int $roomIdCurrent ID откуда идём. * @param int $roomIdCurrent ID откуда идём.
* @throws \Krugozor\Database\Mysql\Exception * @param DBPDO|null $db
*/ */
public static function toRoom(int $roomId, int $roomIdCurrent): void public static function toRoom(int $roomId, int $roomIdCurrent): void
{ {
$itemsWeight = \db::c()->query('SELECT SUM(weight) AS all_weight FROM `inventory` WHERE owner_id = ?i AND on_sale = 0', $_SESSION['uid'])->fetch_assoc(); $db = DBPDO::INIT();
$eff = \db::c()->query('SELECT type FROM users_effects WHERE owner_id = ?i AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid'])->fetch_assoc(); $itemsWeight = $db->fetch('SELECT SUM(weight) AS all_weight FROM inventory WHERE owner_id = ? AND on_sale = 0', $_SESSION['uid']);
$eff = $db->fetch('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']);
$errors = []; $errors = [];
if ($itemsWeight['all_weight'] > get_meshok()) { if ($itemsWeight['all_weight'] > get_meshok()) {
$errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...'; $errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...';
@ -78,7 +81,7 @@ class Travel
echo sprintf('<span class="error">%s</span>', $error); echo sprintf('<span class="error">%s</span>', $error);
} }
} elseif (in_array($roomId, self::allowedRoomMoves($roomIdCurrent))) { } elseif (in_array($roomId, self::allowedRoomMoves($roomIdCurrent))) {
\db::c()->query('UPDATE users, online SET users.room = ?i, online.room = ?i WHERE `online`.`user_id` = `users`.`id` AND `online`.`user_id` = ?i', $roomId, $roomId, $_SESSION['uid']); $db->execute('UPDATE users, online SET users.room = ?, online.room = ? WHERE `online`.`user_id` = `users`.`id` AND `online`.`user_id` = ?', [$roomId, $roomId, $_SESSION['uid']]);
header('location: ' . self::$roomFileName[$roomId]); header('location: ' . self::$roomFileName[$roomId]);
exit; exit;
} }

View File

@ -2,8 +2,8 @@
namespace Battles; namespace Battles;
use Battles\Database\DBPDO;
use Exceptions\GameException; use Exceptions\GameException;
use db;
class User class User
{ {
@ -53,10 +53,12 @@ class User
// Динамически рассчитываемые // Динамически рассчитываемые
public $maxHealth = 5; public $maxHealth = 5;
public $maxMana = 5; public $maxMana = 5;
protected static $db;
public function __construct($user) public function __construct(int $user)
{ {
$user_query = db::c()->query('SELECT * FROM users WHERE id = "?s" OR login = "?s"', $user, $user)->fetch_assoc(); self::$db = DBPDO::INIT();
$user_query = self::$db->fetch('SELECT * FROM users WHERE id = ? OR login = ?', [$user, $user]);
foreach ($this as $key => $value) { foreach ($this as $key => $value) {
if (isset($user_query[$key])) { if (isset($user_query[$key])) {
$this->$key = $user_query[$key]; $this->$key = $user_query[$key];
@ -73,7 +75,7 @@ class User
* @return string * @return string
* @throws GameException * @throws GameException
*/ */
public function getStat($stat_name, $isMainWindow = 0) public function getStat($stat_name, $isMainWindow = 0):string
{ {
$allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom']; $allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'];
if (in_array($stat_name, $allowed)) { if (in_array($stat_name, $allowed)) {
@ -89,16 +91,16 @@ class User
/** /**
* Повышает один из выбранных статов на 1, но не выше self::STAT_MAXIMUM_AMOUNT при условии наличия свободных очков статов. * Повышает один из выбранных статов на 1, но не выше self::STAT_MAXIMUM_AMOUNT при условии наличия свободных очков статов.
* @param $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'. * @param string $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'.
* @throws GameException * @throws GameException
*/ */
public function addOnePointToStat($stat_name) public function addOnePointToStat(string $stat_name)
{ {
$allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom']; $allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'];
if (in_array($stat_name, $allowed)) { if (in_array($stat_name, $allowed)) {
if ($this->free_stat_points > 0 && $this->$stat_name <= self::STAT_MAXIMUM_AMOUNT) { if ($this->free_stat_points > 0 && $this->$stat_name <= self::STAT_MAXIMUM_AMOUNT) {
$query = 'UPDATE users SET ?f = ?f + 1, free_stat_points = free_stat_points - 1 WHERE id = ?i'; $query = "UPDATE users SET {$stat_name} = {$stat_name} + 1, free_stat_points = free_stat_points - 1 WHERE id = ?";
db::c()->query($query, $stat_name, $stat_name, $this->id); self::$db->execute($query,$this->id);
} else { } else {
throw new GameException(self::ERROR_STAT_IS_MAXIMUM); throw new GameException(self::ERROR_STAT_IS_MAXIMUM);
} }
@ -108,7 +110,7 @@ class User
} }
protected function showStarSign() protected function showStarSign(): ?string
{ {
/* /*
* 1 aries * 1 aries
@ -124,19 +126,21 @@ class User
* 11 aquarius * 11 aquarius
* 12 pisches * 12 pisches
*/ */
$zodiac[356] = "10"; $zodiac = [
$zodiac[326] = "09"; 356 => "10",
$zodiac[296] = "08"; 326 => "09",
$zodiac[266] = "07"; 296 => "08",
$zodiac[235] = "06"; 266 => "07",
$zodiac[203] = "05"; 235 => "06",
$zodiac[172] = "04"; 203 => "05",
$zodiac[140] = "03"; 172 => "04",
$zodiac[111] = "02"; 140 => "03",
$zodiac[78] = "01"; 111 => "02",
$zodiac[51] = "12"; 78 => "01",
$zodiac[20] = "11"; 51 => "12",
$zodiac[0] = "10"; 20 => "11",
0 => "10",
];
$dayOfYear = date("z", strtotime($this->borndate)); $dayOfYear = date("z", strtotime($this->borndate));
$isLeapYear = date("L", strtotime($this->borndate)); //Высокосный? $isLeapYear = date("L", strtotime($this->borndate)); //Высокосный?
if ($isLeapYear && $dayOfYear > 59) { if ($isLeapYear && $dayOfYear > 59) {
@ -159,4 +163,17 @@ class User
{ {
return $this->mana . '/' . $this->maxMana; return $this->mana . '/' . $this->maxMana;
} }
public static function setUserEffect(int $userId, int $type, string $name, int $time):bool
{
return self::$db->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time) VALUES (?,?,?,?)',[$userId, $type, $name, $time]);
}
public static function removeUserEffect(int $userId, int $type):bool
{
if (self::$db->fetch('SELECT 1 FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type])) {
self::$db->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]);
}
return false;
}
} }

View File

@ -5,16 +5,15 @@ namespace Battles;
trait UserEffects trait UserEffects
{ {
public static $effectName = [ public static $effectName = [
2 => 'Заклинание молчания',
3 => 'Заклятие форумного молчания',
4 => 'Заклятие хаоса',
5 => 'Заклятие обезличивания',
10 => 'паралич', 10 => 'паралич',
11 => 'легкая травма', 11 => 'легкая травма',
12 => 'средняя травма', 12 => 'средняя травма',
13 => 'тяжёлая травма', 13 => 'тяжёлая травма',
14 => 'неизлечимая травма', 14 => 'неизлечимая травма',
1022 => 'невидимость',
2 => 'Заклинание молчания',
3 => 'Заклятие форумного молчания',
4 => 'Заклятие хаоса',
5 => 'Заклятие обезличивания',
20 => 'Проверка Паладинов', 20 => 'Проверка Паладинов',
21 => 'Сила нейтралитета', 21 => 'Сила нейтралитета',
22 => 'Защита от кулачного нападения', 22 => 'Защита от кулачного нападения',
@ -47,6 +46,7 @@ trait UserEffects
226 => 'Стена Воды [3]', 226 => 'Стена Воды [3]',
227 => 'Защита от нападений', 227 => 'Защита от нападений',
405 => 'Микстура жизненных сил', 405 => 'Микстура жизненных сил',
1022 => 'невидимость',
9994 => 'Антидот/Путы (Эликсир?)', 9994 => 'Антидот/Путы (Эликсир?)',
]; ];
} }

View File

@ -11,12 +11,10 @@ class UserInfo extends User
/** /**
* Отображает куклу персонажа (образ и слоты). * Отображает куклу персонажа (образ и слоты).
* *
* @param int $isBattle - установить 1, если куклу нужно отобразить в поединке (показывает параметры при наведении * @param int $isBattle установить 1, если куклу нужно отобразить в поединке (показывает параметры при наведении
* на образ). * на образ).
* @param int $isMain - установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает * @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает
* его). * его).
*
* @throws \Krugozor\Database\Mysql\Exception
*/ */
private function UserInfoDoll($isBattle = 0, $isMain = 0) private function UserInfoDoll($isBattle = 0, $isMain = 0)
{ {
@ -150,16 +148,16 @@ class UserInfo extends User
public function showUserInfo() public function showUserInfo()
{ {
$this->effects = new \Battles\Models\EffectsModel($this->id);
$this->WatcherStatus(); $this->WatcherStatus();
$effects = new \Battles\Models\EffectsModel($this->id);
if ($this->block && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) { if ($this->block && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
throw new \Exceptions\GameException('<span class="error">Персонаж ' . $this->login . ' заблокирован!</span>'); throw new \Exceptions\GameException('<span class="error">Персонаж ' . $this->login . ' заблокирован!</span>');
} elseif ($this->effects->getHideUserInfoStatus() && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) { } elseif ($effects->getHideUserInfoStatus() && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
if ($this->effects->getHideUserInfoStatus() == -1) { if ($effects->getHideUserInfoStatus() == -1) {
$date = 'навсегда'; $date = 'навсегда';
} else { } else {
$date = 'до' . date('d.m.Y', strtotime($this->effects->getHideUserInfoStatus())); $date = 'до' . date('d.m.Y', strtotime($effects->getHideUserInfoStatus()));
} }
throw new \Exceptions\GameException('<span class="error">Персонаж ' . $this->login . ' обезличен ' . $date . '.</span>'); throw new \Exceptions\GameException('<span class="error">Персонаж ' . $this->login . ' обезличен ' . $date . '.</span>');
} else { } else {
@ -169,7 +167,7 @@ class UserInfo extends User
private function WatcherStatus() private function WatcherStatus()
{ {
$query = \db::c()->query('SELECT `align`,`admin` FROM `users` WHERE `id` = ?i', $this->watcher_id)->fetch_assoc(); $query = parent::$db->fetch('SELECT align, admin FROM users WHERE id = ?', $this->watcher_id);
if ($query['admin']) { if ($query['admin']) {
$this->watcherIsAdmin = 1; $this->watcherIsAdmin = 1;
} }

View File

@ -2,9 +2,6 @@
# Date: 28.10.2020 (17:41) # Date: 28.10.2020 (17:41)
namespace Exceptions; namespace Exceptions;
use Exception;
class GameException extends Exception { }
class GameException extends \Exception
{
}

View File

@ -4,7 +4,7 @@
* Author: Igor Barkov <lopar.4ever@gmail.com> * Author: Igor Barkov <lopar.4ever@gmail.com>
* Project name: Battles-Game * Project name: Battles-Game
*/ */
if (empty($_SESSION['uid'])) { if (empty($_SESSION['uid']) && $_SERVER['REQUEST_URI'] != "/enter.php") {
header("Location: index.php"); header("Location: index.php");
exit; exit;
} }

File diff suppressed because it is too large Load Diff