Удалён зодиак. Фиксы перехода php7.2 -> php7.4. Покупка и продажа за банкноты (#25). Унификация вывода кнопок в магазине. Удалён старый закомментированый код. Больше констант. Плавная текучка от библиотеки db::c в сторону DBPDO. И тому подобное. Процесс идёт...
This commit is contained in:
parent
fd6c1e8986
commit
5714ab83f3
@ -7,17 +7,16 @@
|
||||
|
||||
namespace Battles;
|
||||
|
||||
use Config;
|
||||
use Exceptions\GameException;
|
||||
use Battles\Database\DBPDO;
|
||||
use Throwable;
|
||||
|
||||
class Bank
|
||||
{
|
||||
public $user_id;
|
||||
private $money;
|
||||
public int $user_id = 0;
|
||||
private int $money = 0;
|
||||
private $user;
|
||||
private static $db;
|
||||
private static DBPDO $db;
|
||||
|
||||
const ERROR_NO_MONEY_IN_WALLET = "Ошибка! Нет денег в кошельке!";
|
||||
const ERROR_NO_BANK_ACCOUNT = "Ошибка! Счёта не существует!";
|
||||
@ -174,11 +173,11 @@ class Bank
|
||||
self::setBankMoney($this->money, $this->user_id);
|
||||
$this->bankLogs(0, $this->money, "withdrawMoney");
|
||||
// Отдаём сумму в кошелёк получателя
|
||||
$this->user->money += $amount;
|
||||
self::setWalletMoney($this->user->money, $this->user_id);
|
||||
$this->user['money'] += $amount;
|
||||
self::setWalletMoney($this->user['money'], $this->user_id);
|
||||
// Возвращаем изменившиеся значения
|
||||
return [
|
||||
'walletMoney' => $this->user->money,
|
||||
'walletMoney' => $this->user['money'],
|
||||
'bankMoney' => $this->money
|
||||
];
|
||||
}
|
||||
@ -223,7 +222,7 @@ class Bank
|
||||
|
||||
}
|
||||
|
||||
public function getMoney()
|
||||
public function getMoney(): int
|
||||
{
|
||||
return $this->money;
|
||||
}
|
||||
|
@ -3,7 +3,6 @@
|
||||
|
||||
namespace Battles;
|
||||
|
||||
use Config;
|
||||
use SQLite3;
|
||||
use SQLite3Result;
|
||||
|
||||
|
@ -21,6 +21,7 @@ class InventoryItem extends Item
|
||||
{
|
||||
parent::__construct($row);
|
||||
$this->owner_id = $row->owner_id;
|
||||
$this->present = $row->present;
|
||||
$this->db = DBPDO::INIT();
|
||||
}
|
||||
|
||||
@ -28,7 +29,7 @@ class InventoryItem extends Item
|
||||
{
|
||||
parent::printAllInfo();
|
||||
if ($this->present) {
|
||||
echo "<p style='color: maroon; font-style: italic'>Это подарок от {$this->present}. Вы не можете передать его кому-либо ещё.</p>";
|
||||
echo "<p style='color: maroon; font-style: italic'>Это подарок от $this->present. Вы не можете передать его кому-либо ещё.</p>";
|
||||
}
|
||||
}
|
||||
|
||||
@ -71,7 +72,6 @@ IMG;
|
||||
*/
|
||||
public function dressItem()
|
||||
{
|
||||
$db = new DBPDO();
|
||||
$itemInSlot = [];
|
||||
if ($this->dressStatsChecks()) {
|
||||
return self::REQUIREMENTS_NOT_MET;
|
||||
@ -79,8 +79,8 @@ IMG;
|
||||
// считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 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]);
|
||||
$weared = $this->db->ofetchAll('SELECT dressed_slot FROM inventory WHERE dressed_slot != 0 AND item_type = ? AND owner_id = ?', [$this->item_type, $this->owner_id]);
|
||||
$wearedCount = $this->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) {
|
||||
@ -95,11 +95,11 @@ IMG;
|
||||
//работаем с нормальными слотами
|
||||
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]);
|
||||
$this->db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = ? AND owner_id = ?', [$itemInSlot[0], $this->owner_id]);
|
||||
$this->db->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]);
|
||||
$this->db->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;
|
||||
@ -113,11 +113,11 @@ IMG;
|
||||
// Сортируем массив свободных слотов по возрастанию.
|
||||
sort($emptyRingSlots);
|
||||
// Одеваем предмет в первый свободный слот.
|
||||
DBPDO::INIT()->execute('update inventory set dressed_slot = ? where item_id = ?', [$emptyRingSlots[0], $this->item_id]);
|
||||
$this->db->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);
|
||||
$this->db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11');
|
||||
$this->db->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $this->item_id);
|
||||
} else {
|
||||
/* проверка на переполнение слотов */
|
||||
$error = self::TOO_MANY_ITEMS_IN_SLOTS;
|
||||
@ -127,7 +127,7 @@ IMG;
|
||||
$error = self::UNKNOWN_ITEM_TYPE;
|
||||
}
|
||||
|
||||
return isset($error) ? $error : true;
|
||||
return $error ?? true;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -137,7 +137,6 @@ IMG;
|
||||
*/
|
||||
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]);
|
||||
return DBPDO::INIT()->execute('delete from inventory where dressed_slot = 0 and owner_id = ? and item_id = ?', [$_SESSION['uid'], $itemId]);
|
||||
}
|
||||
}
|
@ -6,7 +6,6 @@ class Item
|
||||
protected $name;
|
||||
protected $item_type;
|
||||
protected $durability;
|
||||
protected $price;
|
||||
protected $need_strength;
|
||||
protected $need_dexterity;
|
||||
protected $need_intuition;
|
||||
@ -102,8 +101,6 @@ class Item
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
protected function wrap(int $number):string
|
||||
{
|
||||
if ($number > 0) {
|
||||
@ -134,10 +131,9 @@ class Item
|
||||
"Увёртливость" => $this->add_evasion,
|
||||
"Шанс крита" => $this->add_criticals,
|
||||
];
|
||||
echo "<b>" . $this->name . "</b> (Масса: " . $this->weight . ")";
|
||||
echo "<b>$this->name</b> (Масса: $this->weight)";
|
||||
echo "<br> Долговечность: " . $this->durability;
|
||||
|
||||
echo "<br><em>{$this->typename}</em><br>";
|
||||
echo "<br><em>$this->typename</em><br>";
|
||||
foreach ($needsLines as $stat => $value) {
|
||||
if ($value > 0) {
|
||||
echo "<br>Требуется $stat" . $this->wrap($value);
|
||||
|
@ -3,107 +3,213 @@
|
||||
namespace Battles;
|
||||
|
||||
use Battles\Database\DBPDO;
|
||||
use Exceptions\GameException;
|
||||
|
||||
class ShopItem extends Item
|
||||
{
|
||||
private const NO_ITEMS_IN_STOCK = "Товара нет в наличии!";
|
||||
private const NO_MONEY = "У вас нет денег!";
|
||||
private const BUTTON = [
|
||||
'setmarket' => 'Сдать в магазин',
|
||||
'unsetmarket' => 'Снять с продажи',
|
||||
'buymarket' => 'Совершить обмен',
|
||||
'sellshop' => 'Продать',
|
||||
'buyshop' => 'Купить',
|
||||
];
|
||||
private const BUY_QUERY = 'insert into inventory (owner_id, name, item_type, durability,
|
||||
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, price)
|
||||
select
|
||||
?,
|
||||
ifnull(name,\'Неизвестный предмет\'),
|
||||
ifnull(item_type,0),
|
||||
ifnull(durability, 1),
|
||||
ifnull(need_strength, 0),
|
||||
ifnull(need_dexterity, 0),
|
||||
ifnull(need_intuition, 0),
|
||||
ifnull(need_endurance, 0),
|
||||
ifnull(need_intelligence, 0),
|
||||
ifnull(need_wisdom, 0),
|
||||
ifnull(add_strength, 0),
|
||||
ifnull(add_dexterity, 0),
|
||||
ifnull(add_intuition, 0),
|
||||
ifnull(add_endurance, 0),
|
||||
ifnull(add_intelligence, 0),
|
||||
ifnull(add_wisdom, 0),
|
||||
ifnull(add_accuracy, 0),
|
||||
ifnull(add_evasion, 0),
|
||||
ifnull(add_criticals, 0),
|
||||
ifnull(add_min_physical_damage, 0),
|
||||
ifnull(add_max_physical_damage, 0),
|
||||
ifnull(image, \'noitem.png\'),
|
||||
ifnull(weight, 1),
|
||||
?
|
||||
from items where id = ?';
|
||||
// Тип операции в магазине. Для отображения разных блоков в разных случаях.
|
||||
private $optype;
|
||||
private ?int $shop_item_quantity;
|
||||
private ?int $bank_price;
|
||||
private ?int $price;
|
||||
|
||||
public function __construct($row, $operationType = null)
|
||||
{
|
||||
parent::__construct($row);
|
||||
if ($operationType) {
|
||||
$this->optype = $operationType;
|
||||
}
|
||||
$this->price = $row->price ?? null;
|
||||
$this->shop_item_quantity = $row->shop_item_quantity ?? null;
|
||||
$this->bank_price = $row->bank_price ?? null;
|
||||
$this->item_id = $row->item_id ?? $row->id;
|
||||
}
|
||||
|
||||
public function printInfo()
|
||||
{
|
||||
parent::printAllInfo();
|
||||
$this->printAllInfo();
|
||||
if ($this->optype === 'buyshop') {
|
||||
if ($this->bank_price) {
|
||||
echo "<div>Цена: $this->bank_price банкнот.</div>";
|
||||
}
|
||||
if ($this->shop_item_quantity > 0 && $this->shop_item_quantity < 20) {
|
||||
echo "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shop_item_quantity единиц товара!</div>";
|
||||
}
|
||||
}
|
||||
if ($this->optype === 'sellshop') {
|
||||
if ($this->getSellPriceMean() < 50) {
|
||||
$goods = 'этот хлам';
|
||||
} elseif ($this->getSellPriceMean() < 100) {
|
||||
$goods = 'этот посредственный товар';
|
||||
} elseif ($this->getSellPriceMean() < 500) {
|
||||
$goods = 'этот неплохой предмет';
|
||||
} elseif ($this->getSellPriceMean() < 1000) {
|
||||
$goods = 'эту отличную штуку';
|
||||
} else {
|
||||
$goods = 'это превосходное изделие';
|
||||
}
|
||||
echo "<div style='margin-top: 9px; font-style: italic;'>В среднем за $goods можно выручить <span class='success'>{$this->getSellPriceMean()}</span> кр.</div>";
|
||||
}
|
||||
}
|
||||
|
||||
public function printImage(): string
|
||||
{
|
||||
if (!$this->image) {
|
||||
$this->image = 'noitem.png';
|
||||
}
|
||||
return "<img src='/i/sh/$this->image' class='item-wrap-normal' alt=''>";
|
||||
}
|
||||
|
||||
public static function buyItem($id, User $buyer): string
|
||||
{
|
||||
//TODO Добавить снятие денег с проверками на их наличие.
|
||||
$db = new DBPDO();
|
||||
$item = $db->ofetch('select * from shop where item_id = ?', $id);
|
||||
$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 = [
|
||||
$buyer->getId(), $item->name, $item->item_type, $item->durability, $item->price,
|
||||
$item->need_strength, $item->need_dexterity, $item->need_intuition,
|
||||
$item->need_endurance, $item->need_intelligence, $item->need_wisdom,
|
||||
$item->add_strength, $item->add_dexterity, $item->add_intuition,
|
||||
$item->add_endurance, $item->add_intelligence, $item->add_wisdom,
|
||||
$item->add_accuracy, $item->add_evasion, $item->add_criticals,
|
||||
$item->add_min_physical_damage, $item->add_max_physical_damage,
|
||||
$item->image, $item->weight
|
||||
];
|
||||
$db->execute($query, $values);
|
||||
$deloText = "{$buyer->getLogin()} купил товар «{$item->name}» id:($id) в магазине за $item->price кр.";
|
||||
$check = $db->ofetch("select * from trade_offers where shop_item_id = ?", $id);
|
||||
$itemPrice = $check->bank_price ?? 0;
|
||||
if (empty($check->shop_item_quantity) || empty($check->shop_item_id)) {
|
||||
return self::NO_ITEMS_IN_STOCK;
|
||||
}
|
||||
|
||||
// TODO БАРТЕР!
|
||||
if (isset($check->barter_item_list_json)) {
|
||||
echo "Работаем по бартеру!";
|
||||
}
|
||||
|
||||
$db->execute(self::BUY_QUERY, [$buyer->getId(), $itemPrice, $check->shop_item_id]);
|
||||
$item = $db->ofetch("select item_id, name, price from inventory where item_id = ?", $db->lastInsertId());
|
||||
if (empty($item->item_id) || empty($item->name) || empty($item->price)) {
|
||||
return 'Запрос в базу не прошёл.';
|
||||
} else {
|
||||
$boughtItemId = $item->item_id;
|
||||
$boughtItemName = $item->name;
|
||||
$boughtItemPrice = $item->price;
|
||||
if ($item->price > 0) {
|
||||
try {
|
||||
$bank = new Bank($buyer->getId());
|
||||
$bank->withdrawMoney($item->price);
|
||||
} catch (GameException $e) {
|
||||
echo 'Банковская ошибка!';
|
||||
return self::NO_MONEY;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if ($check->shop_item_quantity != -1) {
|
||||
$db->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_id = ?", $check->shop_item_id);
|
||||
}
|
||||
|
||||
$deloText = $buyer->getLogin() . " купил товар «" . $boughtItemName . "» id:(" . $boughtItemId . ") в магазине за " . $boughtItemPrice . " банкнот.";
|
||||
GameLogs::addUserLog($buyer->getId(), $deloText);
|
||||
return "Предмет $item->name куплен за $item->price.";
|
||||
return "Предмет " . $boughtItemName . " куплен за " . $boughtItemPrice . " банкнот.";
|
||||
}
|
||||
|
||||
//TODO не пишутся логи продажи!
|
||||
|
||||
/** TODO
|
||||
* Notice: Undefined index: shopsell in /volume2/web/battles/classes/Battles/Bank.php on line 199 Call Stack: 0.0003 430192
|
||||
* 1. {main}() /volume2/web/battles/shop.php:0 0.0051 966928
|
||||
* 2. Battles\ShopItem::sellItem() /volume2/web/battles/shop.php:21 0.1067 998536
|
||||
* 3. Battles\Bank::setBankMoney() /volume2/web/battles/classes/Battles/ShopItem.php:162
|
||||
* Не отработал запрос в БД в файле /volume2/web/battles/classes/Battles/GameLogs.php(20)
|
||||
*/
|
||||
public static function sellItem($id, User $seller, $bankTrade = 0): string
|
||||
{
|
||||
$db = new DBPDO();
|
||||
$item = $db->ofetch('select * from inventory where item_id = ?', $id);
|
||||
$sellingItemName = $item->name;
|
||||
// Продажа за цену от нуля до половины стоимости.
|
||||
$sellingPrice = mt_rand(0, $item->price / 2);
|
||||
$db->execute('delete from inventory where item_id = ?', $id);
|
||||
if ($bankTrade) {
|
||||
$bank = new Bank($seller->getId());
|
||||
$bank->setMoney($bank->getMoney() - $sellingPrice);
|
||||
$bank->setMoney($bank->getMoney() + $sellingPrice);
|
||||
Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'shopsell');
|
||||
} else {
|
||||
$db->execute('update users set money = money - ? where id = ?', [$sellingPrice, $_SESSION['uid']]);
|
||||
}
|
||||
$deloText = "{$seller->getLogin()} продал товар «{$item->name}» id:($id) в магазине за $sellingPrice кр.";
|
||||
$deloText = "{$seller->getLogin()} продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр.";
|
||||
GameLogs::addUserLog($seller->getId(), $deloText);
|
||||
if ($sellingPrice == 0) {
|
||||
$status = "После длительных и изнурительных торгов вы плюнули на всё и просто подарили ваш «{$item->name}» торговцу.";
|
||||
$status = "После длительных и изнурительных торгов вы плюнули на всё и просто подарили ваш «{$sellingItemName}» торговцу.";
|
||||
} else {
|
||||
$status = "Вы продали «{$item->name}» за $sellingPrice кр.";
|
||||
$status = "Вы продали «{$sellingItemName}» за $sellingPrice кр.";
|
||||
}
|
||||
return $status;
|
||||
}
|
||||
|
||||
/** Подчсчёт средней суммы продажи.
|
||||
* @return int
|
||||
*/
|
||||
private function getSellPriceMean(): ?int
|
||||
{
|
||||
if ($this->price) {
|
||||
$arr = range(0, $this->price / 2);
|
||||
return array_sum($arr) / sizeof($arr);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Для кнопок управления под картинкой предмета в зависимости от ситуации.
|
||||
* @param null $shopType
|
||||
*/
|
||||
public function printControls($shopType = null)
|
||||
public function printControls()
|
||||
{
|
||||
if ($shopType === 'marketput') {
|
||||
echo <<<BTN
|
||||
<form method="post">
|
||||
<input placeholder="{$this->price}" name="cost">
|
||||
<input type="hidden" name="putId" value="{$this->item_id}">
|
||||
<br><input type="submit" name="putToMarket" value="Cдать в магазин">
|
||||
if (in_array($this->optype, ['setmarket', 'unsetmarket', 'buymarket', 'sellshop', 'buyshop',])) {
|
||||
$str = $this->optype == 'setmarket' ? '<input placeholder=" ' . $this->price . ' " name="cost">' : '';
|
||||
$button_name = self::BUTTON[$this->optype];
|
||||
echo <<<FORM
|
||||
<form method="post">$str
|
||||
<input type="hidden" name="itemId" value="$this->item_id">
|
||||
<br><input type="submit" name="$this->optype" value="$button_name">
|
||||
</form>
|
||||
BTN;
|
||||
} else {
|
||||
switch ($shopType) {
|
||||
default:
|
||||
$btnValue = "Купить за " . intval($this->price) . " кр.";
|
||||
$btnLink = "/shop.php?buy={$this->item_id}&rnd=" . mt_rand();
|
||||
break;
|
||||
case 'sell':
|
||||
$btnValue = "Продать";
|
||||
$btnLink = "/shop.php?sell={$this->item_id}&rnd=" . mt_rand();
|
||||
break;
|
||||
case 'marketgetback':
|
||||
$btnValue = "Снять с продажи";
|
||||
$btnLink = "?back={$this->item_id}&rnd=" . mt_rand();
|
||||
break;
|
||||
case 'marketbuy':
|
||||
$btnValue = "Купить за " . intval($this->setsale) . " кр.";
|
||||
$btnLink = "?otdel={$this->item_type}&set={$this->item_id}&rnd=" . mt_rand();
|
||||
break;
|
||||
}
|
||||
|
||||
echo <<<BTN
|
||||
<p><input type="button" style="background: darkgrey; border: 1px solid grey; border-radius: 2px;" value="{$btnValue}"
|
||||
onclick="location='{$btnLink}'">
|
||||
BTN;
|
||||
FORM;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @return mixed
|
||||
*/
|
||||
public function getItemType()
|
||||
{
|
||||
return $this->item_type;
|
||||
}
|
||||
}
|
@ -45,52 +45,6 @@ class User
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
protected function showStarSign(): ?string
|
||||
{
|
||||
/*
|
||||
* 1 aries
|
||||
* 2 taurus
|
||||
* 3 gemini
|
||||
* 4 cancer
|
||||
* 5 leo
|
||||
* 6 virgo
|
||||
* 7 libra
|
||||
* 8 scorpio
|
||||
* 9 sagittarios
|
||||
* 10 capricorn
|
||||
* 11 aquarius
|
||||
* 12 pisches
|
||||
*/
|
||||
$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) {
|
||||
--$dayOfYear;
|
||||
}
|
||||
foreach ($zodiac as $day => $sign) {
|
||||
if ($dayOfYear > $day) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
return $sign ?? null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* @param int $userId
|
||||
* @param int $type
|
||||
|
@ -1,15 +1,24 @@
|
||||
<?php
|
||||
|
||||
namespace Battles;
|
||||
|
||||
use Battles\Database\DBPDO;
|
||||
use Battles\Models\EffectsModel;
|
||||
|
||||
class UserInfo extends UserStats
|
||||
{
|
||||
use Rooms;
|
||||
//Статусы того, кто смотрит на информацию.
|
||||
public $watcher_id;
|
||||
private $watcherIsAdmin;
|
||||
private $watcherIsModerator;
|
||||
|
||||
private int $bankMoney;
|
||||
//Тот, кто смотрит на информацию.
|
||||
private User $watcher;
|
||||
|
||||
public function __construct($user)
|
||||
{
|
||||
parent::__construct($user);
|
||||
$bank = new Bank($this->id);
|
||||
$this->bankMoney = $bank->getMoney();
|
||||
}
|
||||
|
||||
/**
|
||||
* Отображает куклу персонажа (образ и слоты).
|
||||
@ -19,7 +28,7 @@ class UserInfo extends UserStats
|
||||
* @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает
|
||||
* его).
|
||||
*/
|
||||
private function UserInfoDoll($isBattle = 0, $isMain = 0)
|
||||
private function UserInfoDoll(int $isBattle = 0, int $isMain = 0)
|
||||
{
|
||||
$di = new DressedItems($this->id);
|
||||
$dressedItems = $di->getItemsInSlots();
|
||||
@ -49,6 +58,45 @@ class UserInfo extends UserStats
|
||||
echo '</div><!-- slot-image -->';
|
||||
}
|
||||
|
||||
private function ttz()
|
||||
{
|
||||
$arr = [
|
||||
'Уровень' => $this->level,
|
||||
'Сила' => $this->printStat('strength'),
|
||||
'Ловкость' => $this->printStat('dexterity'),
|
||||
'Интуиция' => $this->printStat('intuition'),
|
||||
'Выносливость' => $this->printStat('endurance'),
|
||||
'Интеллект' => $this->printStat('intelligence'),
|
||||
'Мудрость' => $this->printStat('wisdom'),
|
||||
'Уворот' => $this->getFullStats()->evasion,
|
||||
'Точность' => $this->getFullStats()->accuracy,
|
||||
'Шанс крита' => $this->getFullStats()->criticals,
|
||||
'Урон' => $this->getFullStats()->min_physical_damage . ' - ' . $this->getFullStats()->max_physical_damage,
|
||||
'Локация' => Rooms::$roomNames[$this->room],
|
||||
|
||||
];
|
||||
$str = null;
|
||||
$i = 0;
|
||||
foreach ($arr as $item => $value) {
|
||||
$str .= "<div class='column' style='text-align: right; margin-right: 10px;'>$item</div><div class='column'>$value</div>";
|
||||
if (in_array($i,[6,9])) {
|
||||
$str .= "<div style='margin-top: 10px;'></div><div></div>";
|
||||
}
|
||||
$i++;
|
||||
}
|
||||
$nameString = $this->align ? "<img src='/i/align_$this->align.png' alt='Склонность'>" : "";
|
||||
$nameString .= $this->block ? "<span class='private' style='text-decoration: line-through;'>$this->login</span>" : "<b>$this->login</b>";
|
||||
$nameString .= $this->clan ? "<img src='/i/clan/$this->clan.png' alt='Клан'>" : "";
|
||||
echo "<div class='info'><b>$nameString</b></div><!-- info -->";
|
||||
echo "<div class='stats-container' style='display: grid; grid-template-columns: 150px 100px; font-size: 1.2em;'>$str</div>";
|
||||
}
|
||||
|
||||
private function printStat($statName): string
|
||||
{
|
||||
return $this->getFreeStatPoints() ? $this->getStat($statName, 1) . '(' . $this->getFullStats()->$statName . ')' : $this->getFullStats()->$statName;
|
||||
}
|
||||
|
||||
//TODO вызывать из main.php
|
||||
private function UserInfoStats($isMainWindow = 0)
|
||||
{
|
||||
$captions = 'Уровень:<br>Сила:<br>Ловкость:<br>Интуиция:<br>Выносливость:<br>Интеллект:<br>Мудрость:<br>Местонахождение:';
|
||||
@ -62,7 +110,6 @@ class UserInfo extends UserStats
|
||||
parent::getFullStats()->wisdom . '<br>' .
|
||||
Rooms::$roomNames[$this->room];
|
||||
if ($isMainWindow) {
|
||||
$this->Bank = new Bank($this->id);
|
||||
$captions = 'Уровень:<br>Здоровье:<br>Сила:<br>Ловкость:<br>Интуиция:<br>Выносливость:<br>Интеллект:<br>Мудрость:<br>Опыт:<br>Очки характеристик:<br>Деньги:<br>Деньги в банке:';
|
||||
$variables =
|
||||
$this->level . '<br>' .
|
||||
@ -76,7 +123,7 @@ class UserInfo extends UserStats
|
||||
$this->experience . '<br>' .
|
||||
$this->free_stat_points . '<br>' .
|
||||
$this->money . '<br>' .
|
||||
$this->Bank->getMoney();
|
||||
$this->bankMoney;
|
||||
}
|
||||
$nameString = null;
|
||||
$nameString .= $this->align ? "<img src='/i/align_$this->align.png' alt='Склонность'>" : "";
|
||||
@ -100,16 +147,13 @@ HTML;
|
||||
*/
|
||||
private function showPrivateData(): ?string
|
||||
{
|
||||
if (!$this->watcherIsAdmin || !$this->watcherIsModerator) {
|
||||
return null;
|
||||
}
|
||||
$birthday = date('d.m.Y', strtotime($this->borndate));
|
||||
$userLogs = GameLogs::getUserLogs($this->id);
|
||||
$log = null;
|
||||
while ($userLogRow = $userLogs->fetchArray(SQLITE3_ASSOC)) {
|
||||
$log .= sprintf('<code>%s</code><br>', date('d.m.Y H:i ', strtotime($userLogRow['date'])) . $userLogRow['text']);
|
||||
}
|
||||
$adminData = $this->watcherIsAdmin ? $this->showAdminOnlyData() : null;
|
||||
$adminData = $this->watcher->getAdmin() ? $this->showAdminOnlyData() : null;
|
||||
return <<<INFO
|
||||
<div class="secret-info">
|
||||
E-Mail: $this->email<br>
|
||||
@ -129,15 +173,13 @@ INFO;
|
||||
*/
|
||||
private function showAdminOnlyData(): ?string
|
||||
{
|
||||
$this->Bank = new Bank($this->id);
|
||||
$bankMoney = $this->Bank->getMoney();
|
||||
return <<<INFO
|
||||
ИД Игрока: $this->id<br>
|
||||
ИД Комнаты: $this->room<br>
|
||||
Деньги: $this->money<br>
|
||||
Деньги в банке: $bankMoney<br>
|
||||
Опыт: $this->experience<br>
|
||||
Нераспределённые очки: $this->free_stat_points<br>
|
||||
⁑ ИД Игрока: $this->id<br>
|
||||
⁑ ИД Комнаты: $this->room<br>
|
||||
⁑ Деньги: $this->money<br>
|
||||
⁑ Деньги в банке: $this->bankMoney<br>
|
||||
⁑ Опыт: $this->experience<br>
|
||||
⁑ Нераспределённые очки: $this->free_stat_points<br>
|
||||
INFO;
|
||||
|
||||
}
|
||||
@ -146,30 +188,27 @@ INFO;
|
||||
{
|
||||
echo '<div class="user-info-container">';
|
||||
$this->UserInfoDoll();
|
||||
$this->UserInfoStats();
|
||||
echo '<div class="slot-lower"> <!-- statuses! -->';
|
||||
echo '</div><!-- slot-lower -->';
|
||||
echo '<div class="user-signs">';
|
||||
echo sprintf('<img src="i/zodiac/%s.png" alt="Родовой знак">', $this->showStarSign());
|
||||
echo '</div><!-- user-signs -->';
|
||||
echo '</div><!-- user-info-container -->';
|
||||
$this->ttz();
|
||||
echo '<div class="slot-lower"> <!-- statuses! --></div>';
|
||||
echo '</div><!-- u-i-c -->';
|
||||
echo '<hr><!-- Нижняя часть -->';
|
||||
echo '<div class="user-info-container-lower">';
|
||||
echo '<h2>Об игроке</h2>';
|
||||
echo $this->realname ? "Имя: $this->realname" : "";
|
||||
echo $this->info ? "<br>" . nl2br($this->info) : "";
|
||||
echo '</div><!-- user-info-container-lower -->';
|
||||
echo $this->showPrivateData();
|
||||
echo '</div><!-- u-i-c-l -->';
|
||||
if ($this->watcher->getAdmin() || $this->watcher->getAlign() == 1) {
|
||||
echo $this->showPrivateData();
|
||||
}
|
||||
}
|
||||
|
||||
public function showUserInfo()
|
||||
{
|
||||
$this->WatcherStatus();
|
||||
$effects = new EffectsModel($this->id);
|
||||
|
||||
if ($this->block && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
|
||||
if ($this->block && (!$this->watcher->getAdmin() || !$this->watcher->getAlign() == 1)) {
|
||||
echo "<span class='error'>Персонаж $this->login заблокирован!</span>";
|
||||
} elseif ($effects->getHideUserInfoStatus() && (!$this->watcherIsAdmin || !$this->watcherIsModerator)) {
|
||||
} elseif ($effects->getHideUserInfoStatus() && (!$this->watcher->getAdmin() || !$this->watcher->getAlign() == 1)) {
|
||||
if ($effects->getHideUserInfoStatus() == -1) {
|
||||
$date = 'навсегда';
|
||||
} else {
|
||||
@ -181,17 +220,6 @@ INFO;
|
||||
}
|
||||
}
|
||||
|
||||
private function WatcherStatus()
|
||||
{
|
||||
$query = parent::$db->fetch('SELECT align, admin FROM users WHERE id = ?', $this->watcher_id);
|
||||
if ($query['admin']) {
|
||||
$this->watcherIsAdmin = 1;
|
||||
}
|
||||
if ($query['align'] == 1) {
|
||||
$this->watcherIsModerator = 1;
|
||||
}
|
||||
}
|
||||
|
||||
public function showUserDoll($isBattle = 0, $isMain = 0)
|
||||
{
|
||||
echo '<div class="user-info-container">';
|
||||
@ -216,17 +244,22 @@ INFO;
|
||||
$timeleft = timeOut($effect->remaining_time - time());
|
||||
$r .= "
|
||||
<div>
|
||||
<img class='image' src='/i/{$img[$effect->type]}' alt='{$effect->name}'>
|
||||
<span class='title'>{$effect->name}</span>
|
||||
<img class='image' src='/i/{$img[$effect->type]}' alt='$effect->name'>
|
||||
<span class='title'>$effect->name</span>
|
||||
<div class='timeleft'>$timeleft</div>
|
||||
</div>
|
||||
";
|
||||
}
|
||||
return $r;
|
||||
}
|
||||
public function showStarSign(): ?string
|
||||
|
||||
/**
|
||||
* @param mixed $watcher_id
|
||||
*/
|
||||
public function setWatcher(int $watcher_id): void
|
||||
{
|
||||
return parent::showStarSign();
|
||||
$this->watcher = new User($watcher_id);
|
||||
}
|
||||
|
||||
|
||||
}
|
@ -8,7 +8,7 @@
|
||||
|
||||
ini_set('display_errors', 'On');
|
||||
error_reporting(E_ALL);
|
||||
define("GAMEDOMAIN", "battles.lan");
|
||||
const GAMEDOMAIN = "battles.lan";
|
||||
/*
|
||||
* Запрещаем кэшировать
|
||||
*/
|
||||
|
@ -6,6 +6,8 @@
|
||||
*/
|
||||
|
||||
use Battles\Database\DBPDO;
|
||||
use Battles\DressedItems;
|
||||
use Battles\InventoryItem;
|
||||
use Battles\Travel;
|
||||
use Battles\User;
|
||||
|
||||
@ -109,7 +111,7 @@ $var_map = [
|
||||
function get_out($u)
|
||||
{
|
||||
$pers = db::c()->query('SELECT * FROM users WHERE id = ?i', $u)->fetch_assoc_array();
|
||||
\Battles\DressedItems::undressAllItems($pers['id']);
|
||||
DressedItems::undressAllItems($pers['id']);
|
||||
db::c()->query('UPDATE inventory SET owner = ?i WHERE owner = ?i', $pers['id'], $pers['id'] + _BOTSEPARATOR_);
|
||||
###
|
||||
$row = db::c()->query('SELECT * FROM `effects` WHERE `owner` = ?i', $pers['id'] + _BOTSEPARATOR_);
|
||||
@ -461,7 +463,7 @@ function ref_drop()
|
||||
$user = db::c()->query('SELECT `sergi`,`kulon`,`weap`,`bron`,`r1`,`r2`,`r3`,`helm`,`perchi`,`shit`,`boots`,`m1`,`m2`,`m3`,`m4`,`m5`,`m6`,`m7`,`m8`,`m9`,`m10` FROM `users` WHERE id = ?i', $_SESSION['uid'])->fetch_assoc();
|
||||
for ($i = 0; $i <= 20; $i++) {
|
||||
if ($user[$slot[$i]] && !derj($user[$slot[$i]])) {
|
||||
$item = new \Battles\DressedItems($_SESSION['uid']);
|
||||
$item = new DressedItems($_SESSION['uid']);
|
||||
$item->undressItem($i + 1);
|
||||
$user[$slot[$i]] = null;
|
||||
}
|
||||
@ -528,7 +530,7 @@ function usemagic($id, $target)
|
||||
}
|
||||
if ($bat) {
|
||||
if ($row['maxdur'] <= ($row['duration'] + 1)) {
|
||||
\Battles\InventoryItem::destroyItem($row['id']);
|
||||
InventoryItem::destroyItem($row['id']);
|
||||
} else {
|
||||
if (!$row['magic']) {
|
||||
db::c()->query('UPDATE `inventory` SET `includemagicdex` =`includemagicdex` - ?i WHERE id = ?i', $bat, $row['id']);
|
||||
@ -630,15 +632,15 @@ function get_meshok()
|
||||
* Надеюсь временная заглушка, которая объединяет get_meshok() и другую выдачу одной строкой.
|
||||
* @return string
|
||||
*/
|
||||
function getItemsMassaInfo()
|
||||
function getItemsMassaInfo(): string
|
||||
{
|
||||
$i_row = db::c()->query('SELECT SUM(`massa`) AS `massa`, SUM(`gmeshok`) AS `massa_bonus` FROM `inventory` WHERE `setsale` = 0 AND `owner` = ?i', $_SESSION['uid'])->fetch_assoc();
|
||||
$u_row = db::c()->query('SELECT `sila` FROM `users` WHERE `id` = ?i', $_SESSION['uid'])->fetch_assoc();
|
||||
if ($i_row['massa'] > $u_row['sila'] * 4 + $i_row['massa_bonus']) {
|
||||
return "<span style='color:maroon;'>" . $i_row['massa'] . "</span>/" . ($u_row['sila'] * 4 + $i_row['massa_bonus']);
|
||||
} else {
|
||||
return $i_row['massa'] . "/" . ($u_row['sila'] * 4 + $i_row['massa_bonus']);
|
||||
$itemRow = DBPDO::INIT()->ofetch("select sum(weight) as all_weight from inventory where owner_id = ?", $_SESSION['uid']);
|
||||
$userRow = DBPDO::INIT()->ofetch("select strength * 4 as max_weight from users where id = ?", $_SESSION['uid']);
|
||||
$textStyle = '';
|
||||
if ($itemRow->all_weight > $userRow->max_weight) {
|
||||
$textStyle = " style='color:maroon;'";
|
||||
}
|
||||
return "<span$textStyle>$itemRow->all_weight / $userRow->max_weight</span>";
|
||||
}
|
||||
|
||||
function addlog($id, $log)
|
||||
|
13
inf.php
13
inf.php
@ -1,11 +1,16 @@
|
||||
<?php
|
||||
|
||||
use Battles\Models\PresentsModel;
|
||||
use Battles\Template;
|
||||
use Battles\UserInfo;
|
||||
|
||||
session_start();
|
||||
include_once 'config.php';
|
||||
$userInfo = new \Battles\UserInfo(urldecode($_SERVER['QUERY_STRING']));
|
||||
$presentsModel = new \Battles\Models\PresentsModel($userInfo->getId());
|
||||
$userInfo = new UserInfo(urldecode($_SERVER['QUERY_STRING']));
|
||||
$presentsModel = new PresentsModel($userInfo->getId());
|
||||
$presentsList = $presentsModel->getAllPresents();
|
||||
$userInfo->watcher_id = $_SESSION['uid'] ?? null;
|
||||
\Battles\Template::header('Информация о ' . $userInfo->getLogin());
|
||||
$userInfo->setWatcher($_SESSION['uid']);
|
||||
Template::header('Информация о ' . $userInfo->getLogin());
|
||||
if (!$userInfo->getId()) {
|
||||
echo sprintf('Ошибка: персонаж <em>%s</em> не найден...<p><a style="color: #99f;" href="javascript:window.history.go(-1);">←назад</a></p>', urldecode($_SERVER['QUERY_STRING']));
|
||||
exit;
|
||||
|
62
library.php
62
library.php
@ -1,7 +1,11 @@
|
||||
<?php
|
||||
|
||||
use Battles\Template;
|
||||
use Battles\UserInfo;
|
||||
|
||||
session_start();
|
||||
require_once "functions.php";
|
||||
\Battles\Template::header('Библиотека Просвещения');
|
||||
Template::header('Библиотека Просвещения');
|
||||
?>
|
||||
<TABLE border=0 width=600 cellspacing="0" cellpadding="0" align=left>
|
||||
|
||||
@ -211,62 +215,12 @@ if ($_GET['lib_room'] == 'hall' || !$_GET['lib_room']) {
|
||||
addchp('Вы успешно создали свиток <strong>' . $dress['name'] . '</strong>!', '{[]}' . Nick::id($user['id'])->short() . '{[]}');
|
||||
}
|
||||
}
|
||||
$a = new \Battles\UserInfo($user['id']);
|
||||
$a = new UserInfo($user['id']);
|
||||
echo "<tr><td>Вы стоите в небольшой комнате, от пола до потолка забтиой банками, пробирками, ингредиентами и прочими полезными вещами.
|
||||
Здесь Вы можете собрать предметы по имеющимся у Вас рецептам.<br><br><img align=left alt='Родовой знак' src='i/zodiac/{$a->showStarSign()}.png'";
|
||||
Здесь Вы можете собрать предметы по имеющимся у Вас рецептам.";
|
||||
|
||||
//выводим инфо по стихиям
|
||||
echo 'Ваша стихия:';
|
||||
$el = element($a->showStarSign());
|
||||
switch ($el) {
|
||||
case 'a':
|
||||
echo "<strong><font color=#0198ef><ins>Воздух</ins></font></strong>";
|
||||
break;
|
||||
case 'w':
|
||||
echo "<strong><font color=#0d2b99><ins>Вода</ins></font></strong>";
|
||||
break;
|
||||
case 'f':
|
||||
echo "<strong><font color=#df0d0d><ins>Огонь</ins></font></strong>";
|
||||
break;
|
||||
case 'e':
|
||||
echo "<strong><font color=#086604><ins>Земля</ins></font></strong>";
|
||||
break;
|
||||
}
|
||||
echo "<br/>Эффективность магии:";
|
||||
$elem_align = [
|
||||
'a' => ['a' => '1', 'e' => '0', 'f' => '0.5', 'w' => '0.5'],
|
||||
'e' => ['a' => '0', 'e' => '1', 'f' => '0.5', 'w' => '0.5'],
|
||||
'f' => ['a' => '0.5', 'e' => '0.5', 'f' => '1', 'w' => '0'],
|
||||
'w' => ['a' => '0.5', 'e' => '0.5', 'f' => '0', 'w' => '1'],
|
||||
];
|
||||
foreach ($elem_align as $k => $ea) {
|
||||
switch ($k) {
|
||||
case 'a':
|
||||
echo "<br/><font color=#0198ef>Воздух</font>";
|
||||
break;
|
||||
case 'w':
|
||||
echo "<br/><font color=#0d2b99>Вода</font>";
|
||||
break;
|
||||
case 'f':
|
||||
echo "<br/><font color=#df0d0d>Огонь</font>";
|
||||
break;
|
||||
case 'e':
|
||||
echo "<br/><font color=#086604>Земля</font>";
|
||||
break;
|
||||
}
|
||||
switch ($ea[$el]) {
|
||||
case '0':
|
||||
echo " : <font color=gray>" . ($ea[$el] * 100) . "%</font>";
|
||||
break;
|
||||
case '0.5':
|
||||
echo " : " . ($ea[$el] * 100) . "%";
|
||||
break;
|
||||
case '1':
|
||||
echo " : <b>" . ($ea[$el] * 100) . "%</b>";
|
||||
break;
|
||||
}
|
||||
}
|
||||
echo '</td></tr>';
|
||||
|
||||
if ($craft_err) {
|
||||
echo "<tr><td><font color=red>Недостаточно ингредиентов!</font></td></tr>";
|
||||
}
|
||||
|
12
main.php
12
main.php
@ -1,11 +1,14 @@
|
||||
<?php
|
||||
|
||||
/**
|
||||
* @var User $user
|
||||
*/
|
||||
use Battles\Database\DBPDO;
|
||||
use Battles\DressedItems;
|
||||
use Battles\GameLogs;
|
||||
use Battles\InventoryItem;
|
||||
use Battles\Template;
|
||||
use Battles\Travel;
|
||||
use Battles\User;
|
||||
use Battles\UserInfo;
|
||||
use Battles\UserStats;
|
||||
|
||||
@ -73,7 +76,7 @@ if ($edit) {
|
||||
usemagic($use, $useTarget);
|
||||
}
|
||||
if ($undress) {
|
||||
\Battles\DressedItems::undressAllItems($_SESSION['uid']);
|
||||
DressedItems::undressAllItems($_SESSION['uid']);
|
||||
}
|
||||
}
|
||||
|
||||
@ -84,7 +87,7 @@ $userStats = new UserStats($user->getId());
|
||||
$data = DBPDO::INIT()->ofetchAll('SELECT * FROM inventory WHERE owner_id = ? AND dressed_slot = 0 AND on_sale = 0', $user->getId());
|
||||
$iteminfo = [];
|
||||
foreach ($data as $row) {
|
||||
$iteminfo[] = new InventoryItem($row);
|
||||
$iteminfo = new InventoryItem($row);
|
||||
}
|
||||
|
||||
//Обработчики нажатий на кнопки.
|
||||
@ -264,7 +267,8 @@ Template::header('Игра');
|
||||
</script>
|
||||
<div id=hint3 class=ahint></div>
|
||||
<div id="chpassbank" style="display:none; position:absolute; top:50px; left:250px;"></div>
|
||||
<table style="width: 100%">
|
||||
<?php $userInfo->showUserInfoMain()?>
|
||||
<table style="width: 100%;filter: sepia(1);background: white;">
|
||||
<TR>
|
||||
<td style="vertical-align: top; width: 350px">
|
||||
<?php $userInfo->showUserDoll(0, 1); ?> <!-- Первый столбец -->
|
||||
|
369
shop.php
369
shop.php
@ -1,7 +1,9 @@
|
||||
<?php
|
||||
|
||||
use Battles\Bank;
|
||||
use Battles\Database\DBPDO;
|
||||
use Battles\GameLogs;
|
||||
use Battles\Item;
|
||||
use Battles\ShopItem;
|
||||
use Battles\Template;
|
||||
use Battles\User;
|
||||
@ -11,287 +13,148 @@ session_start();
|
||||
require_once 'functions.php';
|
||||
$user = $user ?? new User($_SESSION['uid']);
|
||||
$db = new DBPDO();
|
||||
/*
|
||||
* aheroshop.php
|
||||
* $data = db::c()->query('SELECT * FROM `ahero_shop` WHERE `count` > 0 AND `razdel` = ?i ORDER by `point` ASC', $_GET['otdel']);
|
||||
* db::c()->query('UPDATE `shop` SET `count` = `count`- ?i WHERE `id` = ?i', $_POST['count'], $set);
|
||||
* db::c()->query('UPDATE `users` set `doblest` = `doblest` - ?i * ?i WHERE id = ?i', $_POST['count'], $dress['point'], $user['id']);
|
||||
*
|
||||
* shop_luka.php
|
||||
* $data = mysql_query("SELECT * FROM `shop` WHERE `count` > 0 AND `razdel` = '{$_GET['otdel']}' AND `zeton` != '0' ORDER by `cost` ASC");
|
||||
* $vsego = $zetons-$_POST['count']*$dress['zeton'];
|
||||
* if($vsego<='0'){
|
||||
* mysql_query("DELETE FROM `inventory` WHERE `type`='200' and `name`='Жетон' and owner='".$user["id"]."'");
|
||||
* }else{mysql_query("UPDATE `inventory` set `maxdur` = '$vsego' WHERE `type`='200' and `name`='Жетон' and owner='".$user["id"]."'");}
|
||||
* */
|
||||
|
||||
|
||||
$saleItems = false;
|
||||
$shopCategoryType = $_POST['sale'] ?? '';
|
||||
$shopCategoryTypeNumber = $_GET['otdel'] ?? 0;
|
||||
$status = null;
|
||||
|
||||
if (!empty($_POST['sellshop'])) {
|
||||
$status = ShopItem::sellItem($_POST['itemId'], $user, 1);
|
||||
}
|
||||
|
||||
if (!empty($_POST['buyshop'])) {
|
||||
$status = ShopItem::buyItem($_POST['itemId'], $user);
|
||||
}
|
||||
|
||||
$bank = new Bank($user->getId());
|
||||
|
||||
switch ($shopCategoryTypeNumber) {
|
||||
default:
|
||||
$shopCategoryType = "Все товары";
|
||||
break;
|
||||
case Item::ITEM_TYPE_HELMET:
|
||||
$shopCategoryType = "Шлемы";
|
||||
break;
|
||||
case Item::ITEM_TYPE_ARMOR:
|
||||
$shopCategoryType = "Броня";
|
||||
break;
|
||||
case Item::ITEM_TYPE_LEGS:
|
||||
$shopCategoryType = "Поножи";
|
||||
break;
|
||||
case Item::ITEM_TYPE_BOOTS:
|
||||
$shopCategoryType = "Сапоги";
|
||||
break;
|
||||
case Item::ITEM_TYPE_GLOVES:
|
||||
$shopCategoryType = "Перчатки";
|
||||
break;
|
||||
case Item::ITEM_TYPE_WEAPON:
|
||||
$shopCategoryType = "Оружие";
|
||||
break;
|
||||
case Item::ITEM_TYPE_SHIELD:
|
||||
$shopCategoryType = "Щиты";
|
||||
break;
|
||||
case Item::ITEM_TYPE_BELT:
|
||||
$shopCategoryType = "Пояса";
|
||||
break;
|
||||
case Item::ITEM_TYPE_RING:
|
||||
$shopCategoryType = "Кольца";
|
||||
break;
|
||||
case Item::ITEM_TYPE_AMULET:
|
||||
$shopCategoryType = "Амулеты";
|
||||
break;
|
||||
case Item::ITEM_TYPE_CONSUMABLE:
|
||||
$shopCategoryType = "Расходники";
|
||||
break;
|
||||
case Item::ITEM_TYPE_OTHER:
|
||||
$shopCategoryType = "Разное";
|
||||
break;
|
||||
case 'sale':
|
||||
$shopCategoryType = "Предметы в инвентаре";
|
||||
$saleItems = true;
|
||||
break;
|
||||
case 1:
|
||||
$shopCategoryType = "Кинжалы";
|
||||
break;
|
||||
case 11:
|
||||
$shopCategoryType = "Топоры";
|
||||
break;
|
||||
case 12:
|
||||
$shopCategoryType = "Дубины";
|
||||
break;
|
||||
case 13:
|
||||
$shopCategoryType = "Мечи";
|
||||
break;
|
||||
case 2:
|
||||
$shopCategoryType = "Сапоги";
|
||||
break;
|
||||
case 21:
|
||||
$shopCategoryType = "Перчатки";
|
||||
break;
|
||||
case 22:
|
||||
$shopCategoryType = "Легкая броня";
|
||||
break;
|
||||
case 23:
|
||||
$shopCategoryType = "Тяжелая броня";
|
||||
break;
|
||||
case 24:
|
||||
$shopCategoryType = "Шлемы";
|
||||
break;
|
||||
case 3:
|
||||
$shopCategoryType = "Щиты";
|
||||
break;
|
||||
case 4:
|
||||
$shopCategoryType = "Серьги";
|
||||
break;
|
||||
case 41:
|
||||
$shopCategoryType = "Ожерелья";
|
||||
break;
|
||||
case 42:
|
||||
$shopCategoryType = "Кольца";
|
||||
break;
|
||||
case 5:
|
||||
$shopCategoryType = "Заклинания: нейтральные";
|
||||
break;
|
||||
case 51:
|
||||
$shopCategoryType = "Заклинания: боевые и защитные";
|
||||
break;
|
||||
case 6:
|
||||
$shopCategoryType = "Амуниция";
|
||||
break;
|
||||
}
|
||||
|
||||
// MUST BE ARRAY!
|
||||
$iteminfo = [];
|
||||
if (!$saleItems) {
|
||||
$shopItems = db::c()->query('SELECT `shop`.*,
|
||||
`magic`.`name` AS `magic_name`,
|
||||
`magic`.`chanse` AS `magic_chanse`,
|
||||
`magic`.`time` AS `magic_time`,
|
||||
`magic`.`file` AS `magic_file`,
|
||||
`magic`.`targeted` AS `magic_targeted`,
|
||||
`magic`.`needcharge` AS `magic_needcharge`,
|
||||
`magic`.`img` AS `magic_img`
|
||||
|
||||
FROM `shop` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE `count` > 0 AND `cost` > 0 AND `razdel` = ?i ORDER by `nlevel` ASC, `id` ASC', $shopCategoryTypeNumber);
|
||||
|
||||
$iteminfo = [];
|
||||
while ($row = $shopItems->fetch_assoc()) {
|
||||
$iteminfo[] = new ShopItem($row);
|
||||
$shopItems = $db->ofetchAll("select * from items inner join trade_offers on id = shop_item_id where shop_id = 1 and shop_item_quantity !=0");
|
||||
foreach ($shopItems as $shopItemObject) {
|
||||
$iteminfo[] = new ShopItem($shopItemObject, 'buyshop');
|
||||
}
|
||||
} else {
|
||||
$inventoryItems = db::c()->query('SELECT `inventory`.*,
|
||||
`magic`.`name` AS `magic_name`,
|
||||
`magic`.`chanse` AS `magic_chanse`,
|
||||
`magic`.`time` AS `magic_time`,
|
||||
`magic`.`file` AS `magic_file`,
|
||||
`magic`.`targeted` AS `magic_targeted`,
|
||||
`magic`.`needcharge` AS `magic_needcharge`,
|
||||
`magic`.`img` AS `magic_img`,
|
||||
0 AS `maxdur`
|
||||
|
||||
FROM `inventory` LEFT JOIN `magic` ON `magic` = `magic`.`id` WHERE
|
||||
`dressed` = 0 AND `setsale` = 0 AND `cost` > 0 AND `present` = "?s" AND
|
||||
`tradesale` = 0 AND `podzem` = 0 AND `goden` = 0 AND `artefact` = 0 AND `owner` = ?i
|
||||
ORDER BY `update` DESC', null, $_SESSION['uid']);
|
||||
|
||||
$iteminfo = [];
|
||||
while ($row = $inventoryItems->fetch_assoc()) {
|
||||
$iteminfo[] = new ShopItem($row);
|
||||
$inventoryItems = $db->ofetchall("select * from inventory where on_sale = 0 and dressed_slot = 0 and durability > 0 and owner_id = ?", $user->getId());
|
||||
foreach ($inventoryItems as $inventoryItemObject) {
|
||||
$iteminfo[] = new ShopItem($inventoryItemObject, 'sellshop');
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
$sellItemId = $_GET['sell'] ?? 0;
|
||||
|
||||
if ($sellItemId) {
|
||||
ShopItem::sellItem($sellItemId, $user);
|
||||
}
|
||||
|
||||
if (!empty($_GET['buy'])) {
|
||||
ShopItem::buyItem($_GET['buy'], $user);
|
||||
/* $dress = db::c()->query('SELECT * FROM `shop` WHERE `id`=?i', $_GET['buy'])->fetch_assoc();
|
||||
$itemWeight = db::c()->query('SELECT sum(`massa`) AS `m` FROM `inventory` WHERE `owner` = ?i AND `setsale` = 0', $_SESSION['uid'])->fetch_assoc();
|
||||
|
||||
if (($dress['massa'] + $itemWeight['m']) > (get_meshok())) {
|
||||
$status = 'Недостаточно места в рюкзаке.';
|
||||
}
|
||||
elseif ($user['money'] >= $dress['cost'] && ($dress['count'] > 0 || $dress['count'] == -1)) {
|
||||
$newItem = [
|
||||
'prototype' => $dress['id'],
|
||||
'owner' => $user['id'],
|
||||
'name' => $dress['name'], //s
|
||||
'type' => $dress['type'],
|
||||
'massa' => $dress['massa'],
|
||||
'cost' => $dress['cost'],
|
||||
'img' => $dress['img'], //s
|
||||
'maxdur' => $dress['maxdur'],
|
||||
'isrep' => $dress['isrep'],
|
||||
'gsila' => $dress['gsila'],
|
||||
'glovk' => $dress['glovk'],
|
||||
'ginta' => $dress['ginta'],
|
||||
'gintel' => $dress['gintel'],
|
||||
|
||||
'ghp' => $dress['ghp'],
|
||||
'gnoj' => $dress['gnoj'],
|
||||
'gtopor' => $dress['gtopor'],
|
||||
'gdubina' => $dress['gdubina'],
|
||||
'gmech' => $dress['gmech'],
|
||||
'gfire' => $dress['gfire'],
|
||||
'gwater' => $dress['gwater'],
|
||||
'gair' => $dress['gair'],
|
||||
'gearth' => $dress['gearth'],
|
||||
'glight' => $dress['glight'],
|
||||
'ggray' => $dress['ggray'],
|
||||
'gdark' => $dress['gdark'],
|
||||
|
||||
'needident' => $dress['needident'],
|
||||
'nsila' => $dress['nsila'],
|
||||
'nlovk' => $dress['nlovk'],
|
||||
'ninta' => $dress['ninta'],
|
||||
'nintel' => $dress['nintel'],
|
||||
'nmudra' => $dress['nmudra'],
|
||||
'nvinos' => $dress['nvinos'],
|
||||
'nnoj' => $dress['nnoj'],
|
||||
'ntopor' => $dress['ntopor'],
|
||||
'ndubina' => $dress['ndubina'],
|
||||
'nmech' => $dress['nmech'],
|
||||
|
||||
'nfire' => $dress['nfire'],
|
||||
'nwater' => $dress['nwater'],
|
||||
'nair' => $dress['nair'],
|
||||
'nearth' => $dress['nearth'],
|
||||
'nlight' => $dress['nlight'],
|
||||
'ngray' => $dress['ngray'],
|
||||
'ndark' => $dress['ndark'],
|
||||
'mfkrit' => $dress['mfkrit'],
|
||||
'mfakrit' => $dress['mfakrit'],
|
||||
'mfuvorot' => $dress['mfuvorot'],
|
||||
'mfauvorot' => $dress['mfauvorot'],
|
||||
|
||||
'bron1' => $dress['bron1'],
|
||||
'bron2' => $dress['bron2'],
|
||||
'bron3' => $dress['bron3'],
|
||||
'bron4' => $dress['bron4'],
|
||||
'minu' => $dress['minu'],
|
||||
'maxu' => $dress['maxu'],
|
||||
'magic' => $dress['magic'],
|
||||
'nlevel' => $dress['nlevel'],
|
||||
'nalign' => $dress['nalign'],
|
||||
'dategoden' => $dress['dategoden'],
|
||||
'goden' => $dress['goden'],
|
||||
'gmp' => $dress['gmp'],
|
||||
'artefact' => $dress['artefact'],
|
||||
'koll' => $dress['koll'],
|
||||
];
|
||||
|
||||
db::c()->query('INSERT INTO `inventory` SET ?A[?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,?i,?i,?i]', $newItem);
|
||||
$inventoryItemId = db::c()->getLastInsertId();
|
||||
if ($dress['count'] != -1) {
|
||||
db::c()->query('UPDATE `shop` SET `count` = `count` - 1 WHERE `id` = ?i', $_GET['buy']);
|
||||
}
|
||||
$status = "Вы купили «{$dress['name']}» за {$dress['cost']} кр.";
|
||||
db::c()->query('UPDATE `users` set `money` = `money` - ?i WHERE `id` = ?i', $dress['cost'], $_SESSION['uid']);
|
||||
$deloText = "{$user->getLogin()} купил товар «{$dress['name']}» id:({$inventoryItemId}) в магазине за {$dress['cost']} кр.";
|
||||
GameLogs::addUserLog($user->getId(), $deloText);
|
||||
// Для обновления данных о деньгах на странице
|
||||
$user['money'] -= $dress['cost'];
|
||||
|
||||
} else {
|
||||
$status = "Недостаточно денег или нет вещей в наличии.";
|
||||
}*/
|
||||
}
|
||||
Template::header('Магазин');
|
||||
?>
|
||||
<script src="js/main.js"></script>
|
||||
<script src="js/main.js"></script>
|
||||
<style>
|
||||
a.waretype {
|
||||
margin: 2px 16px;
|
||||
padding: 6px;
|
||||
border: 1px silver solid;
|
||||
border-radius: 4px;
|
||||
background-color: #ccc;
|
||||
display: block;
|
||||
}
|
||||
a.sell {
|
||||
background-color: #cdc;
|
||||
}
|
||||
a.alltypes {
|
||||
background-color: #ccd;
|
||||
}
|
||||
.status {
|
||||
color:darkgreen;
|
||||
background:#afa;
|
||||
}
|
||||
</style>
|
||||
<h1>Государственный магазин</h1>
|
||||
<a href=# onclick=hrefToFrame('city.php?cp')> ← выйти на Центральную площадь</a>
|
||||
<div><?php if (!empty($status)) err($status); ?></div>
|
||||
<TABLE width=100% cellspacing="0" cellpadding="4">
|
||||
<TR>
|
||||
<TD valign=top align=left>
|
||||
<div class="status"><?= $status ?></div>
|
||||
<table style="width: 100%; border-collapse: collapse; border-spacing: 0; padding: 4px;">
|
||||
<tr>
|
||||
<td style="vertical-align: top; text-align: left;">
|
||||
<h3><?= $shopCategoryType ?></h3>
|
||||
<?php if ($saleItems): ?>
|
||||
<div style="text-align: center;">Вы можете продать ваши предметы за сущие копейки.</div>
|
||||
<?php endif; ?>
|
||||
<!--Магазин-->
|
||||
<TABLE class="zebra" WIDTH=100% CELLSPACING="1" CELLPADDING="2">
|
||||
<table class="zebra" style="width: 100%; border-collapse: separate; border-spacing: 1px; padding: 2px;">
|
||||
<?php
|
||||
if ($saleItems == true) {
|
||||
foreach ($iteminfo as $ii) {
|
||||
echo "<tr><td style='width: 150px; text-align: center;'>";
|
||||
$ii->printImage();
|
||||
$ii->printControls('sell');
|
||||
echo "</td>";
|
||||
echo "<td style='vertical-align: top;'>";
|
||||
$ii->printInfo();
|
||||
echo "</td></tr>";
|
||||
}
|
||||
} else {
|
||||
foreach ($iteminfo as $ii) {
|
||||
echo "<tr><td style='width: 150px; text-align: center;'>";
|
||||
$ii->printImage();
|
||||
$ii->printControls();
|
||||
echo "</td>";
|
||||
echo "<td style='vertical-align: top;'>";
|
||||
$ii->printInfo();
|
||||
echo "</td></tr>";
|
||||
foreach ($iteminfo as $ii) {
|
||||
if ($ii->getItemType() != $shopCategoryTypeNumber && $shopCategoryTypeNumber != 'sale') {
|
||||
continue;
|
||||
}
|
||||
echo "<tr><td style='width: 150px; text-align: center; padding: 5px;'>";
|
||||
echo $ii->printImage();
|
||||
$ii->printControls();
|
||||
echo "<td style='vertical-align: top; padding: 5px;'>";
|
||||
$ii->printInfo();
|
||||
}
|
||||
?>
|
||||
</TABLE>
|
||||
</TD>
|
||||
<TD valign=top width=280>
|
||||
<B>Масса всех ваших вещей: <?= getItemsMassaInfo() ?>
|
||||
<BR>У вас в наличии: <span style="color: darkgreen;"><?= $user['money'] ?></span> кр.</B>
|
||||
</table>
|
||||
<td style="width: 280px; vertical-align: top;">
|
||||
<strong>
|
||||
Масса всех ваших вещей: <?= getItemsMassaInfo() ?> <br>
|
||||
У вас в банке: <span style="color: darkgreen;"><?= $bank->getMoney() ?></span> банкнот.
|
||||
</strong>
|
||||
<hr>
|
||||
<div style="text-align: center; font-weight: bold;">Отделы магазина</div>
|
||||
<a href="shop.php?otdel=sale&rnd=<?= mt_rand() ?>">Продать вещи</a>
|
||||
<dl>
|
||||
<dt><b>Оружие:</b></dt>
|
||||
<dd><a href="?otdel=1&rnd=<?= mt_rand() ?>">кинжалы</a></dd>
|
||||
<dd><a href="?otdel=11&rnd=<?= mt_rand() ?>">топоры</a></dd>
|
||||
<dd><a href="?otdel=12&rnd=<?= mt_rand() ?>">дубины</a></dd>
|
||||
<dd><a href="?otdel=13&rnd=<?= mt_rand() ?>">мечи</a></dd>
|
||||
<dt><b>Одежда:</b></dt>
|
||||
<dd><a href="?otdel=24&rnd=<?= mt_rand() ?>">шлемы</a></dd>
|
||||
<dd><a href="?otdel=23&rnd=<?= mt_rand() ?>">тяжелая броня</a></dd>
|
||||
<dd><a href="?otdel=22&rnd=<?= mt_rand() ?>">легкая броня</a></dd>
|
||||
<dd><a href="?otdel=3&rnd=<?= mt_rand() ?>">щиты</a></dd>
|
||||
<dd><a href="?otdel=21&rnd=<?= mt_rand() ?>">перчатки</a></dd>
|
||||
<dd><a href="?otdel=2&rnd=<?= mt_rand() ?>">сапоги</a></dd>
|
||||
<dt><b>Ювелирные товары:</b></dt>
|
||||
<dd><a href="?otdel=4&rnd=<?= mt_rand() ?>">серьги</a></dd>
|
||||
<dd><a href="?otdel=41&rnd=<?= mt_rand() ?>">ожерелья</a></dd>
|
||||
<dd><a href="?otdel=42&rnd=<?= mt_rand() ?>">кольца</a></dd>
|
||||
<dt><b>Магия:</b></dt>
|
||||
<dd><a href="?otdel=51&rnd=<?= mt_rand() ?>">боевые</a></dd>
|
||||
<dd><a href="?otdel=5&rnd=<?= mt_rand() ?>">разные</a></dd>
|
||||
<dt><b>Разное:</b></dt>
|
||||
<dd><a href="?otdel=6&rnd=<?= mt_rand() ?>">амуниция</a></dd>
|
||||
</dl>
|
||||
<a class="waretype" href="?otdel=6&rnd=<?= mt_rand() ?>">Оружие</a>
|
||||
<a class="waretype" href="?otdel=1&rnd=<?= mt_rand() ?>">Шлемы</a>
|
||||
<a class="waretype" href="?otdel=2&rnd=<?= mt_rand() ?>">Броня</a>
|
||||
<a class="waretype" href="?otdel=3&rnd=<?= mt_rand() ?>">Поножи</a>
|
||||
<a class="waretype" href="?otdel=4&rnd=<?= mt_rand() ?>">Сапоги</a>
|
||||
<a class="waretype" href="?otdel=5&rnd=<?= mt_rand() ?>">Перчатки</a>
|
||||
<a class="waretype" href="?otdel=7&rnd=<?= mt_rand() ?>">Щиты</a>
|
||||
<a class="waretype" href="?otdel=8&rnd=<?= mt_rand() ?>">Пояса</a>
|
||||
<a class="waretype" href="?otdel=9&rnd=<?= mt_rand() ?>">Кольца</a>
|
||||
<a class="waretype" href="?otdel=10&rnd=<?= mt_rand() ?>">Амулеты</a>
|
||||
<a class="waretype" href="?otdel=20&rnd=<?= mt_rand() ?>">Расходники</a>
|
||||
<a class="waretype" href="?otdel=50&rnd=<?= mt_rand() ?>">Разное</a>
|
||||
<a class="waretype alltypes" href="?rnd=<?= mt_rand() ?>">Все товары</a>
|
||||
<a class="waretype sell" href="?otdel=sale&rnd=<?= mt_rand() ?>">Продать вещи</a>
|
||||
<div id="hint3" class="ahint"></div>
|
||||
</TD>
|
||||
</TR>
|
||||
</TABLE>
|
||||
</table>
|
Loading…
Reference in New Issue
Block a user