diff --git a/admin/admin.php b/admin/admin.php index 23fcc34..70ef826 100644 --- a/admin/admin.php +++ b/admin/admin.php @@ -6,11 +6,9 @@ */ require_once '../functions.php'; -use Battles\Bank; use Battles\Database\Db; use Battles\GameConfigs; use Battles\Moderation; -use Battles\Nick; use Battles\Template; use Battles\User; @@ -67,9 +65,8 @@ UNREGCLANLIST; public function disallowRegister($id) { - $bank = new Bank($id); Db::getInstance()->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id); - $bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id); + User::getInstance()->money()->modifyBank(GameConfigs::CLAN['clan_register_cost']); } }; $unregisteredClans->getList(); @@ -97,7 +94,7 @@ foreach ($row as $r) { $invisList .= '[id] = ' .$r->id. ', ' .$r->login. '
'; } - +User::getInstance()-> Template::header('ᐰdminка'); ?> diff --git a/akadem.php b/akadem.php index 4ed73c6..357a646 100644 --- a/akadem.php +++ b/akadem.php @@ -1,8 +1,8 @@ setMoney(User::getInstance()->getMoney() - $needMoney); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); + User::getInstance()->money()->spend($needMoney); db::c()->query('UPDATE `users` SET ?f = ?i WHERE `id` = ?i', 'prof' . $type, $profId, User::getInstance()->getId()); $deloText = "{$user['login']} купил профессию «{$name}» в академии за {$needMoney} кр."; GameLogs::addUserLog($_SESSION['uid'], $deloText); @@ -67,8 +66,7 @@ if ($get == 'medic') { } if ($get == 'exit') { - db::c()->query('UPDATE `users`,`online` SET `users`.`room` = 2702, `online`.`room` = 2702 WHERE `users`.`id` = ?i AND `online`.`id` = ?i', User::getInstance()->getId(), User::getInstance()->getId()); - header('Location: city.php'); + Travel::toRoom(2702, User::getInstance()->getRoom()); } Template::header('Академия'); ?> @@ -80,7 +78,7 @@ Template::header('Академия');
Информация - КредитыgetMoney() ?> + Кредитыmoney()->get() ?> Уровень персонажаgetLevel() ?>
diff --git a/bank.php b/bank.php index 41914fb..af3223d 100644 --- a/bank.php +++ b/bank.php @@ -1,77 +1,23 @@ getId()); -$status = ''; +$_POST['action'] ??= null; +$bank = new Bank(); -$toid = $_POST['to_id'] ?? 0; -$summa = $_POST['summa'] ?? 0; -$submit = $_POST['action'] ?? ''; -try { // Зачисление кредитов на счёт. - if ($submit === 'depositMoney' && $summa) { - $operation = $bank->depositMoney($summa); - User::getInstance()->setMoney($operation['walletMoney']); - $bank->setMoney($operation['bankMoney']); - $status = SUCCESS; - } -// Снятие кредитов со счёта. - if ($submit === 'withdrawMoney' && $summa) { - $operation = $bank->withdrawMoney($summa); - User::getInstance()->setMoney($operation['walletMoney']); - $bank->setMoney($operation['bankMoney']); - $status = SUCCESS; - } -// Перевод кредитов на другой счёт. - if ($submit === 'sendMoney' && $summa && $toid) { - User::getInstance()->setMoney($bank->sendMoney($toid, $summa)); - $status = SUCCESS; - } -} catch (GameException $e) { - echo 'Банковская ошибка!'; -} finally { - unset($submit, $summa, $toid); +if ($_POST['action'] === 'depositMoney' && !empty($_POST['summa'])) { + $bank->depositMoney($_POST['summa']); } -Template::header('Банк'); -?> - - - -
-
- На счету: getMoney() ?> -
- На руках: getMoney() ?> -
-
- Работа со счётом -
- - - -
-
- - - -
-
-
- Перевод кредитов -
- -
- - -
- Комиссия: % от переводимой суммы, но не менее 1 кр. -
+// Снятие кредитов со счёта. +if ($_POST['action'] === 'withdrawMoney' && !empty($_POST['summa'])) { + $bank->withdrawMoney($_POST['summa']); +} +// Перевод кредитов на другой счёт. +if ($_POST['action'] === 'sendMoney' && !empty($_POST['summa']) && !empty($_POST['to-id'])) { + $bank->sendMoney($_POST['to-id'], $_POST['summa']); +} + +require_once 'views/bank.php'; diff --git a/buy.php b/buy.php index 590d251..249d80d 100644 --- a/buy.php +++ b/buy.php @@ -1,6 +1,5 @@ getId()); - if ($bank->getMoney() <= PRICES[$name]) { + if (User::getInstance()->money()->getBank() <= PRICES[$name]) { return false; } $query = sprintf('update users_bonuses set %s = %s + 1 where user_id = ?', $name, $name); Db::getInstance()->execute($query, User::getInstance()->getId()); - $bank->setMoney($bank->getMoney() - $prices[$name]); + User::getInstance()->money()->modifyBank(-PRICES[$name]); return true; } diff --git a/buy_klan.php b/buy_klan.php index 138f88e..b52ff8e 100644 --- a/buy_klan.php +++ b/buy_klan.php @@ -1,6 +1,5 @@ getId()); - if ($bank->getMoney() <= PRICES[$name]) { + if (User::getInstance()->money()->getBank() <= PRICES[$name]) { return false; } $query = sprintf('update clan_bonuses set %s = %s + 1 where short_name = ?', $name, $name); Db::getInstance()->execute($query, User::getInstance()->getClan()); - $bank->setMoney($bank->getMoney() - PRICES[$name]); + User::getInstance()->money()->modifyBank(-PRICES[$name]); return true; } diff --git a/c_haos_in.php b/c_haos_in.php index e720d6f..ab55ce3 100644 --- a/c_haos_in.php +++ b/c_haos_in.php @@ -323,7 +323,7 @@ if (!$ch_rooms[$in_haos['room']]) { addchp('За убийство босса Цитадели Хаоса вы получили ' . $dress['name'], '{[]}' . Nick::id($all_get[$l_id])->short() . '{[]}'); } if ($priz_exp > 0) { - GiveExp($all_get[$l_id], $priz_exp); + \Battles\User::getInstance($all_get[$l_id])->addExperience($priz_exp); addchp('За убийство босса Цитадели Хаоса вы получили ' . $priz_exp . ' опыта', '{[]}' . Nick::id($all_get[$l_id])->short() . '{[]}'); mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) VALUES ('','0','{$cur_user['id']}','\"" . $all_get[$l_id] . "\" получил в ЦХ \"" . $priz_exp . "\" опыта',1,'" . time() . "');"); diff --git a/cave.php b/cave.php index aef740f..33e4de0 100644 --- a/cave.php +++ b/cave.php @@ -5,18 +5,17 @@ use Battles\GameLogs; use Battles\ShopItem; use Battles\Template; use Battles\User; +use Battles\UserEffect; require_once 'functions.php'; //require_once 'cave/cave_bots.php'; $userslots = ['sergi', 'kulon', 'perchi', 'weap', 'bron', 'r1', 'r2', 'r3', 'helm', 'shit', 'boots', 'rybax', 'plaw', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10']; -function cancarry($m, $uid) +function cancarry($m, $uid): bool { if (!$uid) { $uid = User::getInstance()->getId(); } - $weight = \Battles\Database\Db::getInstance()->execute('select sum(weight) from inventory where owner_id = ? and on_sale = 0', $uid)->fetchColumn(); - $maxWeight = \Battles\Database\Db::getInstance()->execute('select strength * 4 from users where id = ?', $uid)->fetchColumn(); - return $weight + $m > $maxWeight ? false : true; + return !UserEffect::isOverEncumbered($uid, $m); } function placeinbackpack($qty, $userid = null) @@ -339,7 +338,7 @@ while ($rec = mysql_fetch_assoc($r)) { } if (User::getInstance()->getRoom() == 621) { - $base = "/underdesigns/alchcave"; + $base = "/i/underdesigns/alchcave"; } $maxloses = 3; @@ -1194,6 +1193,7 @@ Template::header('cave'); if ($user['hp'] <= 0) { makedeath(); } + $botNames = CaveBots::$botnames; $botIds = CaveBots::$bots; function drawmap($map1, $players, $x, $y, $direction) diff --git a/clan_create.php b/clan_create.php index 8b44c3c..0380c18 100644 --- a/clan_create.php +++ b/clan_create.php @@ -1,18 +1,16 @@ ofetch('select * from clans where owner_id = ?', User::getInstance()->getId()); $clanFullName = $_POST['clan_full_name'] ?? ''; $clanShortName = $_POST['clan_short_name'] ?? ''; $clanInfo = $_POST['clan_info'] ?? ''; -$userBank = new Bank(User::getInstance()->getId()); if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { $eff = Db::getInstance()->execute('select count(*) from users_effects where type = 20 and owner_id = ?', User::getInstance()->getId())->fetchColumn(); @@ -27,7 +25,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { if (User::getInstance()->getClan()) { $errorMessage[1] = 'Вы уже состоите в клане!.
'; } - if (GameConfigs::CLAN['clan_register_cost'] >= $userBank->getMoney()) { + if (GameConfigs::CLAN['clan_register_cost'] >= User::getInstance()->money()->getBank()) { $errorMessage[2] = 'Не хватает денег на регистрацию клана.
'; } if (!$eff) { @@ -39,8 +37,8 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { if (!$errorMessage || User::getInstance()->getAdmin()) { try { Db::getInstance()->execute('insert into clans (owner_id, full_name, short_name, info) values (?,?,?,?)', [User::getInstance()->getId(), $clanFullName, $clanShortName, $clanInfo]); - $userBank->setMoney($userBank->getMoney() - GameConfigs::CLAN['clan_register_cost']); - Battles\Bank::setBankMoney($userBank->getMoney(), User::getInstance()->getId(), 'clanRegister'); + + User::getInstance()->money()->modifyBank(-GameConfigs::CLAN['clan_register_cost'], 'clanRegister'); // Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит. $userClan = new stdClass(); $userClan->full_name = $clanFullName; @@ -101,7 +99,7 @@ if ($userClan): ?> Для регистрации клана необходимо иметь:
  1. Проверку на чистоту. У вас её нет. -
  2. 10000 кредитов на банковском счёте. У вас на счету getMoney() ?>. +
  3. 10000 кредитов на банковском счёте. У вас на счету money()->getBank() ?>.
Поле информации не обазательное. Но его содержимое может серьёзно повысить шансы на регистрацию клана.
Заявку на регистрацию подает глава клана. diff --git a/classes/Battles/Bank.php b/classes/Battles/Bank.php index 99a534b..5fc3a1b 100644 --- a/classes/Battles/Bank.php +++ b/classes/Battles/Bank.php @@ -7,21 +7,22 @@ namespace Battles; -use Exceptions\GameException; use Battles\Database\Db; -use Throwable; class Bank { - public int $user_id = 0; + private int $user_id = 0; private int $money = 0; - private $user; + private string $error = ''; + private string $status = ''; + private int $comission = 0; - const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; - const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; - const ERROR_NO_MONEY_IN_BANK_ACCOUNT = "Ошибка! Нет денег на счету!"; - const ERROR_WRONG_AMOUNT = "Ошибка! Сумма должна быть положительной!"; - const LOG = [ + private const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!"; + private const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!"; + private const ERROR_NO_MONEY_IN_BANK_ACCOUNT = "Ошибка! Нет денег на счету!"; + private const ERROR_WRONG_AMOUNT = "Ошибка! Сумма должна быть положительной!"; + private const ERROR_WRONG_ID = 'Неверный ID!'; + private const LOG = [ 'sendMoney' => 'Банк: Перевод средств на другой счёт.', 'receiveMoney' => 'Банк: Получение средств.', 'depositMoney' => 'Пополнение счёта.', @@ -30,10 +31,12 @@ class Bank 'sellShop' => 'Продажа товара в магазине.' ]; - public function __construct(int $user_id) + public function __construct(int $user_id = null) { + if (empty($user_id)) { + $user_id = User::getInstance()->getId(); + } $bank_row = Db::getInstance()->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id); - $this->user = Db::getInstance()->fetch('SELECT money FROM users WHERE id = ?', $user_id); foreach ($this as $key => $value) { if (isset($bank_row[$key])) { $this->$key = $bank_row[$key]; @@ -48,75 +51,69 @@ class Bank * * @return int */ - private function bankCommission(int $amount): int + private function commission(int $amount): int { $bankCommission = round($amount * GameConfigs::BANK_COMISSION); - if ($bankCommission < 1) { - return 1; - } else { - return (int)$bankCommission; - } + $this->comission = max(1, (int)$bankCommission); + return $this->comission; } /** * Пишем банковское событие в лог в БД * - * @param int $receiverId ID получателя. - * @param int $amount сумма. + * @param int $receiverId ID получателя. + * @param int $amount сумма. * @param string $operationType тип банковской операции. - * @param int $senderId ID отправителя (ID игрока, если не указано иное). + * @param ?int $senderId ID отправителя (ID игрока, если не указано иное). * * @return void */ - private function bankLogs(int $receiverId, int $amount, string $operationType, int $senderId = null): void + private function addLog(int $receiverId, int $amount, string $operationType, ?int $senderId = null): void { if (is_null($senderId)) { $senderId = $this->user_id; } - $text = self::LOG[$operationType]; - if ($operationType == "sendMoney") { - $text .= " Комиссия: " . $this->bankCommission($amount); - } elseif ($operationType == "depositMoney") { + if ($operationType === 'depositMoney' || $operationType === 'withdrawMoney') { $receiverId = $this->user_id; - } elseif ($operationType == "withdrawMoney") { - $receiverId = $this->user_id; - $text .= " Комиссия: " . $this->bankCommission($amount); } - GameLogs::addBankLog($senderId,$receiverId,$amount,$operationType,$text); + $commText = $this->comission ? ' Комиссия: ' . $this->comission : ''; + $text = self::LOG[$operationType] . $commText; + $this->status = $text; + GameLogs::addBankLog($senderId, $receiverId, $amount, $operationType, $text); } /** * Перевод денег между банковскими счетами игроков с банковской комиссией. * - * @param int $receiver ID получателя. - * @param int $amount сумма. - * - * @return int - * @throws GameException + * @param mixed $receiver ID получателя. + * @param mixed $amount Cумма. */ - public function sendMoney(int $receiver, int $amount): int + public function sendMoney($receiver, $amount) { - $receiverWallet = Db::getInstance()->ofetch('SELECT money FROM bank WHERE user_id = ?', $receiver); - if ($amount <= 0) { - throw new GameException(self::ERROR_WRONG_AMOUNT); + if (!is_numeric($receiver)) { + $this->error = self::ERROR_WRONG_ID; + return; } - if (!$receiverWallet) { - throw new GameException(self::ERROR_NO_BANK_ACCOUNT); + $rec = new self($receiver); + if (!is_numeric($amount) || $amount <= 0) { + $this->error = self::ERROR_WRONG_AMOUNT; } - $amountWithComission = $amount + $this->bankCommission($amount); + if (!$rec->user_id) { + $this->error = self::ERROR_NO_BANK_ACCOUNT; + } + $amountWithComission = $amount + $this->commission($amount); if ($amountWithComission > $this->money) { - throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); + $this->error = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT; + } + if ($this->error) { + return; } // Снимаем сумму с комиссией у отправителя - $this->money -= $amountWithComission; - self::setBankMoney($this->money, $this->user_id); - $this->bankLogs($receiver, $this->money, "sendMoney"); + $this->modify(-$amountWithComission); + $this->addLog($rec->user_id, $this->money, 'sendMoney', $this->user_id); // Отдаём сумму на счёт получателю - $receiverWallet->money += $amount; - self::setBankMoney($receiverWallet->money, $receiver); - $this->bankLogs($receiver, $receiverWallet->money, "receiveMoney"); - // Возвращаем изменившиеся значения - return $this->money; + $rec->modify($amount); + $rec->addLog($rec->user_id, $rec->money, 'receiveMoney', $this->user_id); } /** @@ -124,30 +121,22 @@ class Bank * * @param int $amount сумма. * - * @return array - * @throws GameException */ - public function depositMoney(int $amount): array + public function depositMoney(int $amount) { if ($amount <= 0) { - throw new GameException(self::ERROR_WRONG_AMOUNT); - } - $walletMoney = Db::getInstance()->fetchColumn('SELECT money FROM users WHERE id = ?', $this->user_id); - if ($walletMoney < $amount) { - throw new GameException(self::ERROR_NO_MONEY_IN_WALLET); + $this->error = self::ERROR_WRONG_AMOUNT; } // Забираем деньги из кошелька получателя - $this->user->money -= $amount; - self::setWalletMoney($this->user->money, $this->user_id); + if (!User::getInstance($this->user_id)->money()->spend($amount)) { + $this->error = self::ERROR_NO_MONEY_IN_WALLET; + } + if ($this->error) { + return; + } // Отдаём сумму на счёт получателю - $this->money += $amount; - self::setBankMoney($this->money, $this->user_id); - $this->bankLogs(0, $this->money, "depositMoney"); - // Возвращаем изменившиеся значения - return [ - 'walletMoney' => $this->user->money, - 'bankMoney' => $this->money - ]; + $this->modify($amount); + $this->addLog(0, $this->money, 'depositMoney'); } /** @@ -155,66 +144,29 @@ class Bank * * @param int $amount сумма. * - * @return array - * @throws GameException */ - public function withdrawMoney(int $amount): array + public function withdrawMoney(int $amount) { if ($amount <= 0) { - throw new GameException(self::ERROR_WRONG_AMOUNT); + $this->error = self::ERROR_WRONG_AMOUNT; } - $amountWithComission = $amount + $this->bankCommission($amount); + $amountWithComission = $amount + $this->commission($amount); if ($this->money < $amountWithComission) { - throw new GameException(self::ERROR_NO_MONEY_IN_BANK_ACCOUNT); + $this->error = self::ERROR_NO_MONEY_IN_BANK_ACCOUNT; + } + if ($this->error) { + return; } // Снимаем сумму с комиссией у отправителя - $this->money -= $amountWithComission; - self::setBankMoney($this->money, $this->user_id); - $this->bankLogs(0, $this->money, "withdrawMoney"); + $this->modify(-$amountWithComission); + $this->addLog(0, $this->money, 'withdrawMoney'); // Отдаём сумму в кошелёк получателя - $this->user['money'] += $amount; - self::setWalletMoney($this->user['money'], $this->user_id); - // Возвращаем изменившиеся значения - return [ - 'walletMoney' => $this->user['money'], - 'bankMoney' => $this->money - ]; + User::getInstance($this->user_id)->money()->earn($amount); } - /** - * Установить количество денег на банковском счету. - * - * @param int $amount сумма. - * @param int $user_id ID пользователя. - * @param string $operationType Тип операции. По умолчанию пусто. Если ввести, система запишет событие в банковский лог. - * - * @return void - */ - public static function setBankMoney(int $amount, int $user_id, string $operationType = ''): void + private function save() { - try { - Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$amount, $user_id]); - if ($operationType) { - GameLogs::addBankLog(0, 0, $amount, $operationType, self::LOG[$operationType]); - } - } catch (Throwable $e) { - echo "Не отработал запрос в БД в файле {$e->getFile()}({$e->getLine()})"; - } - - } - - /** - * Установить количество денег на руках. - * - * @param int $amount сумма. - * @param int $user_id ID пользователя. - * - * @return void - */ - public static function setWalletMoney(int $amount, int $user_id): void - { - User::getInstance($user_id)->setMoney($amount); - User::getInstance($user_id)->saveMoney(); + Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$this->money, $this->user_id]); } public function getMoney(): int @@ -222,8 +174,30 @@ class Bank return $this->money; } - public function setMoney($amount) + public function modify(int $amount, string $logType = '') { - $this->money = $amount; + if ($amount > 0) { + // add_money + $this->money += $amount; + $this->save(); + } elseif ($amount < 0) { + // remove_money + if ($this->money < $amount) { + return; + } + $this->money -= $amount; + $this->save(); + } + if ($logType && $amount !== 0) { + $this->addLog(0, $this->money, $logType); + } } -} \ No newline at end of file + + public function getStatus(): string + { + if (!$this->error) { + return $this->status; + } + return $this->error; + } +} diff --git a/classes/Battles/Check.php b/classes/Battles/Check.php index d7d812b..4fa76fc 100644 --- a/classes/Battles/Check.php +++ b/classes/Battles/Check.php @@ -14,6 +14,7 @@ class Check * Check constructor. * * @param User $user + * @param Db $db */ public function __construct(User $user, Db $db) { @@ -21,8 +22,13 @@ class Check $this->db = $db; } - public function Effects() + public static function expiredEffects() { - return $this->db->execute('delete from users_effects where remaining_time <= ?', strtotime('now')); + return Db::getInstance()->execute('delete from users_effects where remaining_time <= ?', strtotime('now')); + } + + public static function userExists($id): bool + { + return Db::getInstance()->fetchColumn('select count(*) from users where id = ?', $id) > 0; } } \ No newline at end of file diff --git a/classes/Battles/Clan.php b/classes/Battles/Clan.php index 9c89bad..602cf85 100644 --- a/classes/Battles/Clan.php +++ b/classes/Battles/Clan.php @@ -3,6 +3,7 @@ namespace Battles; use Battles\Database\Db; +use Battles\Models\User\Effects; class Clan { @@ -34,14 +35,13 @@ class Clan if (User::getInstance($login)->getLevel() < 1) { $error .= '
Персонаж 0 уровня не может быть принят!'; } - if (User::getInstance()->getMoney() < GameConfigs::CLAN['add_member_cost']) { + if (!User::getInstance()->money()->spend(GameConfigs::CLAN['add_member_cost'])) { $error .= '
Недостаточно денег!'; } if ($error) { return $error; } - User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['add_member_cost']); - User::getInstance()->saveMoney(); + User::getInstance($login)->setClan(User::getInstance()->getClan()); return "Персонаж «{$login}» успешно принят в клан."; } @@ -49,20 +49,18 @@ class Clan public function removeMember(string $login): string { $error = null; - if (User::getInstance()->getMoney() < GameConfigs::CLAN['remove_member_cost']) { - $error .= '
Недостаточно денег!'; - } if (User::getInstance($login)->getId() === User::getInstance()->getId()) { $error .= '
Себя выгонять нельзя!'; } if (User::getInstance($login)->getClan() !== User::getInstance()->getClan()) { $error .= '
Персонаж не состоит в этом клане!'; } + if (!User::getInstance()->money()->spend(GameConfigs::CLAN['remove_member_cost'])) { + $error .= '
Недостаточно денег!'; + } if ($error) { return $error; } - User::getInstance()->setMoney(User::getInstance()->getMoney() - GameConfigs::CLAN['remove_member_cost']); - User::getInstance()->saveMoney(); User::getInstance($login)->setClan(null); return "Персонаж «{$login}» покинул клан."; } @@ -100,7 +98,7 @@ class Clan private function getProverka($user_id) { - return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = 20 and owner_id = ?', $user_id); + return Effects::count($user_id, 20); } public function getClanOwnerId(): ?int diff --git a/classes/Battles/DressedItems.php b/classes/Battles/DressedItems.php index c1ce5b8..c8fcb3d 100644 --- a/classes/Battles/DressedItems.php +++ b/classes/Battles/DressedItems.php @@ -8,6 +8,7 @@ namespace Battles; use Battles\Database\Db; +use Battles\Models\Inventory; use stdClass; class DressedItems @@ -51,7 +52,7 @@ class DressedItems self::getItemsInSlots(); // Проверяем, что используется один из 12 слотов и наличие предмета в слоте. if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem->$slot_id) { - self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$slot_id, $this->USERID]); + Inventory::undressOne($slot_id, $this->USERID); } } public static function undressAllItems($user_id) diff --git a/classes/Battles/Hostel.php b/classes/Battles/Hostel.php new file mode 100644 index 0000000..ccaad05 --- /dev/null +++ b/classes/Battles/Hostel.php @@ -0,0 +1,177 @@ + [8, 16, 24, 32], + 2 => [15, 30, 45, 60], + 3 => [25, 50, 75, 100], + 4 => [40, 80, 120, 160] + ]; + public const BASENAME = [ + 1 => 'Сумка', + 2 => 'Сундук', + 3 => 'Комната', + 4 => 'Амбар', + ]; + + public function __construct() + { + $this->uid = User::getInstance()->getId(); + $data = Db::getInstance()->ofetch('select id, type, time from hostel where uid = ?', $this->uid); + $this->hid = $data->id ?? null; + $this->type = $data->type ?? null; + $this->time = $data->time ?? null; + } + + private function add7DayRent($type) + { + Db::getInstance()->execute('insert into hostel (uid, type, time) values (?,?,?)', [$this->uid, $type, time() + 60 * 60 * 24 * 7]); + } + + private function addRentTime($hostel_id, $time) + { + Db::getInstance()->execute('update hostel set time = ? where id = ? and uid = ?', [$time, $hostel_id, $this->uid]); + } + + private function removeItems() + { + Db::getInstance()->execute('update inventory set in_hostel = 0 where owner_id = ? and in_hostel = 1', $this->uid); + } + + private function removeRent() + { + Db::getInstance()->execute('delete from hostel where id = ? and uid = ?', [$this->hid, $this->uid]); + } + + private function pay($amount): bool + { + if (!User::getInstance()->money()->spend($amount)) { + $this->setError('Недостаточно денег!'); + return false; + } + return true; + } + + private function hasNoRents(): bool + { + if ($this->hid) { + $this->setError('Не более 1 арендованного места!'); + return false; + } + return true; + } + + private function typeIsAllowed($type): bool + { + if (!in_array($type, [1, 2, 3, 4])) { + $this->setError('Неверный тип аренды!'); + return false; + } + return true; + } + + public function setError(string $message) + { + $this->status = ['type' => 'error', 'message' => $message]; + } + + private function setSuccess(string $message) + { + $this->status = ['type' => 'success', 'message' => $message]; + } + + public function newRent($type): bool + { + if ( + !$this->typeIsAllowed($type) || + !$this->hasNoRents() || + !$this->pay(self::PRICEPERTYPE[$type][0]) + ) { + return false; + } + $this->add7DayRent($type); + $this->setSuccess('Поздравляем с успешной арендой!'); + return true; + } + + public function remove(): bool + { + if ($this->time < time()) { + $this->setError('Нельзя отказаться от услуг если имеется задолежнность!'); + return false; + } + $this->removeRent(); + $this->removeItems(); + $this->setSuccess('Вы успешно отказались от аренды!'); + return true; + } + + public function changeType(int $type) + { + $this->remove(); + $this->newRent($type); + } + + public function changeTime(int $ordered_time): bool + { + $daysByOrder = [ + 1 => 7, + 2 => 14, + 3 => 21, + 4 => 28, + ]; + if ( + !$this->typeIsAllowed($ordered_time) || + !$this->pay(self::PRICEPERTYPE[$this->type][$ordered_time - 1]) + ) { + return false; + } + $this->time += 60 * 60 * 24 * $daysByOrder[$ordered_time]; + $this->addRentTime($this->hid, $this->time); + $this->setSuccess('Всё прошло успешно!'); + return true; + } + + /** + * @return int|null + */ + public function getHid(): ?int + { + return $this->hid; + } + + /** + * @return int|null + */ + public function getType(): ?int + { + return $this->type; + } + + /** + * @return int|null + */ + public function getTime(): ?int + { + return $this->time; + } + + /** + * @return array + */ + public function getStatus(): array + { + return $this->status; + } +} diff --git a/classes/Battles/InventoryItem.php b/classes/Battles/InventoryItem.php index 873209b..1fb588f 100644 --- a/classes/Battles/InventoryItem.php +++ b/classes/Battles/InventoryItem.php @@ -1,12 +1,13 @@ owner_id); $stat = $checkStats->getFullStats(); - return - $this->need_strength > $stat->strength - || $this->need_dexterity > $stat->dexterity - || $this->need_intuition > $stat->intuition - || $this->need_endurance > $stat->endurance - || $this->need_intelligence > $stat->intelligence - || $this->need_wisdom > $stat->wisdom - ? true : null; + return $this->need_strength > $stat->strength + || $this->need_dexterity > $stat->dexterity + || $this->need_intuition > $stat->intuition + || $this->need_endurance > $stat->endurance + || $this->need_intelligence > $stat->intelligence + || $this->need_wisdom > $stat->wisdom; } /** @@ -77,8 +77,8 @@ IMG; // считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами // Count добавленный в первый запрос возвращает одну строку в любом случае. // fetch возвращает одну строку в любом случае. - $weared = Db::getInstance()->ofetchAll('SELECT dressed_slot FROM inventory WHERE dressed_slot != 0 AND item_type = ? AND owner_id = ?', [$this->item_type, $this->owner_id]); - $wearedCount = Db::getInstance()->ofetch('select count(dressed_slot) as c from inventory where dressed_slot !=0 and item_type = ? and owner_id = ?', [$this->item_type, $this->owner_id]); + $weared = Inventory::getDressed($this->item_type, $this->owner_id); + $wearedCount = Inventory::countDressed($this->item_type, $this->owner_id); // Если в слоте есть предмет(ы), забиваем их массив одетых в слот предметов. if ($wearedCount) { foreach ($weared as $item) { @@ -93,11 +93,11 @@ IMG; //работаем с нормальными слотами if ($wearedCount->c == 1) { //если слот занят, снимаем старый предмет и одеваем новый предмет - Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $this->owner_id]); - Db::getInstance()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); + Inventory::undressOne($itemInSlot[0], $this->owner_id); + Inventory::dressOne($this->item_id, $this->owner_id); } elseif (!$wearedCount->c) { //если слот пуст, одеваем новый предмет - Db::getInstance()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); + Inventory::dressOne($this->item_id, $this->owner_id); } else { /* проверка на переполнение слотов */ $error = self::TOO_MANY_ITEMS_IN_SLOTS; @@ -111,11 +111,10 @@ IMG; // Сортируем массив свободных слотов по возрастанию. sort($emptyRingSlots); // Одеваем предмет в первый свободный слот. - Db::getInstance()->execute('update inventory set dressed_slot = ? where item_id = ?', [$emptyRingSlots[0], $this->item_id]); + Inventory::dressOneToSlot($this->item_id, $emptyRingSlots[0]); } elseif ($wearedCount->c == 3) { // Cнимаем предмет из последнего слота 11 и одеваем новый предмет - Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11'); - Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id); + Inventory::changeRings($this->item_id); } else { /* проверка на переполнение слотов */ $error = self::TOO_MANY_ITEMS_IN_SLOTS; @@ -128,9 +127,31 @@ IMG; return $error ?? true; } - public static function destroyItem($itemId) + // Выбрасываем вещь. + public function drop(): string { - Db::getInstance()->execute('delete from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?', [$_SESSION['uid'], $itemId]); + if (empty($this->item_id)) { + return 'Ошибка: предмет не найден!'; + } + if (Inventory::isWeared($this->item_id)) { + return 'Ошибка: нельзя выбросить одетый предмет!'; + } + Inventory::destroyItem($this->item_id, $this->owner_id); + GameLogs::addUserLog(User::getInstance()->getId(), User::getInstance()->getLogin() . ' выбросил предмет ' . $this->name . ' id:(cap' . $this->item_id . ')'); + return 'Предмет ' . $this->name . ' выброшен.'; + } + + /** Снятие всех предметов, которые не подходят по статам. */ + public static function autoDrop() + { + $DI = new DressedItems(User::getInstance()->getId()); + foreach ($DI->getItemsInSlots() as $dressedItem) + { + $ITM = new self($dressedItem); + if (!$ITM->dressStatsChecks()) { + $DI->undressItem($dressedItem->dressed_slot); + } + } } /** Надеюсь, временная заглушка, которая объединяет get_meshok() и другую выдачу одной строкой. @@ -138,9 +159,9 @@ IMG; */ public static function getWeightData(): string { - $query = 'select sum(weight) as `all`, strength * 4 as max from inventory left join users u on owner_id = id where owner_id = ?'; - $weight = Db::getInstance()->ofetch($query, User::getInstance()->getId()); - $css = $weight->all > $weight->max ? ' style="color:maroon;"' : ''; - return "$weight->all / $weight->max"; + $all = Inventory::getWeight(User::getInstance()->getId()); + $max = User::getInstance()->stats()->getMaxWeight(); + $css = $all > $max ? ' style="color:maroon;"' : ''; + return "$all / $max"; } } \ No newline at end of file diff --git a/classes/Battles/Magic/CureInjury.php b/classes/Battles/Magic/CureInjury.php index 9ef433f..a8b97a7 100644 --- a/classes/Battles/Magic/CureInjury.php +++ b/classes/Battles/Magic/CureInjury.php @@ -3,13 +3,13 @@ // Магия лечения травм namespace Battles\Magic; -use Battles\UserEffects, Battles\Database\Db, Battles\User; +use Battles\Database\Db, Battles\User, Battles\UserEffect; class CureInjury extends Magic { private $target; private $login; - use UserEffects; + //use UserEffects; /** * Магия лечения травм. Если у персонажа несколько травм, лечится самая тяжёлая. @@ -25,16 +25,14 @@ class CureInjury extends Magic } $ok = null; $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 == 'Неизвестный эффект') { - $injuryName = self::$effectName[$injury->type]; + if (in_array($injury->type, [11, 12, 13, 14]) && $injuryType >= $injury->type && UserEffect::remove($target, $injury->effect_id)) { + if (empty($injury->name) || $injury->name === 'Неизвестный эффект') { + $injuryName = UserEffect::$effectName[$injury->type]; } else { $injuryName = $injury->name; } $ok = "Вы вылечили повреждение ${injuryName} персонажу $this->login."; - } elseif ($injury->effect_id && $injuryType == 15) { - $db->execute('DELETE FROM users_effects WHERE type IN (11,12,13,14) AND owner_id = ?', $target); + } elseif ($injury->effect_id && $injuryType === 15 && UserEffect::massRemove($target, [11,12,13,14])) { $ok = "Вы вылечили все повреждения персонажу $this->login."; } return $ok; diff --git a/classes/Battles/Models/EffectsModel.php b/classes/Battles/Models/EffectsModel.php deleted file mode 100644 index c3281b4..0000000 --- a/classes/Battles/Models/EffectsModel.php +++ /dev/null @@ -1,39 +0,0 @@ -DB = Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id); - } - - /** - * Проверка обезличен ли персонаж. - * @return int date() до конца эффекта или 0. - */ - public function getHideUserInfoStatus(): int - { - if ($this->DB) { - $i = 0; - while ($i < count($this->DB)) { - if ($this->DB[$i]->type == self::EFFECT_HIDEUSERINFO) { - return $this->DB[$i]->remaining_time; - } - $i++; - } - } - return 0; - } -} \ No newline at end of file diff --git a/classes/Battles/Models/Inventory.php b/classes/Battles/Models/Inventory.php new file mode 100644 index 0000000..a91821c --- /dev/null +++ b/classes/Battles/Models/Inventory.php @@ -0,0 +1,135 @@ +fetchColumn(' + select + sum(weight) + from + inventory + where + owner_id = ? + and on_sale = 0 + ', $user_id); + } + + public static function getBonuses(int $user_id) + { + return Db::getInstance()->ofetch(" + select + sum(add_strength) as item_strength, + sum(add_dexterity) as item_dexterity, + sum(add_intuition) as item_intuition, + sum(add_endurance) as item_endurance, + sum(add_intelligence) as item_intelligence, + sum(add_wisdom) as item_wisdom, + sum(add_accuracy) as item_accuracy, + sum(add_evasion) as item_evasion, + sum(add_criticals) as item_criticals, + sum(add_min_physical_damage) as item_min_physical_damage, + sum(add_max_physical_damage) as item_max_physical_damage + from + inventory + where + dressed_slot != 0 and + owner_id = ? + ", $user_id); + } + + public static function getDressed(int $item_type, int $user_id): object + { + return Db::getInstance()->ofetchAll(' + SELECT + dressed_slot + FROM + inventory + WHERE + dressed_slot != 0 + AND item_type = ? + AND owner_id = ? + ', [$item_type, $user_id]); + } + + public static function countDressed(int $item_type, int $user_id): object + { + return Db::getInstance()->ofetchAll(' + SELECT + count(dressed_slot) + FROM + inventory + WHERE + dressed_slot != 0 + AND item_type = ? + AND owner_id = ? + ', [$item_type, $user_id]); + } + + public static function undressOne(int $slot, int $user_id) + { + Db::getInstance()->execute(' + UPDATE + inventory + SET + dressed_slot = 0 + WHERE + dressed_slot = ? + AND owner_id = ? + ', [$slot, $user_id]); + } + + public static function dressOne(int $item_id, int $user_id) + { + Db::getInstance()->execute(' + UPDATE + inventory + SET + dressed_slot = item_type + WHERE + item_id = ? + AND owner_id = ? + ', [$item_id, $user_id]); + } + + public static function dressOneToSlot(int $item_id, int $slot) + { + Db::getInstance()->execute('UPDATE inventory SET dressed_slot = ? WHERE item_id = ?', [$slot, $item_id]); + } + + public static function destroyItem(int $item_id, int $user_id) + { + Db::getInstance()->execute(' + delete + from + inventory + where + dressed_slot = 0 + and owner_id = ? + and item_id = ? + ', [$user_id, $item_id]); + } + + public static function changeRings(int $item_id) + { + Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11'); + Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $item_id); + } + + public static function isWeared(int $item_id): bool + { + return Db::getInstance()->fetchColumn(' + select + count(*) + from + inventory + where + item_id = ? + and dressed_slot > 0 + ', $item_id) > 0; + } +} \ No newline at end of file diff --git a/classes/Battles/Models/Presents.php b/classes/Battles/Models/Presents.php new file mode 100644 index 0000000..2638d11 --- /dev/null +++ b/classes/Battles/Models/Presents.php @@ -0,0 +1,22 @@ +getId(); + } + return Db::getInstance()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id); + } +} \ No newline at end of file diff --git a/classes/Battles/Models/PresentsModel.php b/classes/Battles/Models/PresentsModel.php deleted file mode 100644 index 38836b1..0000000 --- a/classes/Battles/Models/PresentsModel.php +++ /dev/null @@ -1,26 +0,0 @@ -DB) { - $this->DB = Db::getInstance()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id); - } - } - - public function getAllPresents() - { - return $this->DB; - } -} \ No newline at end of file diff --git a/classes/Battles/Models/User/Effects.php b/classes/Battles/Models/User/Effects.php new file mode 100644 index 0000000..cd30750 --- /dev/null +++ b/classes/Battles/Models/User/Effects.php @@ -0,0 +1,35 @@ +ofetch(" + select + sum(mod_strength) as effect_strength, + sum(mod_dexterity) as effect_dexterity, + sum(mod_intuition) as effect_intuition, + sum(mod_endurance) as effect_endurance, + sum(mod_intelligence) as effect_intelligence, + sum(mod_wisdom) as effect_wisdom + from + users_effects + where + owner_id = ? + ", $user_id); + } + + public static function getAll(int $user_id): object + { + return Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id); + } + + public static function count(int $user_id, int $type) + { + return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = ? and owner_id = ?', [$type, $user_id]); + } +} \ No newline at end of file diff --git a/classes/Battles/Models/User/Stats.php b/classes/Battles/Models/User/Stats.php new file mode 100644 index 0000000..38d8182 --- /dev/null +++ b/classes/Battles/Models/User/Stats.php @@ -0,0 +1,52 @@ +ofetch('select id, strength, dexterity, intuition, endurance, intelligence, wisdom, health, mana, free_stat_points, level from users where ' . $col . ' = ?', $user); + } + + public static function addOne(string $stat, int $user_id) + { + + Db::getInstance()->execute(" + UPDATE + users + SET + $stat = $stat + 1, + free_stat_points = free_stat_points - 1 + WHERE + id = ? + ", $user_id); + } + + public static function save(array $vars) + { + Db::getInstance()->execute(' + update + users + set + strength = ?, + dexterity = ?, + intuition = ?, + endurance = ?, + intelligence = ?, + wisdom = ?, + health = ?, + mana = ?, + free_stat_points = ?, + level = ? + where + id = ? + ', $vars); + } +} \ No newline at end of file diff --git a/classes/Battles/Moderation.php b/classes/Battles/Moderation.php index a8cf52e..c18fbac 100644 --- a/classes/Battles/Moderation.php +++ b/classes/Battles/Moderation.php @@ -17,50 +17,50 @@ class Moderation public static function muteChat(int $target, int $time) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[2]); - User::addUserEffect($target, 2, UserEffects::$effectName[2], $time); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[2]); + UserEffect::add($target, 2, UserEffect::$effectName[2], $time); } public static function unmuteChat(int $target) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[2] . self::STATUS_OFF); - User::removeUserEffect($target, 2); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[2] . self::STATUS_OFF); + UserEffect::remove($target, 2); } public static function muteForum(int $target, int $time) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[3]); - User::addUserEffect($target, 3, UserEffects::$effectName[3], $time); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[3]); + UserEffect::add($target, 3, UserEffect::$effectName[3], $time); } public static function unmuteForum(int $target) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[3] . self::STATUS_OFF); - User::removeUserEffect($target, 3); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[3] . self::STATUS_OFF); + UserEffect::remove($target, 3); } public static function hideUserInfo(int $target, int $time) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[5]); - User::addUserEffect($target, 5, UserEffects::$effectName[5], $time); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[5]); + UserEffect::add($target, 5, UserEffect::$effectName[5], $time); } public static function unHideUserInfo(int $target) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[5] . self::STATUS_OFF); - User::removeUserEffect($target, 5); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[5] . self::STATUS_OFF); + UserEffect::remove($target, 5); } public static function blockUser(int $target) { self::addEffectStatusToUserLog($target, "Блокировка"); - Db::getInstance()->execute('UPDATE battles.users SET block = 1 WHERE id = ?', $target); + Db::getInstance()->execute('UPDATE users SET block = 1 WHERE id = ?', $target); } - public static function unBlockUser(int $target) + public static function unblockUser(int $target) { self::addEffectStatusToUserLog($target, "Блокировка" . self::STATUS_OFF); - Db::getInstance()->execute('UPDATE battles.users SET block = 0 WHERE block = 1 AND id = ?', $target); + Db::getInstance()->execute('UPDATE users SET block = 0 WHERE block = 1 AND id = ?', $target); } public static function addToUserLog(int $target, string $message, int $senderId) @@ -80,7 +80,7 @@ class Moderation public static function addUserCheck(int $target) { - self::addEffectStatusToUserLog($target, UserEffects::$effectName[20]); - User::addUserEffect($target, 20, UserEffects::$effectName[20], strtotime('3days')); + self::addEffectStatusToUserLog($target, UserEffect::$effectName[20]); + UserEffect::add($target, 20, UserEffect::$effectName[20], strtotime('3days')); } } \ No newline at end of file diff --git a/classes/Battles/Nick.php b/classes/Battles/Nick.php index 52a2e2c..b6a8966 100644 --- a/classes/Battles/Nick.php +++ b/classes/Battles/Nick.php @@ -2,17 +2,17 @@ namespace Battles; -use Battles\Database\Db; - /** * Разные способы отображения строки с логином персонажа. */ const INVIS = 'невидимка'; -class Nick extends UserStats +class Nick { - private function isInvisible() + private User $user; + + private function __construct(int $userid) { - return Db::getInstance()->execute('SELECT count(*) FROM users_effects WHERE type = 1022 AND owner_id = ?', $this->id)->fetchColumn(); + $this->user = User::getInstance($userid); } /** @@ -21,25 +21,41 @@ class Nick extends UserStats */ private function getAlignImage(): ?string { - return $this->align ? "Склонность" : null; + return $this->getImage($this->user->getAlign(), '/i/align_'); } /** * Отображение иконки клана. * @return string */ - private function getClanImage(): ?string + private function getClanImage(): string { - return $this->clan ? "Клан" : null; + return $this->getImage($this->user->getClan(), '/i/clan/'); + } + + private function getImage($name, $path): string + { + if (empty($name)) { + return ''; + } + $file = $path . $name . '.png'; + $alt = ''; + if (strpos($path, 'align')) { + $alt = '{a:' . $name . '}'; + } elseif (strpos($path, 'clan')) { + $alt = '{c:' . $name . '}'; + } + return file_exists($file) ? "$alt" : $alt; } private function getInfolinkImage(): string { - return "Ссылка на профиль"; + return "Ссылка на профиль"; } /** * Вызов класса из самого себя. Читать про обратное связывание и пытаться что-то понять. + * * @param $playerId * * @return Nick @@ -58,7 +74,10 @@ class Nick extends UserStats */ public function full(int $showInvisibility = 0): string { - return !$showInvisibility && $this->isInvisible() ? INVIS : $this->getAlignImage() . $this->getClanImage() . " $this->login [$this->level] " . $this->getInfolinkImage(); + if ($showInvisibility === 0 && UserEffect::isInvisible($this->user->getId())) { + return INVIS; + } + return $this->getAlignImage() . ' ' . $this->getClanImage() . ' ' . $this->user->getLogin() . " [" . $this->user->getLevel() . "] " . $this->getInfolinkImage(); } /** @@ -68,7 +87,7 @@ class Nick extends UserStats */ public function short(): string { - return $this->login; + return $this->user->getLogin(); } /** @@ -77,6 +96,6 @@ class Nick extends UserStats */ public function battle(): string { - return $this->full() . "HP [$this->health/$this->maxHealth]"; + return $this->full() . "HP [" . $this->user->stats()->getHealth() . "/" . $this->user->stats()->getMaxHealth() . "]"; } } \ No newline at end of file diff --git a/classes/Battles/ShopItem.php b/classes/Battles/ShopItem.php index 1c4ecc6..2e27464 100644 --- a/classes/Battles/ShopItem.php +++ b/classes/Battles/ShopItem.php @@ -3,13 +3,10 @@ namespace Battles; use Battles\Database\Db; -use Battles\Models\PresentsModel; -use Exceptions\GameException; class ShopItem extends Item { private const NO_ITEMS_IN_STOCK = "Товара нет в наличии!"; - private const NO_MONEY = "У вас нет денег!"; private const NO_BARTER_ITEMS = 'У вас нет требуемых предметов!'; private const BUTTON = [ 'setmarket' => 'Сдать в магазин', @@ -135,23 +132,23 @@ SQL; return ""; } - public static function buyItem($id, User $buyer) + public static function buyItem($id) { $check = Db::getInstance()->ofetch("select * from trade_offers where offer_id = ?", $id); $item = new Item(Db::getInstance()->fetch('select * from items where id = ?', $check->shop_item_id)); $price = $item->calculateItemCost(); if ( - !self::checkAndRemoveBarteredItems($check->barter_items_list_json, $buyer->getId()) || - !self::checkAndPayTheBills($price, $buyer) || + !self::checkAndRemoveBarteredItems($check->barter_items_list_json, User::getInstance()->getId()) || + !self::checkAndPayTheBills($price) || !self::checkAndChangeRemainingItems($check->shop_item_quantity, $check->shop_item_id) ) { return; } - Db::getInstance()->execute(self::BUY_QUERY, [$buyer->getId(), $check->shop_item_id]); - $deloText = $buyer->getLogin() . " купил товар «" . $item->name . "» id:(" . $check->shop_item_id . ") в магазине за " . $price . "."; - GameLogs::addUserLog($buyer->getId(), $deloText); + Db::getInstance()->execute(self::BUY_QUERY, [User::getInstance()->getId(), $check->shop_item_id]); + $deloText = User::getInstance()->getLogin() . " купил товар «" . $item->name . "» id:(" . $check->shop_item_id . ") в магазине за " . $price . "."; + GameLogs::addUserLog(User::getInstance()->getId(), $deloText); self::$status = "Предмет " . $item->name . " куплен за " . $price . "."; } @@ -179,21 +176,13 @@ SQL; return true; } - private static function checkAndPayTheBills(int $price, User $user): bool + private static function checkAndPayTheBills(int $price): bool { - if (User::getInstance()->getMoney() > $price) { - User::getInstance()->setMoney(User::getInstance()->getMoney() - $price); - User::getInstance()->saveMoney(); + if (User::getInstance()->money()->spend($price)) { return true; } - try { - $bank = new Bank(User::getInstance()->getId()); - $bank->withdrawMoney($price); - return true; - } catch (GameException $e) { - self::$status = 'Банковская ошибка! ' . self::NO_MONEY; - return false; - } + (new Bank())->withdrawMoney($price); + return true; } private static function checkAndChangeRemainingItems(int $current_quantity, $item_id): bool @@ -209,7 +198,7 @@ SQL; return true; } - public static function sellItem($id, User $seller, $bankTrade = 0) + public static function sellItem($id, $bankTrade = 0) { $item = Db::getInstance()->ofetch('select * from inventory where item_id = ?', $id); $sellingItemName = $item->name; @@ -217,14 +206,12 @@ SQL; $sellingPrice = $item->price > 1 ? mt_rand(0, $item->price / 2) : mt_rand(0, 1); Db::getInstance()->execute('delete from inventory where item_id = ?', $id); if ($bankTrade) { - $bank = new Bank($seller->getId()); - $bank->setMoney($bank->getMoney() + $sellingPrice); - Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'sellShop'); + User::getInstance()->money()->modifyBank($sellingPrice, 'sellShop'); } else { - Db::getInstance()->execute('update users set money = money - ? where id = ?', [$sellingPrice, $_SESSION['uid']]); + User::getInstance()->money()->earn($sellingPrice); } - $deloText = "{$seller->getLogin()} продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр."; - GameLogs::addUserLog($seller->getId(), $deloText); + $deloText = User::getInstance()->getLogin() . " продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр."; + GameLogs::addUserLog(User::getInstance()->getId(), $deloText); if ($sellingPrice == 0) { self::$status = "После длительных и изнурительных торгов вы плюнули на всё и просто подарили ваш «{$sellingItemName}» торговцу."; } else { @@ -274,8 +261,9 @@ FORM; /** Выдача магазинных предметов по запросу. * Ввелась чтобы перебить takeshopitem() в functions с идентичным функционалом. + * * @param int $item_id ИД предмета. - * @param int $to ИД пперсонажа-получателя. + * @param int $to ИД пперсонажа-получателя. */ public static function giveNewItem(int $item_id, int $to): array { diff --git a/classes/Battles/Travel.php b/classes/Battles/Travel.php index ae88e2a..c4b88a7 100644 --- a/classes/Battles/Travel.php +++ b/classes/Battles/Travel.php @@ -8,9 +8,9 @@ class Travel { /** * Соответствие ID комнаты игровому файлу. - * @var string[] + * @var array */ - public static $roomFileName = [ + public static array $roomFileName = [ 1 => 'main.php', 20 => 'city.php', 21 => 'city.php', @@ -91,18 +91,16 @@ class Travel private static array $roomsCheck = [22, 23, 27, 29, 30, 31, 37, 38, 39, 40, 41, 45, 53, 61, 401, 402, 600, 601, 602, 621, 650, 1051, 1052]; /** - * Перемещение по комнатам. + * Перемещение по комнатам. Header:Location уже включён. * * @param int $roomId ID куда идём. * @param int $roomIdCurrent ID откуда идём. */ public static function toRoom(int $roomId, int $roomIdCurrent): void { - UserStats::getInstance()-> - $itemsWeightOverflow = Db::getInstance()->fetchColumn('SELECT SUM(weight) - (select strength * 4 from users where id = ?) AS weight_overflow FROM inventory WHERE owner_id = ? AND on_sale = 0', [$_SESSION['uid'], $_SESSION['uid']]); $eff = Db::getInstance()->fetchColumn('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']); $errors = []; - if ($itemsWeightOverflow > 0) { + if (UserEffect::isOverEncumbered($_SESSION['uid'])) { $errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...'; } if ($eff == 10) { @@ -155,8 +153,8 @@ class Travel $room[21] = [20, 29, 30, 31, 34, 650, 2111]; $room[29] = $room[30] = $room[31] = $room[34] = [21]; - $room[26] = [20, 401, 660, 777, 2601]; - $room[401] = $room[660] = $room[777] = [26]; + $room[26] = [20, 401, 660, 661, 777, 2601]; + $room[401] = $room[660] = $room[661] = $room[777] = [26]; $room[2601] = [26, 37, 404, 1051, 2655]; @@ -187,7 +185,7 @@ class Travel * * @return void */ - public static function roomRedirects(int $inRoom, int $inBattle, int $inTower) + public static function roomRedirects(int $inRoom, int $inBattle, int $inTower = 0) { if ($inBattle && in_array(pathinfo(debug_backtrace()[0]['file'])['basename'], self::$fbattleCheckFiles)) { header('location: fbattle.php'); diff --git a/classes/Battles/User.php b/classes/Battles/User.php index 5440af0..1f2f746 100644 --- a/classes/Battles/User.php +++ b/classes/Battles/User.php @@ -6,50 +6,44 @@ use Battles\Database\Db; class User { + use Users; private static ?self $_instance = null; + private ?UserProfile $profile = null; + private ?UserEffect $effect = null; + private ?UserStats $stats = null; + private ?UserInfo $userInfo = null; + private ?UserMoney $userMoney = null; - protected int $id = 0; - protected string $login = ''; - protected ?string $pass = null; - protected ?string $email = null; - protected ?string $realname = null; - protected ?string $borndate = null; - protected ?string $info = null; - protected int $level = 0; - protected ?int $align = null; - protected ?string $clan = null; - protected ?int $money = null; - protected ?string $ip = null; - - protected ?int $admin = null; - protected int $room = 0; - protected int $block = 0; - protected string $shadow = ''; // Пока несуществующие, для совместимости. protected int $experience = 0; protected int $battle = 0; - protected int $in_tower = 0; // Скорее башню похороним чем запустим... protected int $zayavka = 0; - public const INFO_CHAR_LIMIT = 1500; - protected function __construct($user = null) { if (is_null($user)) { $user = $_SESSION['uid']; } - $query = 'select * from users where login = ?'; - if (is_numeric($user)) { - $query = 'select * from users where id = ?'; - $user = (int)$user; - } + // Отсекаем 2.0000~ + $col = ctype_digit(strval($user)) ? 'id' : 'login'; + $query = "select * from users where $col = ?"; $user_query = Db::getInstance()->fetch($query, $user); foreach ($this as $key => $value) { if (isset($user_query[$key])) { $this->$key = $user_query[$key]; } } + + $this->profileData = (object)[ + $this->id, + $this->pass, + $this->email, + $this->realname, + $this->borndate, + $this->info, + $this->ip, + ]; } public static function getInstance($user = null): self @@ -60,27 +54,53 @@ class User return self::$_instance; } - /** - * @param int $userId - * @param int $type - * @param string $name - * @param int $time - * @param string|null $json_modifiers_list (str, dex, int, end, intel, wis). - */ - public static function addUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null) + public function profile(): UserProfile { - $mods = json_decode($json_modifiers_list); - Db::getInstance()->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time, mod_strength, mod_dexterity, mod_intuition, mod_endurance, mod_intelligence, mod_wisdom) VALUES (?,?,?,?,?,?,?,?,?,?)', [$userId, $type, $name, $time, $mods->str ?? null, $mods->dex ?? null, $mods->int ?? null, $mods->end ?? null, $mods->intel ?? null, $mods->wis ?? null]); + if (is_null($this->profile)) { + $this->profile = new UserProfile( + $this->id, + $this->pass, + $this->email, + $this->realname, + $this->borndate, + $this->info, + $this->ip, + ); + } + return $this->profile; } - public static function removeUserEffect(int $userId, int $type): bool + public function effect(): UserEffect { - if (Db::getInstance()->fetchColumn('SELECT 1 FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type])) { - Db::getInstance()->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]); + if (is_null($this->effect)) { + $this->effect = new UserEffect(); } - return false; + return $this->effect; } + public function stats(): UserStats + { + if (is_null($this->stats)) { + $this->stats = new UserStats($this->id); + } + return $this->stats; + } + public function userInfo(): UserInfo + { + if (is_null($this->userInfo)) { + $this->userInfo = new UserInfo($this->id); + } + return $this->userInfo; + } + public function money(): UserMoney + { + if (is_null($this->userMoney)) { + $this->userMoney = new UserMoney($this->id, $this->money); + } + return $this->userMoney; + } + + public function getId(): int { return $this->id; @@ -91,44 +111,6 @@ class User return $this->login; } - public function getPass(): string - { - return $this->pass; - } - - /** - * @param mixed $pass - */ - public function setPass($pass): void - { - $this->pass = $pass; - } - - public function getRealname(): string - { - return $this->realname; - } - - /** - * @param mixed $realname - */ - public function setRealname($realname): void - { - $this->realname = $realname; - } - - public function getInfo(): string - { - return $this->info; - } - - /** - * @param mixed $info - */ - public function setInfo($info) - { - $this->info = $info; - } public function getLevel(): int { @@ -154,21 +136,6 @@ class User $this->saveUser(); } - public function getMoney(): int - { - return $this->money; - } - - public function setMoney(int $money) - { - $this->money = max($money, 0); - } - - public function saveMoney() - { - Db::getInstance()->execute('update users set money = ? where id = ?', [$this->money, $this->id]); - } - public function getAdmin(): int { return $this->admin; @@ -206,7 +173,7 @@ class User 'm01', 'm02', 'm03', 'm04', 'm05', 'm06', 'm07', 'm08', 'm09', 'm10', 'f01', 'f02', 'f03', 'f04', 'f05', 'f06', 'f07', 'f08', 'f09', 'f10', ]; - if (in_array($shadow, $shadows) && $this->getShadow() == '0.png') { + if (in_array($shadow, $shadows) && $this->getShadow() === '0.png') { $this->shadow = $shadow . '.png'; } } @@ -216,16 +183,20 @@ class User return $this->experience; } + /** + * @param int $experience + */ + public function addExperience(int $experience): void + { + $this->experience += $experience; + Db::getInstance()->execute('update users set experience = ? where id = ?', [$experience, $this->id]); + } + public function getBattle(): int { return $this->battle; } - public function getInTower(): int - { - return $this->in_tower; - } - public function getZayavka(): int { return $this->zayavka; @@ -236,53 +207,14 @@ class User Db::getInstance()->execute('update online set real_time = ? where user_id = ?', [time(), $this->getId()]); } - public function setInjury(int $type): bool - { - if (!in_array($type, [11, 12, 13, 14])) { - return false; - } - $names1 = ['разбитый нос', 'сотрясение первой степени', 'потрепанные уши', 'прикушенный язык', 'перелом переносицы', 'растяжение ноги', 'растяжение руки', 'подбитый глаз', 'синяк под глазом', 'кровоточащее рассечение', 'отбитая «пятая точка»', 'заклинившая челюсть', 'выбитый зуб «мудрости»', 'косоглазие']; - $names2 = ['отбитые почки', 'вывих «вырезано цензурой»', 'сотрясение второй степени', 'оторванное ухо', 'вывих руки', 'оторванные уши', 'поврежденный позвоночник', 'поврежденный копчик', 'разрыв сухожилия', 'перелом ребра', 'перелом двух ребер', 'вывих ноги', 'сломанная челюсть']; - $names3 = ['пробитый череп', 'разрыв селезенки', 'смещение позвонков', 'открытый перелом руки', 'открытый перелом «вырезано цензурой»', 'излом носоглотки', 'непонятные, но множественные травмы', 'сильное внутреннее кровотечение', 'раздробленная коленная чашечка', 'перелом шеи', 'смещение позвонков', 'открытый перелом ключицы', 'перелом позвоночника', 'вывих позвоночника', 'сотрясение третьей степени']; - $param_names = ['str', 'dex', 'int', 'end', 'intel', 'wis',]; - shuffle($param_names); - switch ($type) { - case 11: - shuffle($names1); - $name = UserEffects::$effectName[$type] . ': ' . $names1(0); - self::addUserEffect($this->id, $type, $name, strtotime('30min'), json_encode([$param_names(0) => -1])); - break; - case 12: - shuffle($names2); - $name = UserEffects::$effectName[$type] . ': ' . $names2(0); - self::addUserEffect($this->id, $type, $name, strtotime('3hours'), json_encode([$param_names(0) => mt_rand(-3, -1), $param_names(1) => mt_rand(-3, -1)])); - break; - case 13: - shuffle($names3); - $name = UserEffects::$effectName[$type] . ': ' . $names3(0); - self::addUserEffect($this->id, $type, $name, strtotime('12hours'), json_encode([$param_names(0) => mt_rand(-5, -1), $param_names(1) => mt_rand(-5, -1), $param_names(2) => mt_rand(-5, -1)])); - break; - default: //type 14 - self::addUserEffect($this->id, $type, UserEffects::$effectName[$type], strtotime('1day'), json_encode([$param_names(0) => -10])); - break; - } - - return true; - } - /** Сохраняет в базу актуальные логин, пароль, email, имя, дату рождения, текст инфы, склонность, клан, образ, права админа. * */ public function saveUser() { - $query = 'update users set login = ?, pass = ?, email = ?, realname = ?, borndate = ?, info = ?, align = ?, clan = ?, shadow = ?, admin = ? where id = ?'; + $query = 'update users set login = ?, align = ?, clan = ?, shadow = ?, admin = ? where id = ?'; $vals = [ $this->login, //set - $this->pass, - $this->email, - $this->realname, - $this->borndate, - $this->info, $this->align, $this->clan, $this->shadow, @@ -291,4 +223,5 @@ class User ]; Db::getInstance()->execute($query, $vals); } + } \ No newline at end of file diff --git a/classes/Battles/UserEffects.php b/classes/Battles/UserEffect.php similarity index 50% rename from classes/Battles/UserEffects.php rename to classes/Battles/UserEffect.php index 4182357..e9d87fb 100644 --- a/classes/Battles/UserEffects.php +++ b/classes/Battles/UserEffect.php @@ -1,14 +1,17 @@ 'Заклинание молчания', 3 => 'Заклятие форумного молчания', 4 => 'Заклятие хаоса', 5 => 'Заклятие обезличивания', + 8 => 'Сон', 10 => 'паралич', 11 => 'Легкая травма', 12 => 'Средняя травма', @@ -50,7 +53,7 @@ trait UserEffects 9994 => 'Антидот/Путы (Эликсир?)', ]; - public static $effectImage = [ + public static array $effectImage = [ 1 => 'travma.gif', 2 => 'magic/sleep.gif', 3 => 'magic/sleepf.gif', @@ -85,4 +88,75 @@ trait UserEffects 227 => 'magic/attack_defence.gif', 1022 => 'sh/hidden.gif', ]; + + /** + * @param int $userId + * @param int $type + * @param string $name + * @param int $time + * @param string|null $json_modifiers_list (str, dex, int, end, intel, wis). + */ + public static function add(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null) + { + $mods = json_decode($json_modifiers_list); + Db::getInstance()->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time, mod_strength, mod_dexterity, mod_intuition, mod_endurance, mod_intelligence, mod_wisdom) VALUES (?,?,?,?,?,?,?,?,?,?)', [$userId, $type, $name, $time, $mods->str ?? null, $mods->dex ?? null, $mods->int ?? null, $mods->end ?? null, $mods->intel ?? null, $mods->wis ?? null]); + } + + public static function updateTime(int $userId, int $type, int $time) + { + if (self::hasEffect($userId, $type)) { + Db::getInstance()->execute('update users_effects set remaining_time = remaining_time + ? where owner_id = ? and type = ?', [$time, $userId, $type]); + } + } + + public static function remove(int $userId, int $type): bool + { + if (self::hasEffect($userId, $type)) { + Db::getInstance()->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]); + return true; + } + return false; + } + + public static function massRemove(int $userId, array $type): bool + { + if (Db::getInstance()->fetchColumn('SELECT count(*) FROM users_effects WHERE owner_id = ? AND type in (?)', [$userId, $type])) { + Db::getInstance()->execute('DELETE FROM users_effects WHERE owner_id = ? AND type in (?)', [$userId, $type]); + return true; + } + return false; + } + + public static function hasEffect(int $userId, int $type): bool + { + return Db::getInstance()->fetchColumn('select count(*) from users_effects where owner_id = ? and type = ?', [$userId, $type]) > 0; + } + + public static function getRemainingEffectTime(int $userId, int $type): int + { + return Db::getInstance()->fetchColumn('select remaining_time from users_effects where owner_id = ? and type = ?', [$userId, $type]); + } + + public static function isInvisible(int $userId): bool + { + return self::hasEffect($userId, 1022); + } + + public static function hasHiddenProfile(int $userId): string + { + $time = self::getRemainingEffectTime($userId, 5); + if (empty($time)) { + return ''; + } + if ($time === -1) { + return 'навсегда'; + } + return 'до' . date('d.m.Y', strtotime($time)); + } + + public static function isOverEncumbered(int $userid, int $addWeight = 0): bool + { + $query = 'select strength * 5 + ' . $addWeight . ' as max from inventory left join users u on owner_id = id where owner_id = ? having sum(weight) > max'; + return Db::getInstance()->fetchColumn($query, $userid) > 0; + } } \ No newline at end of file diff --git a/classes/Battles/UserInfo.php b/classes/Battles/UserInfo.php index 87f3b7b..7b27eba 100644 --- a/classes/Battles/UserInfo.php +++ b/classes/Battles/UserInfo.php @@ -2,71 +2,83 @@ namespace Battles; -use Battles\Database\Db; -use Battles\Models\EffectsModel; +use Battles\Models\User\Effects; +use Exceptions\GameException; class UserInfo extends UserStats { + private const PERCENT_20 = (20 / 100); + private const PERCENT_80 = (80 / 100); use Rooms; - private int $bankMoney; - - public function __construct($user) - { - parent::__construct($user); - $bank = new Bank($this->id); - $this->bankMoney = $bank->getMoney(); - } - /** * Отображает куклу персонажа (образ и слоты). * * @param int $isBattle установить 1, если куклу нужно отобразить в поединке (показывает параметры при наведении * на образ). - * @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает + * @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает * его). + * + * @throws GameException */ - private function UserInfoDoll(int $isBattle = 0, int $isMain = 0) + private function UserInfoDoll(int $isBattle = 0, int $isMain = 0): string { $di = new DressedItems($this->id); + $stats = new UserStats($this->id); $dressedItems = $di->getItemsInSlots(); + $str = null; for ($i = 1; $i <= 12; $i++) { - echo sprintf('
', $i); + $str .= sprintf('
', $i); if (!empty($dressedItems->$i)) { if (!$isBattle && $isMain) { - echo sprintf('%s', + $str .= sprintf('%s', mt_rand(), $i, $dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name); } else { - echo sprintf('%s%s', + $str .= sprintf('%s%s', $dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name); } } else { - echo sprintf('Пустой слот [%s]', $i, $i); + $str .= sprintf('Пустой слот [%s]', $i, $i); } - echo sprintf('
', $i); + $str .= sprintf('
', $i); } - echo '
'; + $str .= '
'; if ($isBattle) { - echo sprintf('%s%sУровень: %s
Сила: %s
Ловкость: %s
Интуиция: %s
Выносливость: %s
Интеллект: %s
Мудрость: %s
', - $this->shadow, $this->login, $this->login, $this->level, $this->strength, $this->dexterity, $this->intuition, $this->endurance, $this->intelligence, $this->wisdom); + $str .= sprintf('%s%sУровень: %s
Сила: %s
Ловкость: %s
Интуиция: %s
Выносливость: %s
Интеллект: %s
Мудрость: %s
', + $this->shadow, $stats->getLogin(), $stats->getLogin(), $stats->getLevel(), $stats->getStat('strength'), $stats->getStat('dexterity'), $stats->getStat('intuition'), $stats->getStat('endurance'), $stats->getStat('intelligence'), $stats->getStat('wisdom')); unset($sh); } else { - echo '' . $this->login . ''; + $str .= '' . $this->login . ''; } - echo '
'; + $str .= '
'; + return $str; } - private function ttz() + public function test(): array + { + return [ + 'Сила' => $this->strength, + 'Ловкость' => $this->dexterity, + 'Интуиция' => $this->intuition, + 'Выносливость' => $this->endurance, + 'Интеллект' => $this->intelligence, + 'Мудрость' => $this->wisdom, + ]; + } + + + /** Вызов из inf.php */ + private function ttz(): string { $stat = $this->getFullStats(); $arr = [ 'Уровень' => $this->level, - 'Сила' => $this->printStat('strength'), - 'Ловкость' => $this->printStat('dexterity'), - 'Интуиция' => $this->printStat('intuition'), - 'Выносливость' => $this->printStat('endurance'), - 'Интеллект' => $this->printStat('intelligence'), - 'Мудрость' => $this->printStat('wisdom'), + 'Сила' => $this->strength, + 'Ловкость' => $this->dexterity, + 'Интуиция' => $this->intuition, + 'Выносливость' => $this->endurance, + 'Интеллект' => $this->intelligence, + 'Мудрость' => $this->wisdom, 'Уворот' => $stat->evasion, 'Точность' => $stat->accuracy, 'Шанс крита' => $stat->criticals, @@ -77,185 +89,146 @@ class UserInfo extends UserStats $str = null; $i = 0; foreach ($arr as $item => $value) { - $str .= "
$item
$value
"; - if (in_array($i,[6,9])) { + $str .= "
$item
$value
"; + if (in_array($i, [6, 9])) { $str .= "
"; } $i++; } - $nameString = $this->align ? "Склонность" : ""; - $nameString .= $this->block ? "$this->login" : "$this->login"; - $nameString .= $this->clan ? "Клан" : ""; - echo "
$nameString
"; - echo "
$str
"; + return sprintf( + "
%s
%s
", + Nick::id($this->id)->full(1), + $str + ); } - private function printStat($statName): string + private function showProgressBar(int $value, int $max_value) { - $stat = $this->getFullStats(); - return $this->getFreeStatPoints() ? $this->getStat($statName, 1) . '(' . $stat->$statName . ')' : $stat->$statName; + $values = [ + '%20%' => (int)round(self::PERCENT_20 * $max_value), + '%80%' => (int)round(self::PERCENT_80 * $max_value), + '%value' => $value, + '%max' => $max_value + ]; + $string = '%value / %max'; + return str_replace(array_keys($values), array_values($values), $string); } - //TODO вызывать из main.php - private function UserInfoStats($isMainWindow = 0) + /** Для вызова из main.php + * @throws GameException + */ + private function UserInfoStats(): string { - $stat = $this->getFullStats(); - $captions = 'Уровень:
Сила:
Ловкость:
Интуиция:
Выносливость:
Интеллект:
Мудрость:
Местонахождение:'; + $captions = 'Уровень:
Здоровье:
Пыль: +
Сила:
Ловкость:
Интуиция:
Выносливость:
Интеллект:
Мудрость: +
Опыт:
Очки характеристик:
Деньги:
Деньги в банке: + '; $variables = $this->level . '
' . - $stat->strength . '
' . - $stat->dexterity . '
' . - $stat->intuition . '
' . - $stat->endurance . '
' . - $stat->intelligence . '
' . - $stat->wisdom . '
' . - Rooms::$roomNames[$this->room]; - if ($isMainWindow) { - $captions = 'Уровень:
Здоровье:
Сила:
Ловкость:
Интуиция:
Выносливость:
Интеллект:
Мудрость:
Опыт:
Очки характеристик:
Деньги:
Деньги в банке:'; - $variables = - $this->level . '
' . - $this->health . '
' . - parent::getStat('strength', 1) . '
' . - parent::getStat('dexterity', 1) . '
' . - parent::getStat('intuition', 1) . '
' . - parent::getStat('endurance', 1) . '
' . - parent::getStat('intelligence', 1) . '
' . - parent::getStat('wisdom', 1) . '
' . - $this->experience . '
' . - $this->free_stat_points . '
' . - $this->money . '
' . - $this->bankMoney; - } - $nameString = null; - if ($this->align) { - if (file_exists("/i/align_$this->align.png")) { - $nameString .= "Склонность"; - } else { - $nameString .= ""; - } - } else { - $nameString .= ""; - } - $nameString .= $this->block ? "$this->login" : "$this->login"; - if ($this->clan) { - if (file_exists("/i/clan/$this->clan.png")) { - $nameString .= "Клан"; - } else { - $nameString .= ""; - } - } else { - $nameString .= ""; - } + $this->showProgressBar($this->health, $this->maxHealth) . '
' . + $this->showProgressBar($this->mana, $this->maxMana) . '
' . + parent::getStat('strength', 1) . '
' . + parent::getStat('dexterity', 1) . '
' . + parent::getStat('intuition', 1) . '
' . + parent::getStat('endurance', 1) . '
' . + parent::getStat('intelligence', 1) . '
' . + parent::getStat('wisdom', 1) . '
' . + $this->experience . '
' . + $this->free_stat_points . '
' . + User::getInstance()->money()->get() . '
' . + User::getInstance()->money()->getBank(); - echo <<id)->full(); + + return <<
$nameString
-
$captions
+
$captions
$variables
HTML; } - /** - * О персонаже для модераторов. - * @return string|null + public function userInfoStatsTest(): array + { + $stat = $this->getFullStats(); + return [ + 'Сила' => $this->strength, + 'Ловкость' => $this->dexterity, + 'Интуиция' => $this->intuition, + 'Выносливость' => $this->endurance, + 'Интеллект' => $this->intelligence, + 'Мудрость' => $this->wisdom, + '
HP' => $this->health . ' / ' . $this->maxHealth, + 'MP' => $this->mana . ' / ' . $this->maxMana, + 'Уворот' => $stat->evasion, + 'Точность' => $stat->accuracy, + 'Шанс крита' => $stat->criticals, + 'Урон' => $stat->min_physical_damage . ' - ' . $stat->max_physical_damage, + '
Уровень' => $this->level, + 'Опыт' => $this->experience, + 'Деньги' => $this->money()->get(), + '
Локация' => Rooms::$roomNames[$this->room], + + ]; + } + + /** Для вызова из inf.php + * @throws GameException */ - private function showPrivateData(): ?string - { - $birthday = date('d.m.Y', strtotime($this->borndate)); - $userLogs = GameLogs::getUserLogs($this->id); - $log = null; - while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) { - $log .= sprintf('%s
', date('d.m.Y H:i ', strtotime($userLogRow['date'])) . $userLogRow['text']); - } - $adminData = User::getInstance()->getAdmin() ? $this->showAdminOnlyData() : null; - return << - E-Mail: $this->email
- ДР Игрока: $birthday
- IP Регистрации: $this->ip
- $adminData
-
Личное дело
- $log -
- -INFO; - } - - /** - * О персонаже для администраторов. - * @return string|null - */ - private function showAdminOnlyData(): ?string - { - return <<id
-⁑ ИД Комнаты: $this->room
-⁑ Деньги: $this->money
-⁑ Деньги в банке: $this->bankMoney
-⁑ Опыт: $this->experience
-⁑ Нераспределённые очки: $this->free_stat_points
-INFO; - - } - - private function Info() - { - echo ''; - echo '
'; - echo ''; - if (User::getInstance()->getAdmin() || User::getInstance()->getAlign() == 1) { - echo $this->showPrivateData(); - } - } - public function showUserInfo() { - $effects = new EffectsModel($this->id); - - if ($this->block && (!User::getInstance()->getAdmin() || !User::getInstance()->getAlign() == 1)) { - echo "Персонаж $this->login заблокирован!"; - } elseif ($effects->getHideUserInfoStatus() && (!User::getInstance()->getAdmin() || !User::getInstance()->getAlign() == 1)) { - if ($effects->getHideUserInfoStatus() == -1) { - $date = 'навсегда'; - } else { - $date = 'до' . date('d.m.Y', strtotime($effects->getHideUserInfoStatus())); - } - echo "Персонаж $this->login обезличен $date."; + $str = null; + $hidden = UserEffect::hasHiddenProfile($this->id); + if ($this->block && !User::getInstance()->getAdmin()) { + $str .= "Персонаж $this->login заблокирован!"; + } elseif (!empty($hidden) && !User::getInstance()->getAdmin()) { + $str .= "Персонаж $this->login обезличен $hidden."; } else { - $this->Info(); + $str .= ''; + $str .= '
'; + $str .= ''; + if (User::getInstance()->getAdmin()) { + $str .= UserPrivateInfo::get(User::getInstance()); + } + } + echo $str; + } + + public function showUserDoll($isBattle = 0, $isMain = 0): string + { + try { + return ''; + } catch (GameException $e) { + return $e; } } - public function showUserDoll($isBattle = 0, $isMain = 0) + /** Отображение на main.php + */ + public function showUserInfoMain(): string { - echo ''; - } - - public function showUserInfoMain() - { - echo ''; + try { + return '
' . $this->UserInfoDoll() . '
' . $this->userInfoStats(); + } catch (GameException $e) { + return $e; + } } public function showUserEffects(): string { - $effs = Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $this->id); - $img = UserEffects::$effectImage; + $effs = Effects::getAll($this->id); + $img = UserEffect::$effectImage; $r = ''; foreach ($effs as $effect) { $timeleft = timeOut($effect->remaining_time - time()); diff --git a/classes/Battles/UserMoney.php b/classes/Battles/UserMoney.php new file mode 100644 index 0000000..3fabf9f --- /dev/null +++ b/classes/Battles/UserMoney.php @@ -0,0 +1,71 @@ +uid = $uid; + $this->wallet_money = $money; + $this->initBank(); + } + + private function initBank() + { + $this->bank = new Bank($this->uid); + } + + public function get(): int + { + return $this->wallet_money; + } + + public function set(int $money) + { + $this->wallet_money = max($money, 0); + } + + public function getBank(): int + { + return $this->bank->getMoney(); + } + + public function modifyBank(int $money, string $logType = '') + { + $this->bank->modify($money, $logType); + } + + private function save() + { + Db::getInstance()->execute('update users set money = ? where id = ?', [$this->wallet_money, $this->uid]); + } + + /** Тратим деньги */ + public function spend(int $value): bool + { + if ($this->wallet_money > $value && $value > 0) { + $this->wallet_money -= $value; + $this->save(); + return true; + } + return false; + } + + /** Получаем деньги */ + public function earn(int $value): bool + { + if ($value <= 0) { + return false; + } + $this->wallet_money += $value; + $this->save(); + return true; + } +} \ No newline at end of file diff --git a/classes/Battles/UserPrivateInfo.php b/classes/Battles/UserPrivateInfo.php new file mode 100644 index 0000000..c5e1fdb --- /dev/null +++ b/classes/Battles/UserPrivateInfo.php @@ -0,0 +1,36 @@ +getId()); + $log = null; + while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) { + $log .= sprintf('%s
', date('d.m.Y H:i ', strtotime($userLogRow['date'])) . $userLogRow['text']); + } + $data = [ + '%email' => $user->profile()->getEmail(), + '%bday' => date('d.m.Y', strtotime($user->profile()->getBorndate())), + '%regip' => $user->profile()->getIp(), + '%uid' => $user->getId(), + '%room' => $user->getRoom(), + '%wallet' => $user->money()->get(), + '%bank' => Db::getInstance()->fetchColumn('select money from bank where user_id = ?', $user->getId()), + '%exp' => $user->getExperience(), + '%fp' => Db::getInstance()->fetchColumn('select free_stat_points from users where id = ?', $user->getId()), + '%log' => $log ?? 'Журнал пуст.', + ]; + $string = '
E-Mail: %email
ДР Игрока: %bday
IP Регистрации: %regip
+ ⁑ ИД Игрока: %uid
⁑ ИД Комнаты: %room
⁑ Деньги: %wallet
⁑ Деньги в банке: %bank
+ ⁑ Опыт: %exp
⁑ Нераспределённые очки: %fp

+
Личное дело
%log
+
'; + return str_replace(array_keys($data), array_values($data), $string); + } +} \ No newline at end of file diff --git a/classes/Battles/UserProfile.php b/classes/Battles/UserProfile.php new file mode 100644 index 0000000..775089f --- /dev/null +++ b/classes/Battles/UserProfile.php @@ -0,0 +1,163 @@ +id = $id; + $this->pass = $pass; + $this->email = $email; + $this->realname = $realname; + $this->borndate = $borndate; + $this->info = $info; + $this->ip = $ip; + } + + + + public function changePassword($old_password, $new_password) + { + if (password_verify($old_password, $this->pass)) { + $this->pass = password_hash($new_password, PASSWORD_DEFAULT); + } else { + $this->status .= 'Неверный пароль!'; + } + } + + /** + * @return string + */ + public function getEmail(): string + { + return $this->email; + } + + /** + * @param string $email + */ + public function setEmail(string $email): void + { + $this->email = $email; + } + + /** + * @return string + */ + public function getRealname(): string + { + return $this->realname; + } + + /** + * @param string $realname + */ + public function setRealname(string $realname): void + { + $this->realname = htmlspecialchars($realname); + } + + /** + * @return string + */ + public function getBorndate(): string + { + return $this->borndate; + } + + /** + * @param string $borndate + */ + public function setBorndate(string $borndate): void + { + $this->borndate = $borndate; + } + + /** + * @return string + */ + public function getInfo(): string + { + return $this->info; + } + + /** + * @param string $info + */ + public function setInfo(string $info): void + { + if (strlen($info) > self::INFO_CHAR_LIMIT) { + $this->status .= 'Максимальная длинна поля Хобби: ' . self::INFO_CHAR_LIMIT . ' символов!'; + } else { + $info = htmlspecialchars($info); + $info = str_replace("\\n", '
', $info); + $info = str_replace("\\r", '', $info); + $info = str_replace('<br />', '
', $info); + $this->info = $info; + } + } + + /** + * @return string + */ + public function getIp(): string + { + return $this->ip; + } + + /** Сохраняет в базу актуальные имя, пароль, email, дату рождения, текст инфы. + * + */ + public function save(): string + { + if ($this->status) { + return $this->status; + } + + $query = 'update users set pass = ?, email = ?, realname = ?, borndate = ?, info = ? where id = ?'; + $vals = [ + //set + $this->pass, + $this->email, + $this->realname, + $this->borndate, + $this->info, + // where + $this->id + ]; + Db::getInstance()->execute($query, $vals); + return 'Успешно!'; + } + +} \ No newline at end of file diff --git a/classes/Battles/UserStats.php b/classes/Battles/UserStats.php index 676bfb0..7a18e50 100644 --- a/classes/Battles/UserStats.php +++ b/classes/Battles/UserStats.php @@ -3,33 +3,35 @@ namespace Battles; -use Battles\Database\Db; +use Battles\Models\Inventory; +use Battles\Models\User\Effects; +use Battles\Models\User\Stats; use Exceptions\GameException; class UserStats extends User { - protected $strength; - protected $dexterity; - protected $intuition; - protected $endurance; - protected $intelligence; - protected $wisdom; - protected $health; - protected $mana; - protected $free_stat_points; + protected int $id; + protected int $strength; + protected int $dexterity; + protected int $intuition; + protected int $endurance; + protected int $intelligence; + protected int $wisdom; + protected int $health; + protected int $mana; + protected int $free_stat_points = 0; + protected int $level; private const STAT_MAXIMUM_AMOUNT = 40; private const ERROR_STAT_IS_MAXIMUM = 'Ошибка: Параметр достиг своего лимита!'; private const ERROR_STAT_UNKNOWN = 'Ошибка: Неизвестный параметр!'; + private const STAT_NAMES_ARRAY = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom']; //// Неизменяемые для игрока(!) переменные. // Удар кулаком всегда 1-2. protected int $minDamage = 1; protected int $maxDamage = 2; // Природная броня всегда 0. - // Зачем их три, если во всех формулах она одна? - protected int $headArmor = 0; - protected int $chestArmor = 0; - protected int $legArmor = 0; + // Динамически рассчитываемые protected int $maxHealth; protected int $maxMana; @@ -41,6 +43,19 @@ class UserStats extends User */ public function __construct($user) { + + $data = Stats::getAll($user); + $this->id = $data->id; + $this->strength = $data->strength; + $this->dexterity = $data->dexterity; + $this->intuition = $data->intuition; + $this->endurance = $data->endurance; + $this->intelligence = $data->intelligence; + $this->wisdom = $data->wisdom; + $this->health = $data->health; + $this->mana = $data->mana; + $this->free_stat_points = $data->free_stat_points; + $this->level = $data->level; parent::__construct($user); $this->maxHealth = round(($this->endurance * 3) + ($this->endurance / 2) * ($this->level - 1) + ($this->endurance / 5) * (($this->level - 1) * ($this->level - 2) / 2)); $this->maxMana = round(($this->wisdom * 3) + ($this->wisdom / 2) * ($this->level - 1) + ($this->wisdom / 5) * (($this->level - 1) * ($this->level - 2) / 2)); @@ -49,23 +64,25 @@ class UserStats extends User /** * Отдаёт информацию о базовом(!) стате. * - * @param $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', - * 'endurance', 'intelligence', 'wisdom'. - * @param int $isMainWindow - переключатель "главного окна". Если включить, дополнительно будет показывать ссылку - * на повышение стата на 1, при условии наличия свободных очков статов. + * @param string $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', + * 'endurance', 'intelligence', 'wisdom'. + * @param int $isMainWindow - переключатель "главного окна". Если включить, дополнительно будет показывать ссылку + * на повышение стата на 1, при условии наличия свободных очков статов. * * @return string + * @throws GameException */ - public function getStat($stat_name, int $isMainWindow = 0): string + public function getStat(string $stat_name, int $isMainWindow = 0): string { - if (!in_array($stat_name, ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'])) { - return self::ERROR_STAT_UNKNOWN; + if (!in_array($stat_name, self::STAT_NAMES_ARRAY)) { + throw new GameException(self::ERROR_STAT_UNKNOWN); } + $stat = strval($this->$stat_name); if ($this->free_stat_points && $isMainWindow && $this->$stat_name < self::STAT_MAXIMUM_AMOUNT) { - $this->$stat_name .= " [+]"; + $rand = strval(mt_rand()); + $stat .= " [+]"; } - return $this->$stat_name; - + return $stat; } /** @@ -79,20 +96,19 @@ class UserStats extends User */ public function addOnePointToStat(string $stat_name) { - if (!in_array($stat_name, ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'])) { + if (!in_array($stat_name, self::STAT_NAMES_ARRAY)) { throw new GameException(self::ERROR_STAT_UNKNOWN); } if ($this->free_stat_points <= 0 || $this->$stat_name >= self::STAT_MAXIMUM_AMOUNT) { throw new GameException(self::ERROR_STAT_IS_MAXIMUM); } else { - $query = "UPDATE users SET {$stat_name} = {$stat_name} + 1, free_stat_points = free_stat_points - 1 WHERE id = ?"; - Db::getInstance()->execute($query, $this->id); + Stats::addOne($stat_name, $this->id); } } public function getMaxWeight(): int { - return $this->strength * 4; + return max($this->strength * 5, 50); } /** @@ -135,71 +151,21 @@ class UserStats extends User return $this->maxMana; } - /** - * @return int - */ - public function getHeadArmor(): int - { - return $this->headArmor; - } - - /** - * @return int - */ - public function getChestArmor(): int - { - return $this->chestArmor; - } - - /** - * @return int - */ - public function getLegArmor(): int - { - return $this->legArmor; - } - public function getFullStats(): object { - $stats = Db::getInstance()->ofetch(" - select - strength, - dexterity, - intuition, - endurance, - intelligence, - wisdom - from users where id = $this->id"); - $itemBonuses = Db::getInstance()->ofetch(" - select - sum(add_strength) as item_strength, - sum(add_dexterity) as item_dexterity, - sum(add_intuition) as item_intuition, - sum(add_endurance) as item_endurance, - sum(add_intelligence) as item_intelligence, - sum(add_wisdom) as item_wisdom, - sum(add_accuracy) as item_accuracy, - sum(add_evasion) as item_evasion, - sum(add_criticals) as item_criticals, - sum(add_min_physical_damage) as item_min_physical_damage, - sum(add_max_physical_damage) as item_max_physical_damage - from inventory where dressed_slot != 0 and owner_id = $this->id"); - $effectBonuses = Db::getInstance()->ofetch(" - select - sum(mod_strength) as effect_strength, - sum(mod_dexterity) as effect_dexterity, - sum(mod_intuition) as effect_intuition, - sum(mod_endurance) as effect_endurance, - sum(mod_intelligence) as effect_intelligence, - sum(mod_wisdom) as effect_wisdom - from users_effects where owner_id = $this->id"); + $stats = Stats::getAll($this->id); + $itemBonuses = Inventory::getBonuses($this->id); + $effectBonuses = Effects::getStatMods($this->id); $obj = (object)[]; - $obj->strength = max(0,$stats->strength + $itemBonuses->item_strength + $effectBonuses->effect_strength); - $obj->dexterity = max(0,$stats->dexterity + $itemBonuses->item_dexterity + $effectBonuses->effect_dexterity); - $obj->intuition = max(0,$stats->intuition + $itemBonuses->item_intuition + $effectBonuses->effect_intuition); - $obj->endurance = max(0,$stats->endurance + $itemBonuses->item_endurance + $effectBonuses->effect_endurance); - $obj->intelligence = max(0,$stats->intelligence + $itemBonuses->item_intelligence + $effectBonuses->effect_intelligence); - $obj->wisdom = max(0,$stats->wisdom + $itemBonuses->item_wisdom + $effectBonuses->effect_wisdom); + foreach (self::STAT_NAMES_ARRAY as $stat) { + $obj->$stat = max(0, $stats->$stat + $itemBonuses->{'item_' . $stat} + $effectBonuses->{'effect_' . $stat}); + } + //$obj->strength = max(0, $stats->strength + $itemBonuses->item_strength + $effectBonuses->effect_strength); + //$obj->dexterity = max(0, $stats->dexterity + $itemBonuses->item_dexterity + $effectBonuses->effect_dexterity); + //$obj->intuition = max(0, $stats->intuition + $itemBonuses->item_intuition + $effectBonuses->effect_intuition); + //$obj->endurance = max(0, $stats->endurance + $itemBonuses->item_endurance + $effectBonuses->effect_endurance); + //$obj->intelligence = max(0, $stats->intelligence + $itemBonuses->item_intelligence + $effectBonuses->effect_intelligence); + //$obj->wisdom = max(0, $stats->wisdom + $itemBonuses->item_wisdom + $effectBonuses->effect_wisdom); $obj->accuracy = max(0, $itemBonuses->item_accuracy); $obj->evasion = max(0, $itemBonuses->item_evasion); $obj->criticals = max(0, $itemBonuses->item_criticals); @@ -212,7 +178,7 @@ class UserStats extends User { $this->level += 1; $this->free_stat_points += 2; - $this->saveStats(); + $this->save(); Chat::addSYSMessage('Внимание, вы получили ' . $this->level . 'уровень. Доступны очки распределения параметров.'); return 'Персонаж перешёл на ' . $this->level . 'уровень.'; } @@ -220,12 +186,9 @@ class UserStats extends User /** Сохраняет в базу актуальные статы, здоровье, ману, свободные очки статов и уровень. * */ - private function saveStats() + private function save() { - $query = 'update users set strength = ?, dexterity = ?, intuition = ?, endurance = ?, - intelligence = ?, wisdom = ?, health = ?, mana = ?, free_stat_points = ?, - level = ? where id = ?'; - $vals = [ + Stats::save([ $this->strength, //set $this->dexterity, $this->intuition, @@ -237,7 +200,6 @@ class UserStats extends User $this->free_stat_points, $this->level, $this->id //where - ]; - Db::getInstance()->execute($query, $vals); + ]); } } \ No newline at end of file diff --git a/classes/Battles/Users.php b/classes/Battles/Users.php new file mode 100644 index 0000000..76dddd5 --- /dev/null +++ b/classes/Battles/Users.php @@ -0,0 +1,29 @@ +execute('select count(*) from users where login = ? or email = ?', [$login, $email])->fetchColumn()) { + $password = password_hash($password, PASSWORD_DEFAULT); + $email = filter_var($email, FILTER_VALIDATE_EMAIL); + + if ( + !$email || + Db::getInstance()->execute('select count(*) from users where login = ? or email = ?', [$login, $email])->fetchColumn() + ) { return 0; } Db::getInstance()->execute('insert into users (login,pass,email,borndate,ip,session_id,shadow) values (?,?,?,?,?,?,?)', diff --git a/classes/Cave/CaveBots.php b/classes/_old/Cave/CaveBots.php similarity index 100% rename from classes/Cave/CaveBots.php rename to classes/_old/Cave/CaveBots.php diff --git a/classes/Cave/CaveItems.php b/classes/_old/Cave/CaveItems.php similarity index 100% rename from classes/Cave/CaveItems.php rename to classes/_old/Cave/CaveItems.php diff --git a/classes/Cave/lose.php b/classes/_old/Cave/lose.php similarity index 100% rename from classes/Cave/lose.php rename to classes/_old/Cave/lose.php diff --git a/classes/Cave/win.php b/classes/_old/Cave/win.php similarity index 100% rename from classes/Cave/win.php rename to classes/_old/Cave/win.php diff --git a/classes/Tournament.php b/classes/_old/Tournament.php similarity index 100% rename from classes/Tournament.php rename to classes/_old/Tournament.php diff --git a/classes/battle_new.class.php b/classes/_old/battle_new.class.php similarity index 99% rename from classes/battle_new.class.php rename to classes/_old/battle_new.class.php index 64d55b9..2f773af 100644 --- a/classes/battle_new.class.php +++ b/classes/_old/battle_new.class.php @@ -1612,9 +1612,9 @@ class fbattle addchp('Внимание! Победа! Бой окончен. Всего вами нанесено урона : ' . $this->damage[$v] . ' HP. Получено опыта : ' . $this->exp[$v] . ' (' . $dop_exp . '%)' . $ads . ' ', '{[]}' . Nick::id($v)->short() . '{[]}'); mysql_query('UPDATE `users` SET `win` = (`win` +1), `fullhptime` = ' . time() . ' WHERE `id` = "' . $v . '"'); - GiveExp($v, $this->exp[$v]); + \Battles\User::getInstance($v)->addExperience($this->exp[$v]); if ($user['caveleader'] > 0 || $user['laba'] > 0) { - GiveRep($v, $rep); + \Battles\User::getInstance($v)->addExperience($rep); } if ($user['klan']) { mysql_query('UPDATE `clans` SET `clanexp` = (`clanexp`+' . (int)$this->exp[$user['id']] . ') WHERE `id` = "' . $v[$user['klan']] . '" LIMIT 1'); @@ -1628,7 +1628,7 @@ class fbattle $flag = 2; foreach ($this->t2 as $k => $v) { mysql_query('UPDATE `battle` SET `win` = 2 WHERE `id` = "' . $this->user['battle'] . '" LIMIT 1'); - $this->t2[$k] = Nick::id($v)->short(); + $this->t2[$k] = \Battles\Nick::id($v)->short(); if ($this->battle_data['aren_of'] == 1 && $this->t2[$k] && $v < _BOTSEPARATOR_) { mysql_query('INSERT INTO `logs_arena` (`battle`, `user`, `uid`, `damage`, `team`) VALUES ("' . $this->user['battle'] . '", "' . $this->t1[$k] . '", "' . $v . '", "' . $this->damage[$v] . '", "2")'); @@ -1668,9 +1668,9 @@ class fbattle echo ""; } mysql_query('UPDATE `users` SET `win` = (`win` +1), `fullhptime` = ' . time() . ' WHERE `id` = "' . $v . '"'); - GiveExp($v, $this->exp[$v]); + \Battles\User::getInstance($v)->addExperience($this->exp[$v]); if ($user['caveleader'] > 0 || $user['laba'] > 0) { - GiveRep($v, $rep); + \Battles\User::getInstance($v)->addExperience($rep); } if ($user['klan']) { mysql_query('UPDATE `clans` SET `clanexp` = (`clanexp`+' . (int)$this->exp[$user['id']] . ') WHERE `id` = "' . $v[$user['klan']] . '" LIMIT 1'); diff --git a/classes/class.upload.php b/classes/_old/class.upload.php similarity index 100% rename from classes/class.upload.php rename to classes/_old/class.upload.php diff --git a/classes/quests_class.php b/classes/_old/quests_class.php similarity index 99% rename from classes/quests_class.php rename to classes/_old/quests_class.php index 82c3f28..77e06f7 100644 --- a/classes/quests_class.php +++ b/classes/_old/quests_class.php @@ -419,7 +419,7 @@ TASK; return $ins; } - public function timeOut($ttm) + public function timeOut($ttm): string { $out = ''; $time_still = $ttm; @@ -590,5 +590,3 @@ TASK; fclose($fp); } } - -$q = new Quests; \ No newline at end of file diff --git a/classes/showpers.php b/classes/showpers.php deleted file mode 100644 index a58750b..0000000 --- a/classes/showpers.php +++ /dev/null @@ -1,44 +0,0 @@ - - * Project name: Battles-Game - */ - -class showpers -{ - private $pers_data; - private $weared_items; - - private function __construct($id) - { - if (!$this->pers_data) { - $query = db::c()->query('SELECT * FROM `users` WHERE `id` = ?i', $id)->fetch_assoc(); - $this->pers_data = $query; - } - if (!$this->weared_items) { - $query = db::c()->query('SELECT `name`, `img`, `type` FROM `inventory` WHERE `owner` = ?i AND `dressed` = 1', $id); - $this->weared_items = $query; - } - } - - private function dgfs() - { - $w_items['sergi'] = $this->pers_data['sergi']; - $w_items['kulon'] = $this->pers_data['kulon']; - $w_items['weap'] = $this->pers_data['weap']; - $w_items['bron'] = $this->pers_data['bron']; - $w_items['r1'] = $this->pers_data['r1']; - $w_items['r2'] = $this->pers_data['r2']; - $w_items['r3'] = $this->pers_data['r3']; - $w_items['helm'] = $this->pers_data['helm']; - $w_items['perchi'] = $this->pers_data['perchi']; - $w_items['shit'] = $this->pers_data['shit']; - $w_items['boots'] = $this->pers_data['boots']; - $w_items['rubax'] = $this->pers_data['rubax']; - $w_items['plaw'] = $this->pers_data['plaw']; - $w_items['rune1'] = $this->pers_data['rune1']; - $w_items['rune2'] = $this->pers_data['rune2']; - $w_items['rune3'] = $this->pers_data['rune3']; - } -} diff --git a/config.php b/config.php index b8acd9b..4ed6198 100644 --- a/config.php +++ b/config.php @@ -33,7 +33,7 @@ header("Cache-Control: post-check=0, pre-check=0", false); */ spl_autoload_register(function ($className) { - $fileName = __DIR__ . '/classes/' . str_replace('\\', '/', $className . '.php'); + $fileName = __DIR__ . '/classes/' . str_replace('\\', DIRECTORY_SEPARATOR, $className . '.php'); if (file_exists($fileName)) { require_once $fileName; } diff --git a/cronjobs/cron_bots_battle.php b/cronjobs/cron_bots_battle.php index 074dc4e..ad10a33 100644 --- a/cronjobs/cron_bots_battle.php +++ b/cronjobs/cron_bots_battle.php @@ -372,9 +372,9 @@ class fbattle addchp('Внимание! Победа! Бой окончен. Всего вами нанесено урона : ' . $this->damage[$v] . ' HP. Получено опыта : ' . $this->exp[$v] . ' (' . $dop_exp . '%)' . $ads . ' ', '{[]}' . Nick::id($v)->short() . '{[]}'); mysql_query('UPDATE `users` SET `win` = (`win` +1), `fullhptime` = ' . time() . ' WHERE `id` = "' . $v . '"'); - GiveExp($v, $this->exp[$v]); + \Battles\User::getInstance($v)->addExperience($this->exp[$v]); if ($user['caveleader'] > 0 || $user['laba'] > 0) { - GiveRep($v, $rep); + \Battles\User::getInstance($v)->addExperience($rep); } if ($user['klan']) { mysql_query('UPDATE `clans` SET `clanexp` = (`clanexp`+' . (int)$this->exp[$user['id']] . ') WHERE `id` = "' . $v[$user['klan']] . '" LIMIT 1'); @@ -449,7 +449,7 @@ class fbattle addchp('Внимание! Победа! Бой окончен. Всего вами нанесено урона : ' . (int)$this->damage[$v] . ' HP. Получено опыта ' . $this->exp[$v] . ' (' . $dop_exp . '%). ', '{[]}' . Nick::id($v)->short() . '{[]}'); mysql_query('UPDATE `users` SET `win` = (`win`+1), `fullhptime` = ' . time() . ' WHERE `id` = "' . $v . '"'); - GiveExp($v, $this->exp[$v]); + \Battles\User::getInstance($v)->addExperience($this->exp[$v]); } $winers .= implode(", ", $this->t2); diff --git a/css/main.css b/css/main.css index 5e58d53..f201b6a 100644 --- a/css/main.css +++ b/css/main.css @@ -319,7 +319,7 @@ img.tip:hover + span.tiptext { /* Отображение информации о персонаже в inf.php (класс User.php) */ div.user-info-container { display: grid; - grid-template-columns: repeat(4, 75px) auto 100px; + grid-template-columns: repeat(4, 75px) auto; grid-template-rows: repeat(5, 75px) auto; grid-gap: 10px; } @@ -409,11 +409,68 @@ div.user-info-container > div.user-info > div.stats-container > div.column { div.user-info-container > div.user-info > div.stats-container > div.column + div.column { text-align: left; } - -div.user-info-container > div.user-signs { - grid-column: 6; - grid-row: 1 / 6; +/*--DOLL-----------------------*/ +div.user-doll-container { + display: grid; + grid-template-columns: repeat(4, 75px); + grid-template-rows: repeat(5, 75px); + grid-gap: 10px; + float: left; + margin-right: 10px; } + +div.user-doll-container > div.slot-1, +div.user-doll-container > div.slot-2, +div.user-doll-container > div.slot-3, +div.user-doll-container > div.slot-4 { + grid-column: 1; +} + +div.user-doll-container > div.slot-5, +div.user-doll-container > div.slot-6, +div.user-doll-container > div.slot-7, +div.user-doll-container > div.slot-8 { + grid-column: 4; +} + +div.user-doll-container > div.slot-1, +div.user-doll-container > div.slot-5 { + grid-row: 1; +} + +div.user-doll-container > div.slot-2, +div.user-doll-container > div.slot-6 { + grid-row: 2; +} + +div.user-doll-container > div.slot-3, +div.user-doll-container > div.slot-7 { + grid-row: 3; +} + +div.user-doll-container > div.slot-4, +div.user-doll-container > div.slot-8 { + grid-row: 4; +} + +div.user-doll-container > div.slot-9, +div.user-doll-container > div.slot-10, +div.user-doll-container > div.slot-11, +div.user-doll-container > div.slot-12 { + grid-row: 5; +} + +div.user-doll-container > div.slot-image { + grid-column: 2 / 4; + grid-row: 1 / 5; +} + +div.user-doll-container > div.slot-image > img { + width: 160px; + height: 330px; + border-radius: 5px; +} + /*-----------------------------*/ div.debug { background:#fef; @@ -422,14 +479,14 @@ div.debug { padding:5px; margin: 3px; } -div.secret-info { +.secret-info { background:#fee; border:1px dashed #faa; border-radius:5px; padding:5px; margin: 3px; } -div.secret-info > span { +.secret-info > span { color: #966; } /* for classes/City.php included in /city.php */ diff --git a/fbattle.php b/fbattle.php index 0a821f1..eeba11a 100644 --- a/fbattle.php +++ b/fbattle.php @@ -132,10 +132,7 @@ $fbattle = new fbattle($user['battle']);
- showUserDoll(1); - ?> + userInfo()->showUserDoll(1) ?>
@@ -160,7 +157,7 @@ $fbattle = new fbattle($user['battle']); $dressed = db::c()->query('SELECT `id` FROM `inventory` WHERE `id` = ?i AND `dressed` = 1', $_GET['use'])->fetch_row(); if ((int)$dressed[0] > 0) { $my_class = $fbattle->my_class; - usemagic($_GET['use'], "" . $_POST['target']); + $bb = explode(" -
- Снять все
-
- showUserEffects() ?> -
-
-
- - -
-
Уровень: getLevel() ?> -
Опыт: getExperience() ?> -
Побед: ?? -
Поражений: ?? -
Ничьих: ?? -
Деньги: getMoney() ?> кр. -
-
- -
-
- Сила: getFreeStatPoints() ? $userStats->getStat('strength', 1) . '(' . strval($stat->strength) . ')' : $stat->strength) ?> -
- Ловкость: getFreeStatPoints() ? $userStats->getStat('dexterity', 1) . '(' . strval($stat->dexterity) . ')' : $stat->dexterity) ?> -
- Интуиция: getFreeStatPoints() ? $userStats->getStat('intuition', 1) . '(' . strval($stat->intuition) . ')' : $stat->intuition) ?> -
- Выносливость: getFreeStatPoints() ? $userStats->getStat('endurance', 1) . '(' . strval($stat->endurance) . ')' : $stat->endurance) ?> -
- Интеллект: getFreeStatPoints() ? $userStats->getStat('intelligence', 1) . '(' . strval($stat->intelligence) . ')' : $stat->intelligence) ?> -
- Мудрость: getFreeStatPoints() ? $userStats->getStat('wisdom', 1) . '(' . strval($stat->wisdom) . ')' : $stat->wisdom) ?> -
- getFreeStatPoints()): ?> - Возможных - увеличений: getFreeStatPoints() ?>
- -
- - Здоровье: - getHealth() ?> -
- Пыль: - getMana() ?> -
- Уворот: evasion ?>
- Точность: accuracy ?>
- Шанс крита: criticals ?>
- Урон: min_physical_damage ?> - - max_physical_damage ?>
-
- Защита от огня: ??
- Защита от воды: ??
- Защита от вохдуха: ??
- Защита от земли: ??
- Защита от яда: ??
- Броня головы: getHeadArmor() ?>
- Броня корпуса: getChestArmor() ?>
- Броня ног: getLegArmor() ?>
-
-
- - -
-
- getShadow() == '0.gif' || User::getInstance()->getAdmin() == 1): ?> - - -
- getRoom() == 20): ?> - - getRoom() == 1): ?> - - - - - -
-
-
- - -
Рюкзак - (масса: getMaxWeight() ?>) -
"; - $ii->printImage(); - $ii->printControls(); - echo ""; - $ii->printInfo(); - } - if (!$data) { - echo "
Пусто"; - } - ?> -
-
- - - \ No newline at end of file +include_once 'views/main-game.php'; diff --git a/module_quest.php b/module_quest.php index ce74894..97ef714 100644 --- a/module_quest.php +++ b/module_quest.php @@ -6,32 +6,29 @@ use Battles\User; require_once 'functions.php'; require_once 'classes/quests_class.php'; -$qEndNow = $_GET['end_qst_now'] ?? null; -$qEnd = $_GET['end_qst'] ?? null; - -if ($qEndNow) { +if (!empty($_GET['end_qst_now'])) { $q->endq((int)$_GET['end_qst_now'], 'end', $user); } -if ($qEnd) { +if (!empty($_GET['end_qst'])) { $q->winqst((int)$_GET['end_qst'], $user); } -$qsee = ''; -$qx = 0; +$qsee = null; $error = ''; +$q = new Quests(); Template::header('module_quest'); ?> query('SELECT `vars` FROM `actions` WHERE `vars` LIKE "?S" AND `vals` = "?s" AND `uid` = ?i LIMIT 100', "%start_quest%", "go", User::getInstance()->getId()); -while ($pl = $sp->fetch_assoc()) { - $questId = str_replace('start_quest', '', $pl['vars']); - $pq = db::c()->query('SELECT `id`,`name`,`info` FROM `quests` WHERE `id` = ?i', $questId)->fetch_assoc(); - $qsee .= sprintf(' %sВыполнить
%s
$s

', $pq['id'], $pq['name'], $pq['id'], $pq['info'], $q->info($pq, User::getInstance()->getId())); - $qx++; -} + +//$sp = \Battles\Database\Db::getInstance()->fetchall('select vars from actions where vars like ? and vals = ? and uid = ? limit 100', ['%start_quest%', 'go', User::getInstance()->getId()]); +//foreach ($sp as $row) { +// $questId = str_replace('start_quest', '', $pl['vars']); +// $pq = \Battles\Database\Db::getInstance()->fetch('select id, name, info from quests where is = ?', $questId); +// $qsee .= sprintf(' %sВыполнить
%s
$s

', $pq['id'], $pq['name'], $pq['id'], $pq['info'], $q->info($pq, User::getInstance()->getId())); +//} if (!$qsee) { $qsee = 'У вас нет заданий.'; @@ -42,8 +39,9 @@ if ($q->error) { ?>
-
Состояние персонажа,
+
+ Состояние персонажа, getLogin() ?> +
diff --git a/podzem_dialog.php b/podzem_dialog.php index cdf49e4..801665d 100644 --- a/podzem_dialog.php +++ b/podzem_dialog.php @@ -28,7 +28,7 @@ Template::header('Подземелье Луки');
- showUserDoll(); ?> + showUserDoll() ?>
@@ -291,8 +291,7 @@ Template::header('Подземелье Луки'); fetch('select * from users where login = ?', 'Лука'); //Этот класс не умеет работать с ботами! Этот вызов - заглушка! - $botInfo = new UserInfo('Лука'); - $botInfo->showUserDoll(); + echo User::getInstance('Лука')->userInfo()->showUserDoll(); ?> diff --git a/post.php b/post.php index 9728c75..162b943 100644 --- a/post.php +++ b/post.php @@ -1,13 +1,12 @@ getMoney()) { + if ($submit == 'sendMessage' && User::getInstance()->money()->get()) { if ($telegraphText) { - User::getInstance()->setMoney(User::getInstance()->getMoney() - 1); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); - db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, $telegraphText); - $statusMessage = 'Сообщение отправлено.'; + if (User::getInstance()->money()->spend(1)) { + db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, $telegraphText); + $statusMessage = 'Сообщение отправлено.'; + } else { + $statusMessage = 'Недостаточно денег.'; + } } else { $statusMessage = 'Сообщение было оставлено пустым!'; } } - if ($submit == 'sendItem' && $sendItemId && User::getInstance()->getMoney()) { - $res = db::c()->query('SELECT name FROM inventory WHERE owner_id = ?i AND item_id = ?i AND dressed_slot = 0 AND on_sale = 0', User::getInstance()->getId(), $sendItemId)->fetch_assoc(); - if (!$res) { + if ($submit == 'sendItem' && $sendItemId && User::getInstance()->money()->get()) { + $itemName = Db::getInstance()->fetchColumn('select name from inventory where owner_id = ? and item_id = ? and dressed_slot = 0 and on_sale = 0', [User::getInstance()->getId(), $sendItemId]); + if (!$itemName) { $statusMessage = "Предмет не найден в рюкзаке."; } else { - User::getInstance()->setMoney(User::getInstance()->getMoney() - 1); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); - db::c()->query('UPDATE `inventory` SET owner_id = ?i WHERE item_id= ?i AND owner_id = ?i', $receiverId, $sendItemId, $_SESSION['uid']); - $statusMessage = 'Предмет "' . $res['name'] . '" передан персонажу ' . User::getInstance($receiverId)->getLogin(); - $receiverLogMessage = 'Получен предмет "' . $res['name'] . '" от персонажа ' . User::getInstance()->getLogin(); - db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, 'Почтовый перевод: ' . $res['name'] . ' от персонажа ' . $user['login'] . '.'); - // Пишем в лог отправителю. - GameLogs::addUserLog($_SESSION['uid'], $statusMessage, 'почта'); - // Пишем в лог получателю. - GameLogs::addUserLog($receiverId, $receiverLogMessage, 'почта'); + if (User::getInstance()->money()->spend(1)) { + db::c()->query('UPDATE `inventory` SET owner_id = ?i WHERE item_id= ?i AND owner_id = ?i', $receiverId, $sendItemId, $_SESSION['uid']); + $statusMessage = 'Предмет "' . $itemName . '" передан персонажу ' . User::getInstance($receiverId)->getLogin(); + $receiverLogMessage = 'Получен предмет "' . $itemName . '" от персонажа ' . User::getInstance()->getLogin(); + db::c()->query('INSERT INTO `telegraph` (`receiver`,`text`) VALUES (?i,"?s")', $receiverId, 'Почтовый перевод: ' . $itemName . ' от персонажа ' . $user['login'] . '.'); + // Пишем в лог отправителю. + GameLogs::addUserLog($_SESSION['uid'], $statusMessage, 'почта'); + // Пишем в лог получателю. + GameLogs::addUserLog($receiverId, $receiverLogMessage, 'почта'); + } else { + $statusMessage = 'Недостаточно денег.'; + } } } @@ -93,7 +96,9 @@ Template::header('Почта');
Передача предметов - +
printImage(); ?> @@ -109,7 +114,7 @@ Template::header('Почта'); getNumRows())): ?>
Нечего передавать... - +
diff --git a/presents.php b/presents.php index a3bc58e..570dadf 100644 --- a/presents.php +++ b/presents.php @@ -13,7 +13,6 @@ * */ -use Battles\Bank; use Battles\Template; use Battles\User; @@ -47,7 +46,7 @@ if (!empty($_POST['sendAction'])) { $_POST['days'] = 1; } $cost = $_POST['days'] * 5; - if (User::getInstance()->getMoney() < $cost) { + if (!User::getInstance()->money()->spend($cost)) { $status = "Не хватает кредитов на оплату подарка!"; return; } @@ -60,9 +59,8 @@ if (!empty($_POST['sendAction'])) { $sender = "Подарок от " . User::getInstance()->getLogin(); } - User::getInstance()->setMoney(User::getInstance()->getMoney() - $cost); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); - db::c()->query('INSERT INTO users_presents (owner, img, text, sender, expiration_date) VALUES (?i,"?s","?s","?s",DATE_ADD(CURDATE(),INTERVAL ?i DAY))', $receiver['id'], $_POST['present'], $_POST['text'], $sender, $_POST['days']); + \Battles\Database\Db::getInstance()->execute('insert into users_presents (owner_id, sender_id, image) values (?,?,?)', [$receiver['id'], $sender, $_POST['present']]); + //db::c()->query('INSERT INTO users_presents (owner, img, text, sender, expiration_date) VALUES (?i,"?s","?s","?s",DATE_ADD(CURDATE(),INTERVAL ?i DAY))', $receiver['id'], $_POST['present'], $_POST['text'], $sender, $_POST['days']); $telegraphText = "Вам пришёл подарок от {$sender}!"; db::c()->query('INSERT INTO `telegraph` (receiver, text) VALUES (?i,"?s")', $receiver['id'], $telegraphText); diff --git a/register.php b/register.php index 8d54518..d723dff 100644 --- a/register.php +++ b/register.php @@ -1,51 +1,24 @@ - ← на главную - -

- -

Регистрация

- -
-
-
-
-
-
-
- - - \ No newline at end of file + +require_once 'views\register.php'; diff --git a/rememberpassword.php b/rememberpassword.php index fc5d638..49ea276 100644 --- a/rememberpassword.php +++ b/rememberpassword.php @@ -3,19 +3,16 @@ use Battles\Template, Battles\RememberPassword; require_once("config.php"); -$login = filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_SPECIAL_CHARS); -$password = isset($_POST['psw']) ? password_hash($_POST['psw'], PASSWORD_DEFAULT) : null; -$_GET['change'] = $_GET['change'] ?? null; -$newPassword = $_POST['newpasswd'] ?? 0; -$hashCheck = $_POST['hashcheck'] ?? 0; + +$_GET['change'] ??= null; $operation = new RememberPassword(); -if ($login) { - $statusMessage = $operation->sendRecoveryMail($login); +if (filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_SPECIAL_CHARS)) { + $statusMessage = $operation->sendRecoveryMail(filter_input(INPUT_POST, 'loginid', FILTER_SANITIZE_SPECIAL_CHARS)); } -if ($newPassword && $hashCheck) { - $statusMessage = $operation->setNewPassword($newPassword, $hashCheck); +if (!empty($_POST['newpasswd']) && !empty($_POST['hashcheck'])) { + $statusMessage = $operation->setNewPassword($_POST['newpasswd'], $_POST['hashcheck']); } Template::header('Восстановление пароля'); ?> @@ -39,7 +36,7 @@ Template::header('Восстановление пароля'); Восстанавливать пароль можно только раз в сутки.


diff --git a/repair.php b/repair.php index 2b5f39f..f16c4ef 100644 --- a/repair.php +++ b/repair.php @@ -1,13 +1,11 @@ getMoney() >= GRAV_COST) { + if (User::getInstance()->money()->spend(GRAV_COST)) { if (iconv_strlen($gravirovkaText) <= GRAV_LIMIT) { Db::getInstance()->execute('UPDATE inventory SET text = ? WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [$gravirovkaText, User::getInstance()->getId(), $itemId]); - User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); $status = REPAIR_STATUS['OK_GRAV_ADDED']; } else { $status = REPAIR_STATUS['ERROR_SIZE_LIMIT']; @@ -42,10 +38,8 @@ if ($gravirovkaText && $itemId) { } // Снять гравировку. if ($gravirovkaRemove) { - if (User::getInstance()->getMoney() >= GRAV_COST) { + if (User::getInstance()->money()->spend(GRAV_COST)) { Db::getInstance()->execute('UPDATE inventory SET text = null WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]); - User::getInstance()->setMoney(User::getInstance()->getMoney() - GRAV_COST); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); $status = REPAIR_STATUS['OK_GRAV_REMOVED']; } else { $status = REPAIR_STATUS['ERROR_NO_MONEY']; @@ -55,11 +49,9 @@ if ($gravirovkaRemove) { // Пока что лимит ремонта поставлен на 25. Дальше можно обыграть. if ($action == 'repair' && $itemId) { $q = Db::getInstance()->ofetch('SELECT name, durability FROM inventory WHERE item_id = ?', $itemId); - if (User::getInstance()->getMoney() > ceil($q->duration / 2)) { - Db::getInstance()->execute('UPDATE inventory SET duration = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND id = ?', [User::getInstance()->getId(), $itemId]); - User::getInstance()->setMoney(User::getInstance()->getMoney() - ceil($q->duration / 2)); - Bank::setWalletMoney(User::getInstance()->getMoney(), User::getInstance()->getId()); - GameLogs::addUserLog(User::getInstance()->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->duration / 2) . ' кр.'); + if (User::getInstance()->money()->spend(ceil($q->durability / 2))) { + Db::getInstance()->execute('UPDATE inventory SET durability = 25 WHERE dressed_slot = 0 AND on_sale = 0 AND owner_id = ? AND item_id = ?', [User::getInstance()->getId(), $itemId]); + GameLogs::addUserLog(User::getInstance()->getId(), 'Отремонтирован предмет «' . $q->name . '» id:(' . $itemId . ') за ' . ceil($q->durability / 2) . ' кр.'); $status = REPAIR_STATUS['OK_REPAIRED']; } else { $status = REPAIR_STATUS['ERROR_NO_MONEY']; diff --git a/shop.php b/shop.php index 14b048c..c17330b 100644 --- a/shop.php +++ b/shop.php @@ -1,11 +1,7 @@ - - -

Государственный магазин

- ← выйти на Центральную площадь -
-
-
-

getCategoryName() ?>

-
- categoryType === -1): ?> - Вы можете продать ваши предметы за сущие копейки. - -
- - getItemsList() ?> -
-
-
- - Масса всех вещей:
- Деньги: getMoney() ?>. -
-
-
-
Отделы магазина
- Оружие - Шлемы - Броня - Поножи - Сапоги - Перчатки - Щиты - Пояса - Кольца - Амулеты - Расходники - Разное - Все товары - Продать вещи -
-
- Если у вас не хватит денег на покупку, деньги будут автоматически сняты с вашего банковского - счёта - с вычетом банковской комиссии за услуги. -
-
-
\ No newline at end of file +require_once 'views/shop.php'; diff --git a/towerin.php b/towerin.php index 98e9ebc..02c1cf5 100644 --- a/towerin.php +++ b/towerin.php @@ -9,7 +9,15 @@ use Battles\User; require_once "functions.php"; $user = User::getInstance(); -if (User::getInstance()->getInTower() != 1) { +$check = new class{ + + public static function getInTower(): bool + { + return \Battles\Database\Db::getInstance()->fetchColumn('select in_tower from users where id = ?', User::getInstance()->getId()) === 1; + } +}; + +if (!$check::getInTower()) { header('Location: main.php'); exit; } diff --git a/user_abilities.php b/user_abilities.php index 456d64b..48e84a9 100644 --- a/user_abilities.php +++ b/user_abilities.php @@ -17,12 +17,13 @@ if (!empty($_GET['teleport']) && User::getInstance()->getAdmin() == 1) { # ORDEN PHP $_POST['use'] ??= null; + if (User::getInstance()->getAdmin()) { - $abil = Db::getInstance()->execute('SELECT 1 FROM users WHERE id = ?i', User::getInstance()->getId())->fetchColumn(); + $abil = Db::getInstance()->execute('SELECT 1 FROM users WHERE id = ?', User::getInstance()->getId())->fetchColumn(); //$abil = unserialize($abil['abil']); switch ($_POST['use']) { case "healing": - include("./magic/Healing.php"); + include_once("./magic/Healing.php"); break; case "ct1": if ($abil[0] > 0 && User::getInstance()->getAlign() == 6) { @@ -30,7 +31,7 @@ if (User::getInstance()->getAdmin()) { //include("./magic/ct1.php"); if ($outok == 1) { $abil[0] -= 1; - db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId()); + Db::getInstance()->execute('update users set abil = ? where id = ?', [serialize($abil), User::getInstance()->getId()]); } } elseif (User::getInstance()->getAlign() != 6) { //Заменён на CureInjury.php class. Придумать вызов. @@ -43,7 +44,7 @@ if (User::getInstance()->getAdmin()) { //include("./magic/ct2.php"); if ($outok == 1) { $abil[1] -= 1; - db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId()); + Db::getInstance()->execute('update users set abil = ? where id = ?', [serialize($abil), User::getInstance()->getId()]); } } elseif (User::getInstance()->getAlign() != 6) { //Заменён на CureInjury.php class. Придумать вызов. @@ -56,7 +57,7 @@ if (User::getInstance()->getAdmin()) { //include("./magic/ct3.php"); if ($outok == 1) { $abil[2] -= 1; - db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId()); + Db::getInstance()->execute('update users set abil = ? where id = ?', [serialize($abil), User::getInstance()->getId()]); } } elseif (User::getInstance()->getAlign() != 6) { //Заменён на CureInjury.php class. Придумать вызов. @@ -68,30 +69,30 @@ if (User::getInstance()->getAdmin()) { //include("./magic/ct_all.php"); break; case "attack": - include("./magic/eattack.php"); + include_once("./magic/eattack.php"); break; case "attack_t": - include("./magic/attack_t.php"); + include_once("./magic/attack_t.php"); if ($skipper == 1) { header("Location:fbattle.php"); exit(); } break; case "battack": - include("./magic/ebattack.php"); + include_once("./magic/ebattack.php"); break; case "attackk_close": if ($abil[1] > 0 && User::getInstance()->getAlign() == 2) { - include("./magic/attackk_close.php"); + include_once("./magic/attackk_close.php"); if ($outok == 1) { $abil[1] -= 1; - db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId()); + Db::getInstance()->execute('update users set abil = ? where id = ?', [serialize($abil), User::getInstance()->getId()]); header("Location:fbattle.php"); exit(); } } else { - include("./magic/attackk_close.php"); + include_once("./magic/attackk_close.php"); header("Location:fbattle.php"); exit(); } @@ -99,22 +100,22 @@ if (User::getInstance()->getAdmin()) { case "attackk_open": if ($abil[1] > 0 && User::getInstance()->getAlign() == 2) { - include("./magic/attackk_open.php"); + include_once("./magic/attackk_open.php"); if ($outok == 1) { $abil[2] -= 1; - db::c()->query('UPDATE users SET abil = "?s" WHERE id = ?i', serialize($abil), User::getInstance()->getId()); + Db::getInstance()->execute('update users set abil = ? where id = ?', [serialize($abil), User::getInstance()->getId()]); header("Location:fbattle.php"); exit(); } } else { - include("./magic/attackk_open.php"); + include_once("./magic/attackk_open.php"); header("Location:fbattle.php"); exit(); } break; case "brat": - include("./magic/brat.php"); + include_once("./magic/brat.php"); if ($skipper == 1) { header("Location:fbattle.php"); exit(); @@ -122,24 +123,23 @@ if (User::getInstance()->getAdmin()) { break; case "vampir": - include("./magic/vampir.php"); + include_once("./magic/vampir.php"); break; case "crush": - include("./magic/devastate.php"); + include_once("./magic/devastate.php"); break; case "def": - include("./magic/defence.php"); + include_once("./magic/defence.php"); break; case "bexit": - include("./magic/bexit.php"); + include_once("./magic/bexit.php"); break; } } -function show_byu($type) +function show_byu($type): string { - global $user; $type = $type + 20; $typeName = [ 21 => '15 минут тишины', @@ -176,23 +176,19 @@ function show_byu($type) 35 => 'antimirror', ]; if (User::getInstance()->getClan()) { - $clan = db::c()->query('SELECT owner_id FROM clans WHERE short_name = "?s"', User::getInstance()->getClan())->fetch_assoc(); - if ($clan['owner_id'] == User::getInstance()->getId()) { - $r = ''; + $clan_owner = Db::getInstance()->fetchColumn('select owner_id from clans where short_name = ?', User::getInstance()->getClan()); + if ($clan_owner === User::getInstance()->getId()) { + $r = 'купить 1 шт.'; } else { - $r = ''; + $r = 'Вы не глава'; } } else { - $r = ''; + $r = 'Вы не состоите в клане'; } return << -
$typeName[$type]
-
$typeName[$type]
-
- $r -
-
+
+ $typeName[$type] $typeName[$type] [$r] +
FFFF; } @@ -231,8 +227,8 @@ A; getAlign() == 2 || User::getInstance()->getAdmin()) // Нейтралы { - - $abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); + $abil = [null, null, null]; + //$abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); //$abil = unserialize($abil['abil']); for ($i = 0; $i < 3; $i++) { if (!$abil[$i]) { @@ -247,8 +243,8 @@ A; if (User::getInstance()->getAlign() == 6 || User::getInstance()->getAdmin()) // Свет { - - $abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); + $abil = [null, null, null]; + //$abil = db::c()->query('SELECT 1 FROM `users` WHERE `id`= ?i', $_SESSION['uid'])->fetch_assoc(); //$abil = unserialize($abil['abil']); for ($i = 0; $i < 3; $i++) { if (!$abil[$i]) { @@ -283,7 +279,7 @@ A;
Счёт - На счету еврокредитов. + На счету money()->getBank() ?>
@@ -418,21 +414,11 @@ A;
- - - - - - - - - - - - - - - +
+getRoom()], 'strah') ?> +
getStatus() : '' ?>
+
+ На счету: money()->getBank() ?> +
+ На руках: money()->get() ?> +
+
+ Работа со счётом +
+ + + +
+
+ + + +
+
+
+ Перевод кредитов +
+ +
+ + +
+ Комиссия: % от переводимой суммы, но не менее 1 кр. +
diff --git a/views/hostel-checkpoint.php b/views/hostel-checkpoint.php new file mode 100644 index 0000000..c2b5bd3 --- /dev/null +++ b/views/hostel-checkpoint.php @@ -0,0 +1,37 @@ +getHid())): ?> +
+ Предварительная оплата +
+

