diff --git a/admin/admin.php b/admin/admin.php index de52d9b..e99b2fa 100644 --- a/admin/admin.php +++ b/admin/admin.php @@ -9,23 +9,24 @@ require_once '../functions.php'; use Battles\Bank; use Battles\Database\DBPDO; +use Battles\GameConfigs; use Battles\Moderation; use Battles\Nick; use Battles\Template; use Battles\User; -$user = $user ?? new User($_SESSION['uid']); if (!$user->getAdmin()) { header("HTTP/1.0 404 Not Found"); exit; } - if (isset($_GET['sleep'])) { Moderation::muteChat($user->getId(), strtotime('15min')); } if (isset($_POST['ldnick']) && isset($_POST['ldtext'])) { - Moderation::addToUserLog($_POST['ldnick'], $_POST['ldtext'], $user->getId()); + $u = new User($_POST['ldnick']); + Moderation::addToUserLog($u->getId(), $_POST['ldtext'], $user->getId()); + unset($u); } if (isset($_POST['syschatmsg'])) { @@ -72,7 +73,7 @@ UNREGCLANLIST; { $bank = new Bank($id); $this->db->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id); - $bank::setBankMoney($bank->getMoney() + Config::$clan_register_cost, $id); + $bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN_REGISTER_COST, $id); } }; $unregisteredClans->db = new DBPDO(); diff --git a/admin/edit_user.php b/admin/edit_user.php index 280e8eb..e36414e 100644 --- a/admin/edit_user.php +++ b/admin/edit_user.php @@ -25,7 +25,7 @@ if ($player) { unset($row); } if ($undress_char) { - undressall($_SESSION['player_id']); + \Battles\DressedItems::undressAllItems($_SESSION['player_id']); } if ($end) { unset($_SESSION['player_id']); @@ -37,10 +37,11 @@ if (isset($_SESSION['player_id'])) { if ($del) { $itemdel = db::c()->query('SELECT item_type, dressed_slot FROM inventory WHERE id=?i', $del)->fetch_assoc(); if ($itemdel['dressed_slot'] == 1) { - dropitem($itemdel['item_type']); + $item = new \Battles\DressedItems($del); + $item->undressItem($itemdel['item_type']); if ($itemdel['item_type'] == 5) { - dropitem(6); - dropitem(7); + $item->undressItem(6); + $item->undressItem(7); } } db::c()->query('DELETE FROM `inventory` WHERE `id` = ?i', $del); diff --git a/admin/test_stats.php b/admin/test_stats.php index 60cbd9d..e5e83f6 100644 --- a/admin/test_stats.php +++ b/admin/test_stats.php @@ -38,7 +38,7 @@ } if(!$kompl_har) $kompl_har=0; $explim=0; - foreach(array_keys(Config::$exptable) as $k) + foreach(array_keys(EXPTABLE) as $k) { if($k>=$ku['exp']) { @@ -47,14 +47,14 @@ } } $sum_stat=15; - foreach(array_keys(Config::$exptable) as $k) + foreach(array_keys(EXPTABLE) as $k) { if($k==$explim) break; else { - $sum_stat+=Config::$exptable[$k][0]; - $sum_stat+=Config::$exptable[$k][2]; + $sum_stat+=EXPTABLE[$k][0]; + $sum_stat+=EXPTABLE[$k][2]; } } $res=mysql_fetch_array( diff --git a/bank.php b/bank.php index b68583a..a672e5f 100644 --- a/bank.php +++ b/bank.php @@ -1,6 +1,7 @@ - Комиссия: % от переводимой суммы, но не менее 1 кр. + Комиссия: % от переводимой суммы, но не менее 1 кр. diff --git a/cave.php b/cave.php index f9c5986..f684eb0 100644 --- a/cave.php +++ b/cave.php @@ -5,7 +5,7 @@ use Battles\Template; session_start(); 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, $u) { global $user; @@ -204,7 +204,7 @@ function gotoroom($r, $redir = 1) function redirectbyroom($r) { - if (in_array($r, Config::$canalenters)) { + if (in_array($r, CANAL_ENTERS)) { header("location: enter_cave.php"); exit; } @@ -286,7 +286,7 @@ function takeusage($x, $y) function makedeath() { global $user, $floor, $loses, $x, $y, $dir; - $cavedata = Config::$cavedata ?? []; + $cavedata = CAVE_DATA ?? []; if (!isset($cavedata[$user->getRoom()]['x' . $floor])) { $floor = 1; loadmap(); @@ -430,11 +430,11 @@ function loadmap() function getslot($i, $user1 = 0) { - global $user; + global $user, $userslots; if (!$user1) { $user1 = $user; } - foreach (Config::$userslots as $k => $v) { + foreach ($userslots as $k => $v) { if ($user1[$v] == $i) { return $v; } @@ -482,12 +482,13 @@ if (@$_GET['kill'] && $user['id'] == $user['caveleader'] && $_GET['kill'] != $us mysql_query("UPDATE `users` SET `room` = (`room`-1), `caveleader` = 0 WHERE `id` = '$v[user]' LIMIT 1"); $r = mysql_query("SELECT `id`, `dressed` FROM `inventory` WHERE `owner` = '$v[user]' AND `dressed` = 1 AND `foronetrip` = 1"); if (mysql_num_rows($r) > 0) { - $usr = mysql_fetch_array(mysql_query("SELECT " . implode(",", Config::$userslots) . " FROM `users` WHERE `id` = '$v[user]'")); + $usr = mysql_fetch_array(mysql_query("SELECT " . implode(",", $userslots) . " FROM `users` WHERE `id` = '$v[user]'")); } while ($rec = mysql_fetch_assoc($r)) { $slot = getslot($rec['id'], $usr); if ($slot) { - dropitemid(0, $v['user'], $slot); + $item = new \Battles\DressedItems($v['user']); + $item->undressItem($slot); } } mysql_query("DELETE FROM `inventory` WHERE `owner` = '$v[user]' AND `foronetrip` = 1"); @@ -737,7 +738,7 @@ if ($ambushes[$y * 2][$x * 2 - 2] && $map[$y * 2][$x * 2 - 1] == 0) { } if ($ax && $ay && $user['hp'] > 0) { - $cavedata = Config::$cavedata ?? []; + $cavedata = CAVE_DATA ?? []; if (!($cavedata[$user->getRoom()]['x' . $floor] == $x && $cavedata[$user->getRoom()]['y' . $floor] == $y)) { if ($ax < $x) { $dir1 = 0; @@ -898,7 +899,8 @@ if (@$_GET['exit']) { while ($rec = mysql_fetch_assoc($r)) { $slot = getslot($rec['id']); if ($slot) { - dropitemid(0, $user['id'], $slot); + $item = new \Battles\DressedItems($user['id']); + $item->undressItem($slot); } } mysql_query("DELETE FROM `inventory` WHERE `owner` = '$user[id]' AND `foronetrip` = 1"); diff --git a/clan_create.php b/clan_create.php index 4ef2d6e..2b927c7 100644 --- a/clan_create.php +++ b/clan_create.php @@ -1,6 +1,7 @@ query('SELECT 1 FROM users_effects WHERE type = 20 AND owner_id = ?i', $user->getId()); $name_check = db::c()->query('SELECT owner_id FROM clans WHERE full_name = "?s" OR short_name = "?s"', $clanFullName, $clanShortName); $errorMessage = []; - if (Config::$clan_register_lock) { + if (GameConfigs::CLAN_REGISTER_LOCK) { $errorMessage[10] = 'Регистрация кланов закрыта!
'; } if ($user->getAlign()) { @@ -27,7 +28,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { if ($user->getClan()) { $errorMessage[1] = 'Вы уже состоите в клане!.
'; } - if (Config::$clan_register_cost >= $userBank->getMoney()) { + if (GameConfigs::CLAN_REGISTER_COST >= $userBank->getMoney()) { $errorMessage[2] = 'Не хватает денег на регистрацию клана.
'; } if (!$eff) { @@ -39,7 +40,7 @@ if ($clanFullName && $clanShortName && $clanInfo && !$userClan) { if (!$errorMessage || $user->getAdmin()) { try { db::c()->query('INSERT INTO clans (owner_id, full_name, short_name, info) VALUES (?i,"?s","?s","?s")', $user->getId(), $clanFullName, $clanShortName, $clanInfo); - $userBank->setMoney($userBank->getMoney() - Config::$clan_register_cost); + $userBank->setMoney($userBank->getMoney() - GameConfigs::CLAN_REGISTER_COST); Battles\Bank::setBankMoney($userBank->getMoney(), $user->getId(), 'clanRegister'); // Заглушка для отображения данных по только что зарегистрированному клану, когда запрос в базу в начале файла ещё не проходит. $userClan = new stdClass(); diff --git a/classes/Battles/Bank.php b/classes/Battles/Bank.php index aed703a..c01504f 100644 --- a/classes/Battles/Bank.php +++ b/classes/Battles/Bank.php @@ -52,7 +52,7 @@ class Bank */ private function bankCommission(int $amount): int { - $bankCommission = round($amount * Config::$bank_commission); + $bankCommission = round($amount * GameConfigs::BANK_COMISSION); if ($bankCommission < 1) { return 1; } else { diff --git a/classes/Battles/Database/DBPDO.php b/classes/Battles/Database/DBPDO.php index 9ec2236..d9f148e 100644 --- a/classes/Battles/Database/DBPDO.php +++ b/classes/Battles/Database/DBPDO.php @@ -2,11 +2,7 @@ namespace Battles\Database; -const DATABASE_HOST = '192.168.20.5'; -const DATABASE_NAME = 'battles'; -const DATABASE_USER = 'battles'; -const DATABASE_PASS = 'bottle-neck-horse'; -const DATABASE_PORT = '32101'; +use Battles\GameConfigs; use PDO, PDOException; class DBPDO { @@ -37,9 +33,9 @@ class DBPDO { if (!$this->pdo) { - $dsn = 'mysql:dbname=' . DATABASE_NAME . ';host=' . DATABASE_HOST . ';port=' . DATABASE_PORT . ';charset=utf8;'; - $user = DATABASE_USER; - $password = DATABASE_PASS; + $dsn = 'mysql:dbname=' . GameConfigs::DATABASE_NAME . ';host=' . GameConfigs::DATABASE_HOST . ';port=' . GameConfigs::DATABASE_PORT . ';charset=utf8;'; + $user = GameConfigs::DATABASE_USER; + $password = GameConfigs::DATABASE_PASS; try { $this->pdo = new PDO($dsn, $user, $password, array(PDO::ATTR_PERSISTENT => true)); @@ -144,5 +140,4 @@ class DBPDO { return $this->pdo->lastInsertId(); } - } \ No newline at end of file diff --git a/classes/Battles/DressedItems.php b/classes/Battles/DressedItems.php index d1b170f..34dd8f3 100644 --- a/classes/Battles/DressedItems.php +++ b/classes/Battles/DressedItems.php @@ -8,6 +8,7 @@ namespace Battles; use Battles\Database\DBPDO; +use stdClass; class DressedItems { @@ -27,94 +28,20 @@ class DressedItems public static function getDressedItemBySlot($itemSlot, $ownerId) { - return self::$db->fetch('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]); + return self::$db->fetch('SELECT *, COUNT(1) AS count FROM inventory WHERE owner_id = ? AND dressed_slot = ?', [$ownerId, $itemSlot]); } - public function getItemsInSlots() + public function getItemsInSlots(): stdClass { $items = self::$db->ofetchALL('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot > 0', $this->USERID); - $i = 0; - while ($i < count($items)) { - $this->dressedItem[$items[$i]->dressed_slot] = $items; - $i++; + $this->dressedItem = new stdClass(); + foreach ($items as $item) { + $i = $item->dressed_slot; + $this->dressedItem->$i = $item; } return $this->dressedItem; } - private function getBonuses(): array - { - $query = << 0 -SQL; - return self::$db->fetch($query, $this->USERID); - } - - public function getStrengthBonus(): ?int - { - return self::getBonuses()['sum_strength']; - } - - public function getDexterityBonus(): ?int - { - return self::getBonuses()['sum_dexterity']; - } - - public function getIntuitionBonus(): ?int - { - return self::getBonuses()['sum_intuition']; - } - - public function getEnduranceBonus(): ?int - { - return self::getBonuses()['sum_endurance']; - } - - public function getIntelliganceBonus(): ?int - { - return self::getBonuses()['sum_intelligence']; - } - - public function getWisdomBonus(): ?int - { - return self::getBonuses()['sum_wisdom']; - } - - public function getAccuracyBonus(): ?int - { - return self::getBonuses()['sum_accuracy'] ?? 0; - } - - public function getEvasionBonus(): ?int - { - return self::getBonuses()['sum_evasion'] ?? 0; - } - - public function getCriticalsBonus(): ?int - { - return self::getBonuses()['sum_criticals'] ?? 0; - } - - public function getMinPhysDamage(): ?int - { - return self::getBonuses()['sum_min_phys_damage']; - } - - public function getMaxPhysDamage(): ?int - { - return self::getBonuses()['sum_max_phys_damage']; - } - /** * Снимает с предмета статус одетого на персонажа в определённом слоте персонажа. * @param $slot_id - номер слота. @@ -123,8 +50,12 @@ SQL; { self::getItemsInSlots(); // Проверяем, что используется один из 12 слотов и наличие предмета в слоте. - if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem[$slot_id]) { + if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem->$slot_id) { self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$slot_id, $this->USERID]); } } + public static function undressAllItems($user_id) + { + return self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot BETWEEN 1 AND 12 AND owner_id = ?', $user_id); + } } \ No newline at end of file diff --git a/classes/Battles/GameConfigs.php b/classes/Battles/GameConfigs.php new file mode 100644 index 0000000..2f8e38d --- /dev/null +++ b/classes/Battles/GameConfigs.php @@ -0,0 +1,21 @@ +prepare("INSERT INTO bank_logs (sender_id, receiver_id, amount, type, text) VALUES (?, ?, ?, ?, ?)"); $row->bindParam(1, $senderId, SQLITE3_INTEGER); $row->bindParam(2, $receiverId, SQLITE3_INTEGER); @@ -45,7 +45,7 @@ class GameLogs if (empty($type)) { $type = "system"; } - $db = new SQLite3(Config::$db_sqlite); + $db = new SQLite3(GameConfigs::DB_SQLITE); $row = $db->prepare("INSERT INTO users_logs (user_id, author_id, type, text) VALUES (?,?,?,?)"); $row->bindParam(1, $userId, SQLITE3_INTEGER); $row->bindParam(2, $authorId, SQLITE3_INTEGER); @@ -57,7 +57,7 @@ class GameLogs public static function getUserLogs($userId = null, $type = null): SQLite3Result { - $db = new SQLite3(Config::$db_sqlite); + $db = new SQLite3(GameConfigs::DB_SQLITE); if ($userId && $type) { $query = "SELECT * FROM users_logs WHERE user_id = ? AND type = ?"; diff --git a/classes/Battles/InventoryItem.php b/classes/Battles/InventoryItem.php index 561d3be..0cd1c14 100644 --- a/classes/Battles/InventoryItem.php +++ b/classes/Battles/InventoryItem.php @@ -1,15 +1,27 @@ present = $row['present']; - } + $this->owner_id = $row->owner_id; + $this->db = DBPDO::INIT(); } public function printInfo() @@ -22,14 +34,110 @@ class InventoryItem extends Item public function printImage() { - if (in_array($this->item_type, range(1,12))) { - echo "item_id} title='Надеть'>"; - parent::printImage(); - echo ""; + if (in_array($this->item_type, range(1, 12))) { + echo <<item_id} title='Надеть'> + + +HTML; } else { - parent::printImage(); + echo << +IMG; } } - public function printControls() {} + public function printControls() + { + /* Тут будут кнопки под картинкой. */ + } + + private function dressStatsChecks(): ?string + { + $checkStats = new UserStats($this->owner_id); + return + $this->need_strength > $checkStats->getFullStats()->strength + || $this->need_dexterity > $checkStats->getFullStats()->dexterity + || $this->need_intuition > $checkStats->getFullStats()->intuition + || $this->need_endurance > $checkStats->getFullStats()->endurance + || $this->need_intelligence > $checkStats->getFullStats()->intelligence + || $this->need_wisdom > $checkStats->getFullStats()->wisdom + ? true : null; + } + + /** + * Одевание предмета из инвентаря в слот. + * @return bool|string + */ + public function dressItem() + { + $db = new DBPDO(); + $itemInSlot = []; + if ($this->dressStatsChecks()) { + return self::REQUIREMENTS_NOT_MET; + } + // считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами + // Count добавленный в первый запрос возвращает одну строку в любом случае. + // fetch возвращает одну строку в любом случае. + $weared = $db->ofetchAll('SELECT dressed_slot FROM inventory WHERE dressed_slot != 0 AND item_type = ? AND owner_id = ?', [$this->item_type, $this->owner_id]); + $wearedCount = $db->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]); + // Если в слоте есть предмет(ы), забиваем их массив одетых в слот предметов. + if ($wearedCount) { + foreach ($weared as $item) { + $itemInSlot[] = $item->dressed_slot; + } + } + if (in_array($this->item_type, [ + self::ITEM_TYPE_HELMET, self::ITEM_TYPE_ARMOR, self::ITEM_TYPE_LEGS, self::ITEM_TYPE_BOOTS, + self::ITEM_TYPE_GLOVES, self::ITEM_TYPE_WEAPON, self::ITEM_TYPE_SHIELD, self::ITEM_TYPE_BELT, + self::ITEM_TYPE_AMULET, + ])) { + //работаем с нормальными слотами + if ($wearedCount->c == 1) { + //если слот занят, снимаем старый предмет и одеваем новый предмет + DBPDO::INIT()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $this->owner_id]); + DBPDO::INIT()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); + } elseif (!$wearedCount->c) { + //если слот пуст, одеваем новый предмет + DBPDO::INIT()->execute('UPDATE inventory SET dressed_slot = item_type WHERE item_id = ? AND owner_id = ?', [$this->item_id, $this->owner_id]); + } else { + /* проверка на переполнение слотов */ + $error = self::TOO_MANY_ITEMS_IN_SLOTS; + DressedItems::undressAllItems($this->owner_id); + } + } elseif ($this->item_type == self::ITEM_TYPE_RING) { + // работаем с кольцами + if ($wearedCount->c < 3) { + // Сравниваем массив колец и массив слотов для колец. + $emptyRingSlots = array_diff([9, 10, 11], $itemInSlot); + // Сортируем массив свободных слотов по возрастанию. + sort($emptyRingSlots); + // Одеваем предмет в первый свободный слот. + DBPDO::INIT()->execute('update inventory set dressed_slot = ? where item_id = ?', [$emptyRingSlots[0], $this->item_id]); + } elseif ($wearedCount->c == 3) { + // Cнимаем предмет из последнего слота 11 и одеваем новый предмет + DBPDO::INIT()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11'); + DBPDO::INIT()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id); + } else { + /* проверка на переполнение слотов */ + $error = self::TOO_MANY_ITEMS_IN_SLOTS; + DressedItems::undressAllItems($this->owner_id); + } + } else { + $error = self::UNKNOWN_ITEM_TYPE; + } + + return isset($error) ? $error : true; + } + + /** + * @param $itemId + * + * @return bool + */ + public static function destroyItem($itemId): bool + { + $db = new DBPDO(); + return $db->execute('delete from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?', [$_SESSION['uid'], $itemId]); + } } \ No newline at end of file diff --git a/classes/Battles/Item.php b/classes/Battles/Item.php index 39a22ae..c2105e4 100644 --- a/classes/Battles/Item.php +++ b/classes/Battles/Item.php @@ -1,6 +1,6 @@ $value) { - if (isset($row[$key])) { - $this->$key = $row[$key]; + if (is_array($row)) { + foreach ($this as $key => $value) { + if (isset($row[$key])) { + $this->$key = $row[$key]; + } + } + } elseif (is_object($row)) { + foreach ($this as $name => $value) { + if (isset($row->$name)) { + $this->$name = $row->$name; + } } } @@ -94,14 +102,7 @@ abstract class Item } } - abstract public function printInfo(); - public function printImage() - { - echo << -IMG; - } protected function wrap(int $number):string { diff --git a/classes/Battles/Magic/CureInjury.php b/classes/Battles/Magic/CureInjury.php index 100b69f..a1677b7 100644 --- a/classes/Battles/Magic/CureInjury.php +++ b/classes/Battles/Magic/CureInjury.php @@ -52,7 +52,7 @@ class CureInjury extends Magic } else { $this->target = new User($this->target); } - $this->login = $this->target->login; + $this->login = $this->target->getLogin(); return ($this->isVisible($caster, $this->target) && $this->isNotDead($caster) && $this->enoughMana($caster) && $this->isNotInBattle($caster)); } } \ No newline at end of file diff --git a/classes/Battles/Travel.php b/classes/Battles/Travel.php index 86b519e..4d148a8 100644 --- a/classes/Battles/Travel.php +++ b/classes/Battles/Travel.php @@ -1,6 +1,7 @@ fetch('SELECT SUM(weight) AS all_weight FROM inventory WHERE owner_id = ? AND on_sale = 0', $_SESSION['uid']); + $itemsWeight = $db->fetch('SELECT SUM(weight) - (select strength * 5 from users where id = ?) AS weight_overflow FROM inventory WHERE owner_id = ? AND on_sale = 0', [$_SESSION['uid'], $_SESSION['uid']]); $eff = $db->fetch('SELECT type FROM users_effects WHERE owner_id = ? AND (`type` = 10 OR `type` = 13 OR `type` = 14)', $_SESSION['uid']); $errors = []; - if ($itemsWeight['all_weight'] > get_meshok()) { + if ($itemsWeight['weight_overflow'] > 0) { $errors[0] = 'У вас переполнен рюкзак, вы не можете передвигаться...'; } if ($eff['type'] == 10) { diff --git a/classes/Battles/User.php b/classes/Battles/User.php index afdd29a..851c20b 100644 --- a/classes/Battles/User.php +++ b/classes/Battles/User.php @@ -3,7 +3,6 @@ namespace Battles; use Battles\Database\DBPDO; -use Exceptions\GameException; class User { @@ -14,48 +13,28 @@ class User protected $realname; protected $borndate; protected $info; - protected $level = 0; - protected $align = 0; + protected $level; + protected $align; protected $clan; - protected $money = 0; - protected $strength = 0; - protected $dexterity = 0; - protected $intuition = 0; - protected $endurance = 0; - protected $intelligence = 0; - protected $wisdom = 0; - protected $health; - protected $mana; - protected $ip; - protected $session_id; + protected $money; + protected $ip = 0; + protected $admin = 0; protected $enter_game; protected $room; protected $block; protected $shadow; - // Удар кулаком всегда 1-2. - protected $minDamage = 1; - protected $maxDamage = 2; - //Броня без предметов не существует. - protected $headArmor = 0; - protected $chestArmor = 0; - protected $legArmor = 0; - protected $free_stat_points = 0; - private const STAT_MAXIMUM_AMOUNT = 40; - private const ERROR_STAT_IS_MAXIMUM = 'Ошибка: Параметр достиг своего лимита!'; - private const ERROR_STAT_UNKNOWN = 'Ошибка: Неизвестный параметр!'; + // Пока несуществующие, для совместимости. - protected $married = 'Someone или нет.'; protected $experience = 200; protected $battle = 0; protected $in_tower = 0; // Скорее башню похороним чем запустим... protected $zayavka = 0; - // Динамически рассчитываемые - protected $maxHealth = 5; - protected $maxMana = 5; protected static $db; - public function __construct(int $user) + public const INFO_CHAR_LIMIT = 1500; + + public function __construct($user) { self::$db = DBPDO::INIT(); $user_query = self::$db->fetch('SELECT * FROM users WHERE id = ? OR login = ?', [$user, $user]); @@ -64,51 +43,8 @@ class User $this->$key = $user_query[$key]; } } - $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)); } - /** - * Отдаёт информацию о базовом(!) стате. - * @param $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'. - * @param int $isMainWindow - переключатель "главного окна". Если включить, дополнительно будет показывать ссылку на повышение стата на 1, при условии наличия свободных очков статов. - * @return string - * @throws GameException - */ - public function getStat($stat_name, $isMainWindow = 0):string - { - $allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom']; - if (in_array($stat_name, $allowed)) { - if ($this->free_stat_points && $isMainWindow && $this->$stat_name < self::STAT_MAXIMUM_AMOUNT) { - return sprintf('%s [+]', $this->$stat_name, mt_rand(), $stat_name); - } else { - return $this->$stat_name; - } - } else { - throw new GameException(self::ERROR_STAT_UNKNOWN); - } - } - - /** - * Повышает один из выбранных статов на 1, но не выше self::STAT_MAXIMUM_AMOUNT при условии наличия свободных очков статов. - * @param string $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom'. - * @throws GameException - */ - public function addOnePointToStat(string $stat_name) - { - $allowed = ['strength', 'dexterity', 'intuition', 'endurance', 'intelligence', 'wisdom']; - if (in_array($stat_name, $allowed)) { - if ($this->free_stat_points > 0 && $this->$stat_name <= self::STAT_MAXIMUM_AMOUNT) { - $query = "UPDATE users SET {$stat_name} = {$stat_name} + 1, free_stat_points = free_stat_points - 1 WHERE id = ?"; - self::$db->execute($query,$this->id); - } else { - throw new GameException(self::ERROR_STAT_IS_MAXIMUM); - } - } else { - throw new GameException(self::ERROR_STAT_UNKNOWN); - } - - } protected function showStarSign(): ?string { @@ -154,22 +90,22 @@ class User return $sign ?? null; } - public function getHealth(): string + + /** + * @param int $userId + * @param int $type + * @param string $name + * @param int $time + * @param string|null $json_modifiers_list (str, dex, int, end, intel, wis). + * @return bool + */ + public static function setUserEffect(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null): bool { - return $this->health . '/' . $this->maxHealth; + $mods = json_decode($json_modifiers_list); + return self::$db->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 function getMana(): string - { - return $this->mana . '/' . $this->maxMana; - } - - public static function setUserEffect(int $userId, int $type, string $name, int $time):bool - { - return self::$db->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time) VALUES (?,?,?,?)',[$userId, $type, $name, $time]); - } - - public static function removeUserEffect(int $userId, int $type):bool + public static function removeUserEffect(int $userId, int $type): bool { if (self::$db->fetch('SELECT 1 FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type])) { self::$db->execute('DELETE FROM users_effects WHERE owner_id = ? AND type = ?', [$userId, $type]); @@ -185,14 +121,6 @@ class User return $this->id; } - /** - * @param int $id - */ - public function setId(int $id): void - { - $this->id = $id; - } - /** * @return string */ @@ -225,6 +153,11 @@ class User $this->pass = $pass; } + public function savePass() + { + self::$db->execute('UPDATE users SET pass = ? WHERE id = ?', [$this->pass, $this->id]); + } + /** * @return string */ @@ -353,101 +286,6 @@ class User $this->money = $money; } - /** - * @return int - */ - public function getStrength(): int - { - return $this->strength; - } - - /** - * @param int $strength - */ - public function setStrength(int $strength): void - { - $this->strength = $strength; - } - - /** - * @return int - */ - public function getDexterity(): int - { - return $this->dexterity; - } - - /** - * @param int $dexterity - */ - public function setDexterity(int $dexterity): void - { - $this->dexterity = $dexterity; - } - - /** - * @return int - */ - public function getIntuition(): int - { - return $this->intuition; - } - - /** - * @param int $intuition - */ - public function setIntuition(int $intuition): void - { - $this->intuition = $intuition; - } - - /** - * @return int - */ - public function getEndurance(): int - { - return $this->endurance; - } - - /** - * @param int $endurance - */ - public function setEndurance(int $endurance): void - { - $this->endurance = $endurance; - } - - /** - * @return int - */ - public function getIntelligence(): int - { - return $this->intelligence; - } - - /** - * @param int $intelligence - */ - public function setIntelligence(int $intelligence): void - { - $this->intelligence = $intelligence; - } - - /** - * @return int - */ - public function getWisdom(): int - { - return $this->wisdom; - } - - /** - * @param int $wisdom - */ - public function setWisdom(int $wisdom): void - { - $this->wisdom = $wisdom; - } /** * @return mixed @@ -465,21 +303,6 @@ class User $this->ip = $ip; } - /** - * @return mixed - */ - public function getSessionId() - { - return $this->session_id; - } - - /** - * @param mixed $session_id - */ - public function setSessionId($session_id): void - { - $this->session_id = $session_id; - } /** * @return int @@ -489,14 +312,6 @@ class User return $this->admin; } - /** - * @param int $admin - */ - public function setAdmin(int $admin): void - { - $this->admin = $admin; - } - /** * @return mixed */ @@ -558,103 +373,18 @@ class User */ public function setShadow($shadow): void { - $this->shadow = $shadow; + $shadows = [ + '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') { + $this->shadow = $shadow . '.png'; + } } - /** - * @return int - */ - public function getMinDamage(): int + public function saveShadow() { - return $this->minDamage; - } - - /** - * @return int - */ - public function getMaxDamage(): int - { - return $this->maxDamage; - } - - /** - * @return int - */ - public function getHeadArmor(): int - { - return $this->headArmor; - } - - /** - * @param int $headArmor - */ - public function setHeadArmor(int $headArmor): void - { - $this->headArmor = $headArmor; - } - - /** - * @return int - */ - public function getChestArmor(): int - { - return $this->chestArmor; - } - - /** - * @param int $chestArmor - */ - public function setChestArmor(int $chestArmor): void - { - $this->chestArmor = $chestArmor; - } - - /** - * @return int - */ - public function getLegArmor(): int - { - return $this->legArmor; - } - - /** - * @param int $legArmor - */ - public function setLegArmor(int $legArmor): void - { - $this->legArmor = $legArmor; - } - - /** - * @return int - */ - public function getFreeStatPoints(): int - { - return $this->free_stat_points; - } - - /** - * @param int $free_stat_points - */ - public function setFreeStatPoints(int $free_stat_points): void - { - $this->free_stat_points = $free_stat_points; - } - - /** - * @return string - */ - public function getMarried(): string - { - return $this->married; - } - - /** - * @param string $married - */ - public function setMarried(string $married): void - { - $this->married = $married; + self::$db->execute('UPDATE users SET shadow = ? WHERE id = ?', [$this->getShadow(), $this->getId()]); } /** @@ -721,20 +451,47 @@ class User $this->zayavka = $zayavka; } - /** - * @return float|int - */ - public function getMaxHealth() + public function saveAnketa() { - return $this->maxHealth; + self::$db->execute('UPDATE users SET realname = ?, info = ? WHERE id = ?', [$this->realname, $this->info, $this->id]); } - /** - * @return float|int - */ - public function getMaxMana() + public function setOnline() { - return $this->maxMana; + self::$db->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::setUserEffect($this->id, $type, $name, strtotime('30min'), json_encode([$param_names(0) => -1])); + break; + case 12: + shuffle($names2); + $name = UserEffects::$effectName[$type] . ': ' . $names2(0); + self::setUserEffect($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::setUserEffect($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::setUserEffect($this->id, $type, UserEffects::$effectName[$type], strtotime('1day'), json_encode([$param_names(0) => -10])); + break; + } + + return true; + } } \ No newline at end of file diff --git a/classes/Battles/UserEffects.php b/classes/Battles/UserEffects.php index 41ee6fc..4182357 100644 --- a/classes/Battles/UserEffects.php +++ b/classes/Battles/UserEffects.php @@ -10,10 +10,10 @@ trait UserEffects 4 => 'Заклятие хаоса', 5 => 'Заклятие обезличивания', 10 => 'паралич', - 11 => 'легкая травма', - 12 => 'средняя травма', - 13 => 'тяжёлая травма', - 14 => 'неизлечимая травма', + 11 => 'Легкая травма', + 12 => 'Средняя травма', + 13 => 'Тяжёлая травма', + 14 => 'Неизлечимая травма', 20 => 'Проверка Паладинов', 21 => 'Сила нейтралитета', 22 => 'Защита от кулачного нападения', @@ -49,4 +49,40 @@ trait UserEffects 1022 => 'невидимость', 9994 => 'Антидот/Путы (Эликсир?)', ]; + + public static $effectImage = [ + 1 => 'travma.gif', + 2 => 'magic/sleep.gif', + 3 => 'magic/sleepf.gif', + 4 => 'magic/haos.gif', + 5 => 'magic/obezl.gif', + 6 => 'expx15.gif', + 7 => 'euphoria.png', + 8 => 'sleep_obj.gif', + 10 => 'magic/chains.gif', + 11 => 'travma.gif', + 12 => 'travma.gif', + 13 => 'travma.gif', + 14 => 'travma.gif', + 20 => 'check.gif', + 21 => 'magic/al_neut_power.gif', + 22 => 'magic/fist_def.gif', + 201 => 'magic/defence.gif', + 202 => 'magic/devastate.gif', + 203 => 'magic/spell_luck.gif', + 215 => 'magic/wis_air_def1.gif', + 216 => 'magic/wis_air_def2.gif', + 217 => 'magic/wis_air_def3.gif', + 218 => 'magic/wis_earth_def1.gif', + 219 => 'magic/wis_earth_def2.gif', + 220 => 'magic/wis_earth_def3.gif', + 221 => 'magic/wis_fire_def1.gif', + 222 => 'magic/wis_fire_def2.gif', + 223 => 'magic/wis_fire_def3.gif', + 224 => 'magic/wis_water_def1.gif', + 225 => 'magic/wis_water_def2.gif', + 226 => 'magic/wis_water_def3.gif', + 227 => 'magic/attack_defence.gif', + 1022 => 'sh/hidden.gif', + ]; } \ No newline at end of file diff --git a/classes/Battles/UserInfo.php b/classes/Battles/UserInfo.php index ab978cd..e356a25 100644 --- a/classes/Battles/UserInfo.php +++ b/classes/Battles/UserInfo.php @@ -1,9 +1,9 @@ getItemsInSlots(); for ($i = 1; $i <= 12; $i++) { echo sprintf('
', $i); - if (!empty($dressedItems[$i])) { + if (!empty($dressedItems->$i)) { if (!$isBattle && $isMain) { - $itemString = '%s'; - echo sprintf($itemString, mt_rand(), $i, $dressedItems[$i]['image'], $dressedItems[$i]['name'], $dressedItems[$i]['name']); + echo sprintf('%s', + mt_rand(), $i, $dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name); } else { - $itemString = '%s%s'; - echo sprintf($itemString, $dressedItems[$i]['image'], $dressedItems[$i]['name'], $dressedItems[$i]['name']); + echo sprintf('%s%s', + $dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name); } } else { echo sprintf('Пустой слот [%s]', $i, $i); @@ -40,8 +40,8 @@ class UserInfo extends User } echo '
'; if ($isBattle) { - $sh = '%s%sУровень: %s
Сила: %s
Ловкость: %s
Интуиция: %s
Выносливость: %s
Интеллект: %s
Мудрость: %s
'; - echo sprintf($sh, $this->shadow, $this->login, $this->login, $this->level, $this->strength, $this->dexterity, $this->intuition, $this->endurance, $this->intelligence, $this->wisdom); + 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); unset($sh); } else { echo '' . $this->login . ''; @@ -54,12 +54,12 @@ class UserInfo extends User $captions = 'Уровень:
Сила:
Ловкость:
Интуиция:
Выносливость:
Интеллект:
Мудрость:
Местонахождение:'; $variables = $this->level . '
' . - parent::getStat('strength') . '
' . - parent::getStat('dexterity') . '
' . - parent::getStat('intuition') . '
' . - parent::getStat('endurance') . '
' . - parent::getStat('intelligence') . '
' . - parent::getStat('wisdom') . '
' . + parent::getFullStats()->strength . '
' . + parent::getFullStats()->dexterity . '
' . + parent::getFullStats()->intuition . '
' . + parent::getFullStats()->endurance . '
' . + parent::getFullStats()->intelligence . '
' . + parent::getFullStats()->wisdom . '
' . Rooms::$roomNames[$this->room]; if ($isMainWindow) { $this->Bank = new Bank($this->id); @@ -78,31 +78,68 @@ class UserInfo extends User $this->money . '
' . $this->Bank->getMoney(); } - $nameString = ''; - if ($this->align) { - $nameString = sprintf('Склонность', $this->align); + $nameString = null; + $nameString .= $this->align ? "Склонность" : ""; + $nameString .= $this->block ? "$this->login" : "$this->login"; + $nameString .= $this->clan ? "Клан" : ""; + + echo << +
$nameString
+
+
$captions
+
$variables
+
+
+HTML; + } + + /** + * О персонаже для модераторов. + * @return string|null + */ + private function showPrivateData(): ?string + { + if (!$this->watcherIsAdmin || !$this->watcherIsModerator) { + return null; } - if ($this->block) { - $nameString .= '' . $this->login . ''; - } else { - $nameString .= ' ' . $this->login . ' '; + $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']); } - if ($this->clan) { - $nameString .= sprintf('Клан', $this->clan); - } - echo ''; + $adminData = $this->watcherIsAdmin ? $this->showAdminOnlyData() : null; + return << + E-Mail: $this->email
+ ДР Игрока: $birthday
+ IP Регистрации: $this->ip
+ $adminData
+
Личное дело
+ $log +
+
+INFO; + } + + /** + * О персонаже для администраторов. + * @return string|null + */ + private function showAdminOnlyData(): ?string + { + $this->Bank = new Bank($this->id); + $bankMoney = $this->Bank->getMoney(); + return <<id
+ИД Комнаты: $this->room
+Деньги: $this->money
+Деньги в банке: $bankMoney
+Опыт: $this->experience
+Нераспределённые очки: $this->free_stat_points
+INFO; + } private function Info() @@ -110,10 +147,7 @@ class UserInfo extends User echo '