dev #38

Merged
lopar merged 22 commits from dev into master 2021-02-03 08:56:49 +00:00
22 changed files with 284 additions and 1940 deletions
Showing only changes of commit 8402912098 - Show all commits

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

File diff suppressed because it is too large Load Diff