+ Аренда оплачена по: getTime()) ?> + (getTime() - time()) ?>) +

+
+ + + + + + + + + + + + + + + + +
Выберите срок предоплаты.
Сутки
Сумма + getType()][$item - 1] ?> +
+
+ Внимание! При расторжении договора или смене тарифа, внесенная плата не возвращается +
+
+ \ No newline at end of file diff --git a/views/hostel.php b/views/hostel.php new file mode 100644 index 0000000..4bf360d --- /dev/null +++ b/views/hostel.php @@ -0,0 +1,192 @@ +getRoom()]); +?> + +getHid()): ?> + + + +
+
Гостиница, Холл
+
+ getId(), 8)): ?> + + + + + + + +
+ +
+
+ getHid()): ?> +
+ Станьте нашим клиентом +
+ +

Выберите подходящий для Вас вариант обслуживания:

+
+ + + getStatus()['type'] === 'error'): ?> +
+ + getStatus()['message'] ?> + +
+ +
+
+
+ +
+ Добро пожаловать! +
+

Вы выбрали вариант предоставления жилья : + getType()] ?>

+

Аренда оплачена по: getTime()); ?> + (getTime() - time()); ?>)

+
+ + +
+
+ Расторгнуть договор Внести предоплату + getStatus()['type'] === 'error'): ?> +
+ + getStatus()['message'] ?> + +
+ +
+ +
+
+ Правила проживания +
+
+

