'Сдать в магазин', 'unsetmarket' => 'Снять с продажи', 'buymarket' => 'Совершить обмен', 'sellshop' => 'Продать', 'buyshop' => 'Купить', ]; private const BUY_QUERY = <<optype = $operationType; } $this->price = $row->price ?? null; $this->shop_item_quantity = $row->shop_item_quantity ?? null; $this->item_id = $row->item_id ?? $row->id; } public function printInfo() { $this->printAllInfo(); if ($this->optype === 'buyshop' && $this->shop_item_quantity > 0 && $this->shop_item_quantity < 20) { echo "
На складе осталось $this->shop_item_quantity единиц товара!
"; } 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 "
В среднем за $goods можно выручить {$this->getSellPriceMean()} кр.
"; } } public function printImage() { if (!$this->image) { $this->image = 'noitem.png'; } echo ""; } //todo наличка после покупки отображается с задержкой. public static function buyItem($id, User $buyer): string { $db = new DBPDO(); $check = $db->ofetch("select * from trade_offers where shop_item_id = ?", $id); 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(), $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)) { return 'Запрос в базу не прошёл.'; } else { $user = new User($_SESSION['uid']); // Если не хватает налички, снимаем с банка с комиссией. if ($user->getMoney() < $item->price) { try { $bank = new Bank($buyer->getId()); $bank->withdrawMoney($item->price); } catch (GameException $e) { echo 'Банковская ошибка!'; return self::NO_MONEY; } } else { $user->setMoney($user->getMoney() - $item->price); $user->saveMoney(); } } 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() . " купил товар «" . $item->name . "» id:(" . $item->item_id . ") в магазине за " . $item->price . "."; GameLogs::addUserLog($buyer->getId(), $deloText); return "Предмет " . $item->name . " куплен за " . $item->price . "."; } 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 = $item->price > 1 ? mt_rand(0, $item->price / 2) : mt_rand(0, 1); $db->execute('delete from inventory where item_id = ?', $id); if ($bankTrade) { $bank = new Bank($seller->getId()); $bank->setMoney($bank->getMoney() + $sellingPrice); Bank::setBankMoney($bank->getMoney(), $seller->getId(), 'sellShop'); } else { $db->execute('update users set money = money - ? where id = ?', [$sellingPrice, $_SESSION['uid']]); } $deloText = "{$seller->getLogin()} продал товар «{$sellingItemName}» id:($id) в магазине за $sellingPrice кр."; GameLogs::addUserLog($seller->getId(), $deloText); if ($sellingPrice == 0) { $status = "После длительных и изнурительных торгов вы плюнули на всё и просто подарили ваш «{$sellingItemName}» торговцу."; } else { $status = "Вы продали «{$sellingItemName}» за $sellingPrice кр."; } return $status; } /** Подчсчёт средней суммы продажи. * @return int */ private function getSellPriceMean(): ?int { if ($this->price > 1) { $arr = range(0, $this->price / 2); return array_sum($arr) / count($arr); } else { return $this->price == 1 ? 1 : null; } } /** * Для кнопок управления под картинкой предмета в зависимости от ситуации. */ public function printControls() { if (in_array($this->optype, ['setmarket', 'unsetmarket', 'buymarket', 'sellshop', 'buyshop',])) { $str = $this->optype == 'setmarket' ? '' : ''; $button_name = self::BUTTON[$this->optype]; echo <<
$str
FORM; } } /** * @return int */ public function getItemType(): int { return $this->item_type; } }