И что я получу за свои кровные?

+ У нас ты можешь: +
    +
  • хранить свое барахло и прочий хлам. +
+

Охрана у вас есть? Не воруют?

+ Самые любопытные могут получить в сурло прямо здесь - в холле. +
    +
  • Устраивать беспорядки в комнатах не позволено. +
  • Прислуга у нас проверенная - пожитки твои не тронут. +
+

И сколько стоит всё это удовольствие?

+
    +
  • Комнаты есть разные, для людей разного достатка. Смотри справа расценки. +
  • Платить нужно каждый день. Пока не заплатишь - на лестницу не ногой. +
  • Вместимость - это сколько твоих вещей влезет в комнату, имеется ввиду общая масса инвентаря. +
+

Как всем этим пользоваться?

+ Всё просто. Плати и живи. +
Приходишь, платишь по долгам, проходишь в аппартаменты. В сундуке есть секции для каждого вида + вещей, фильтр поможет разобраться. +

Что ещё мне нужно знать?

+
    +
  • При смене размера комнаты, ты теряешь оставшееся оплаченное время. +
  • При просрочке платы более 60 суток, мы оставляем за собой право сдать вещи на аукцион для + погашения задолжености. +
  • Если долг будет разумный, то подарки забирать с полки не будем. +
  • Быстро сориентироваться с шмотом поможет фильтр предметов. +
  • Если что потеряешь - твои проблемы. +
+
+
+
+
+ +
+
+ Тарифы и услуги +
+ + + + + + + + + + + + +
Сумка
Вместимость15 ед.
Стоимость (7 сут.)8.00 кр.
+
+ + + + + + + + + + + + +
Сундук
Вместимость30 ед.
Стоимость (7 сут.)15.00 кр.
+
+ + + + + + + + + + + + +
Комната
Вместимость50 ед.
Стоимость (7 сут.)25.00 кр.
+
+ + + + + + + + + + + + +
Амбар
Вместимость100 ед.
Стоимость (7 сут.)40.00 кр.
+
+
+
diff --git a/views/index.html b/views/index.html new file mode 100644 index 0000000..544eb42 --- /dev/null +++ b/views/index.html @@ -0,0 +1,27 @@ + + + + + +Игра +

Battles v.0.7.0222

+
+

Оставь надежду всяк сюда входящий.

+
+ Авторизация
+ + +
+ +
+
+
+ diff --git a/views/presents-list.php b/views/inf-presents.php similarity index 100% rename from views/presents-list.php rename to views/inf-presents.php diff --git a/views/main-game.php b/views/main-game.php new file mode 100644 index 0000000..fc67129 --- /dev/null +++ b/views/main-game.php @@ -0,0 +1,125 @@ + + + +
+ + + + + + + + +
+ userInfo()->showUserDoll(0, 1) ?> +
+ Снять все
+
+ userInfo()->showUserEffects() ?> +
+
+
+
+
+ userInfo()->userInfoStatsTest() as $item => $value): ?> +
: + +
+
+
+
+
+ getShadow() === '0.gif' || User::getInstance()->getAdmin() === 1): ?> + + +
+ getRoom() === 20): ?> + + getRoom() === 1): ?> + + + + + +
+
+
+ + + + + + + + + + + +
Рюкзак (масса: )
+ printImage() ?> + printControls() ?> + + printInfo() ?> + +
Пусто
+
+
\ No newline at end of file diff --git a/views/main-setshadow.php b/views/main-setshadow.php new file mode 100644 index 0000000..f845d18 --- /dev/null +++ b/views/main-setshadow.php @@ -0,0 +1,21 @@ + +
+ +
+ + + + + + +
Внимание! Образ персонажа выбирается только один раз.
+
m<?= $item ?> + +
f<?= $item ?> + +
\ No newline at end of file diff --git a/views/register.php b/views/register.php new file mode 100644 index 0000000..7390505 --- /dev/null +++ b/views/register.php @@ -0,0 +1,29 @@ + + ← на главную + +

Не больше одной регистрации в час!

+ +

Регистрация

+ +
+
+
+
+
+
+
+ + + \ No newline at end of file diff --git a/views/shop.php b/views/shop.php new file mode 100644 index 0000000..70f9ed8 --- /dev/null +++ b/views/shop.php @@ -0,0 +1,53 @@ + + + +

Государственный магазин

+ ← выйти на Центральную площадь +
+
+
+

getCategoryName() ?>

+
+ categoryType === -1): ?> + Вы можете продать ваши предметы за сущие копейки. + +
+ + getItemsList() ?> +
+
+
+ + Масса всех вещей:
+ Деньги: money()->get() ?>. +
+
+
+
Отделы магазина
+ Оружие + Шлемы + Броня + Поножи + Сапоги + Перчатки + Щиты + Пояса + Кольца + Амулеты + Расходники + Разное + Все товары + Продать вещи +
+
+ Если у вас не хватит денег на покупку, деньги будут автоматически сняты с вашего банковского + счёта + с вычетом банковской комиссии за услуги. +
+
+
\ No newline at end of file