Code smell.

This commit is contained in:
Ivor Barhansky 2022-12-17 01:20:43 +02:00
parent b1f578f4b0
commit 0398425205
45 changed files with 875 additions and 851 deletions

View File

@ -15,86 +15,142 @@ if (isset($_POST)) {
<tr>
<th id="main">Основное
<tr>
<td><input name="name" placeholder="Название">
<td><label>
<input name="name" placeholder="Название">
</label>
<tr>
<td><input name="image" placeholder="Картинка">
<td><label>
<input name="image" placeholder="Картинка">
</label>
<tr>
<td><select name="shop">
<option value="0" selected disabled>Тип магазина</option>
<option value="1">Обычный</option>
<option value="2">Цветной</option>
</select>
<td><label>
<select name="shop">
<option value="0" selected disabled>Тип магазина</option>
<option value="1">Обычный</option>
<option value="2">Цветной</option>
</select>
</label>
<tr>
<td><input name=count placeholder="Количество (шт.)" disabled>
<td><label>
<input name=count placeholder="Количество (шт.)" disabled>
</label>
<tr>
<td><select name="item_type">
<option value="0" selected disabled>Тип предмета</option>
<option value="1">Шлем</option>
<option value="2">Броня</option>
<option value="3">Поножи</option>
<option value="4">Сапоги</option>
<option value="5">Перчатки</option>
<option value="6">Оружие</option>
<option value="7">Щит</option>
<option value="8">Пояс</option>
<option value="9">Кольцо</option>
<option value="10">Амулет</option>
<option value="20">Расходник</option>
<option value="50">Всё остальное</option>
<option value="100">Хлам</option>
</select>
<td><label>
<select name="item_type">
<option value="0" selected disabled>Тип предмета</option>
<option value="1">Шлем</option>
<option value="2">Броня</option>
<option value="3">Поножи</option>
<option value="4">Сапоги</option>
<option value="5">Перчатки</option>
<option value="6">Оружие</option>
<option value="7">Щит</option>
<option value="8">Пояс</option>
<option value="9">Кольцо</option>
<option value="10">Амулет</option>
<option value="20">Расходник</option>
<option value="50">Всё остальное</option>
<option value="100">Хлам</option>
</select>
</label>
<tr>
<td><input name=weight placeholder="Масса">
<td><label>
<input name=weight placeholder="Масса">
</label>
<tr>
<td><input name=durability placeholder="Макс. износ">
<td><label>
<input name=durability placeholder="Макс. износ">
</label>
<tr>
<td><input name=price placeholder="Цена (кр.)" disabled>
<td><label>
<input name=price placeholder="Цена (кр.)" disabled>
</label>
<tr>
<th id="needs">Требования
<tr>
<td><input name=need_level placeholder="Уровень">
<td><label>
<input name=need_level placeholder="Уровень">
</label>
<tr>
<td><input name=need_strength placeholder="Сила">
<td><label>
<input name=need_strength placeholder="Сила">
</label>
<tr>
<td><input name=need_dexterity placeholder="Ловкость">
<td><label>
<input name=need_dexterity placeholder="Ловкость">
</label>
<tr>
<td><input name=need_intuition placeholder="Интуиция">
<td><label>
<input name=need_intuition placeholder="Интуиция">
</label>
<tr>
<td><input name=need_endurance placeholder="Выносливость">
<td><label>
<input name=need_endurance placeholder="Выносливость">
</label>
<tr>
<td><input name=need_intelligence placeholder="Интеллект">
<td><label>
<input name=need_intelligence placeholder="Интеллект">
</label>
<tr>
<td><input name=need_wisdom placeholder="Мудрость">
<td><label>
<input name=need_wisdom placeholder="Мудрость">
</label>
<tr>
<th id="adds">Характеристики
<tr>
<td><input name=minu placeholder="Мин.урон">
<td><label>
<input name=minu placeholder="Мин.урон">
</label>
<tr>
<td><input name=maxu placeholder="Макс.урон">
<td><label>
<input name=maxu placeholder="Макс.урон">
</label>
<tr>
<td><input name=add_strength placeholder="Сила">
<td><label>
<input name=add_strength placeholder="Сила">
</label>
<tr>
<td><input name=add_dexterity placeholder="Ловкость">
<td><label>
<input name=add_dexterity placeholder="Ловкость">
</label>
<tr>
<td><input name=add_intuition placeholder="Интуиция">
<td><label>
<input name=add_intuition placeholder="Интуиция">
</label>
<tr>
<td><input name=add_endurance placeholder="Выносливость">
<td><label>
<input name=add_endurance placeholder="Выносливость">
</label>
<tr>
<td><input name=add_intelligence placeholder="Интеллект">
<td><label>
<input name=add_intelligence placeholder="Интеллект">
</label>
<tr>
<td><input name=add_wisdom placeholder="Мудрость">
<td><label>
<input name=add_wisdom placeholder="Мудрость">
</label>
<tr>
<td><input name=add_accuracy placeholder="Точность">
<td><label>
<input name=add_accuracy placeholder="Точность">
</label>
<tr>
<td><input name=add_evasion placeholder="Уворот">
<td><label>
<input name=add_evasion placeholder="Уворот">
</label>
<tr>
<td><input name=add_criticals placeholder="Крит">
<td><label>
<input name=add_criticals placeholder="Крит">
</label>
<tr>
<td><input name=add_min_physical_damage placeholder="Мин.удар">
<td><label>
<input name=add_min_physical_damage placeholder="Мин.удар">
</label>
<tr>
<td><input name=add_min_physical_damage placeholder="Макс.удар">
<td><label>
<input name=add_min_physical_damage placeholder="Макс.удар">
</label>
</table>
<INPUT TYPE="submit" value="Добавить">
</div>
</form>
</form>

View File

@ -123,4 +123,4 @@ Template::header('ᐰdminка');
</form>
<span class="legend">Невидимки</span><br>
<div class="abils" style="width: fit-content; font-weight: bold;"><?= AUser::getInvisiblesList() ?></div>
<div class="abils" style="width: fit-content; font-weight: bold;"><?= AUser::getInvisiblesList() ?></div>

View File

@ -20,6 +20,7 @@ $player = $_POST['player'] ?? null;
$undress_char = $_POST['undress_char'] ?? null;
$end = $_POST['end'] ?? null;
$del = $_POST['del'] ?? null;
$inv = [];
if ($player) {
$row = Db::getInstance()->ofetch('select id, login from users where id = ? or login = ?', [$player, $player]);
@ -35,10 +36,10 @@ if ($end) {
unset($_SESSION['player_name']);
}
if (isset($_SESSION['player_id'])) {
$inv = db::c()->query('SELECT item_id, name, image FROM inventory WHERE owner = ?i ORDER BY id DESC', $_SESSION['player_id']);
$inv = Db::getInstance()->fetchAll('SELECT item_id, name, image FROM inventory WHERE owner_id = ? ORDER BY item_id DESC', $_SESSION['player_id']);
}
if ($del) {
$itemdel = db::c()->query('SELECT item_type, dressed_slot FROM inventory WHERE id=?i', $del)->fetch_assoc();
$itemdel = Db::getInstance()->fetch('SELECT item_type, dressed_slot FROM inventory WHERE item_id = ?', $del);
if ($itemdel['dressed_slot'] == 1) {
$item = new DressedItems($del);
$item->undressItem($itemdel['item_type']);
@ -47,34 +48,36 @@ if ($del) {
$item->undressItem(7);
}
}
Db::getInstance()->execute('delete from inventory where id = ?', $del);
Db::getInstance()->execute('delete from inventory where item_id = ?', $del);
}
Template::header('ᐰdminка инвентаря');
?>
<h1>Администрирование инвентаря <?php if (isset($_SESSION['player_name'])) echo $_SESSION['player_name']; ?></h1>
<h1>Администрирование инвентаря <?php if (isset($_SESSION['player_name'])) { echo $_SESSION['player_name']; } ?></h1>
<table class='adm'>
<tr>
<th>ID</th>
<th>Название</th>
<th>Количество</th>
<th>Картинка</th>
<th></th>
<th scope="col">ID</th>
<th scope="col">Название</th>
<th scope="col">Количество</th>
<th scope="col">Картинка</th>
<th scope="col"></th>
</tr>
<?php if (empty($_SESSION['player_id'])): ?>
<tr>
<th colspan="5">
<th scope="col" colspan="5">
<form method="post">
<input placeholder="Логин или ID" name="player">
<label>
<input placeholder="Логин или ID" name="player">
</label>
<input type="submit">
</form>
</th>
</tr>
<?php else: while ($row = $inv->fetch_assoc()): ?>
<?php else: foreach ($inv as $row): ?>
<tr>
<td><?= $row['id'] ?></td>
<td><?= $row['name'] ?></td>
<td><?= $row['koll'] ?></td>
<td><img src='/i/sh/<?= $row['img'] ?>'></td>
<td><img src='/i/sh/<?= $row['img'] ?>' alt=""></td>
<td>
<form method='post'>
<input name='del' type='hidden' value='<?= $row['id'] ?>'>
@ -82,7 +85,7 @@ Template::header('ᐰdminка инвентаря');
</form>
</td>
</tr>
<?php endwhile; ?>
<?php endforeach; ?>
<th colspan='6'>
<form method='post'>
<input name='undress_char' type='submit' value='Стриптиз'>
@ -92,4 +95,4 @@ Template::header('ᐰdminка инвентаря');
</form>
</th>
<?php endif; ?>
</table>
</table>

View File

@ -1,73 +0,0 @@
<?php
include "config.php";
//$user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '2106' LIMIT 1;"));
//include "functions.php";
//$komp_users = mysql_query("SELECT * FROM `users`,`online` WHERE `users`.`id`=`online`.`id` AND `online`.`date` >= ".(time()-60).";");
$komp_users = mysql_query("SELECT * FROM `users`;");
while($ku=mysql_fetch_array($komp_users))
{
$kompl_raw=mysql_query("SELECT * FROM inventory where owner=".$ku['id']." AND dressed=1");
$items_on_user=array();
$set_id_wear=array();
$kompl_har=0;
while ($kompl=mysql_fetch_array($kompl_raw))
{
$items_on_user[]=$kompl['prototype'];
}
$sets_raw=mysql_query("SELECT * FROM item_sets;");
while ($set_items=mysql_fetch_array($sets_raw))
{
$kompl_full=1;
$in_set=explode(',',$set_items['prot_id']);
foreach($in_set as $tmp_set)
if (!in_array($tmp_set,$items_on_user))
{$kompl_full=0;}
if ($kompl_full==1) $set_id_wear[]=$set_items['set_id'];
}
foreach($set_id_wear as $s)
{
$items_raw=mysql_fetch_array(mysql_query("SELECT * FROM item_sets where set_id='{$s}' limit 1;"));
$kompl_har+=$items_raw['gsila'];
$kompl_har+=$items_raw['glovk'];
$kompl_har+=$items_raw['gintel'];
$kompl_har+=$items_raw['ginta'];
}
if(!$kompl_har) $kompl_har=0;
$explim=0;
foreach(array_keys(EXPTABLE) as $k)
{
if($k>=$ku['exp'])
{
$explim=$k;
break;
}
}
$sum_stat=15;
foreach(array_keys(EXPTABLE) as $k)
{
if($k==$explim)
break;
else
{
$sum_stat+=EXPTABLE[$k][0];
$sum_stat+=EXPTABLE[$k][2];
}
}
$res=mysql_fetch_array(
mysql_query("SELECT IFNULL( (SUM( gsila ) + SUM( glovk ) + SUM( ginta ) + SUM( gintel )) , 0)+ {$kompl_har} + {$sum_stat}
FROM `inventory` WHERE `owner` = '{$ku['id']}' AND `dressed` = 1;"));
$res2=mysql_fetch_array(mysql_query("SELECT `sila`+`lovk`+`intel`+`inta`+`vinos`+`mudra`+`stats` FROM `users` WHERE `id`={$ku['id']};"));
if($res[0]!=$res2[0])
echo("<br/>".$kompl_har." _ ID=".$ku['id']."[".$ku['exp']."] : All=".$res2[0]."/norm=".$res[0]);
}

View File

@ -44,6 +44,6 @@ UNREGCLANLIST;
{
$bank = new Bank($id);
Db::getInstance()->execute('DELETE FROM clans WHERE status = 0 AND owner_id = ?', $id);
$bank::setBankMoney($bank->getMoney() + GameConfigs::CLAN['clan_register_cost'], $id);
$bank->modify(GameConfigs::CLAN['clan_register_cost']);
}
}
}

View File

@ -9,16 +9,16 @@ class Item
public static function add(array $params): void
{
$query = 'insert into items (
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)
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)
values (
: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,
: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)';
$values = [
'name' => $params['name'] ?? uniqid(),
@ -46,4 +46,4 @@ class Item
];
Db::getInstance()->execute($query, $values);
}
}
}

View File

@ -17,4 +17,4 @@ class User
}
return $list;
}
}
}

View File

@ -11,7 +11,7 @@ use Battles\Database\Db;
class Bank
{
private int $user_id = 0;
private int $userId = 0;
private int $money = 0;
private string $error = '';
private string $status = '';
@ -31,15 +31,15 @@ class Bank
'sellShop' => 'Продажа товара в магазине.'
];
public function __construct(int $user_id = null)
public function __construct(int $userId = null)
{
if (empty($user_id)) {
$user_id = User::getInstance()->getId();
if (empty($userId)) {
$userId = User::getInstance()->getId();
}
$bank_row = Db::getInstance()->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $user_id);
$bankRow = Db::getInstance()->fetch('SELECT user_id, money FROM bank WHERE user_id = ?', $userId);
foreach ($this as $key => $value) {
if (isset($bank_row[$key])) {
$this->$key = $bank_row[$key];
if (isset($bankRow[$key])) {
$this->$key = $bankRow[$key];
}
}
}
@ -61,20 +61,20 @@ class Bank
/**
* Пишем банковское событие в лог в БД
*
* @param int $receiverId ID получателя.
* @param int $amount сумма.
* @param int $receiverId ID получателя.
* @param int $amount сумма.
* @param string $operationType тип банковской операции.
* @param ?int $senderId ID отправителя (ID игрока, если не указано иное).
* @param ?int $senderId ID отправителя (ID игрока, если не указано иное).
*
* @return void
*/
private function addLog(int $receiverId, int $amount, string $operationType, ?int $senderId = null): void
{
if (is_null($senderId)) {
$senderId = $this->user_id;
$senderId = $this->userId;
}
if ($operationType === 'depositMoney' || $operationType === 'withdrawMoney') {
$receiverId = $this->user_id;
$receiverId = $this->userId;
}
$commText = $this->comission ? ' Комиссия: ' . $this->comission : '';
$text = self::LOG[$operationType] . $commText;
@ -86,7 +86,7 @@ class Bank
* Перевод денег между банковскими счетами игроков с банковской комиссией.
*
* @param mixed $receiver ID получателя.
* @param mixed $amount Cумма.
* @param mixed $amount Cумма.
*/
public function sendMoney($receiver, $amount)
{
@ -98,7 +98,7 @@ class Bank
if (!is_numeric($amount) || $amount <= 0) {
$this->error = self::ERROR_WRONG_AMOUNT;
}
if (!$rec->user_id) {
if (!$rec->userId) {
$this->error = self::ERROR_NO_BANK_ACCOUNT;
}
$amountWithComission = $amount + $this->commission($amount);
@ -110,10 +110,10 @@ class Bank
}
// Снимаем сумму с комиссией у отправителя
$this->modify(-$amountWithComission);
$this->addLog($rec->user_id, $this->money, 'sendMoney', $this->user_id);
$this->addLog($rec->userId, $this->money, 'sendMoney', $this->userId);
// Отдаём сумму на счёт получателю
$rec->modify($amount);
$rec->addLog($rec->user_id, $rec->money, 'receiveMoney', $this->user_id);
$rec->addLog($rec->userId, $rec->money, 'receiveMoney', $this->userId);
}
/**
@ -128,7 +128,7 @@ class Bank
$this->error = self::ERROR_WRONG_AMOUNT;
}
// Забираем деньги из кошелька получателя
if (!User::getInstance($this->user_id)->money()->spend($amount)) {
if (!User::getInstance($this->userId)->money()->spend($amount)) {
$this->error = self::ERROR_NO_MONEY_IN_WALLET;
}
if ($this->error) {
@ -161,12 +161,12 @@ class Bank
$this->modify(-$amountWithComission);
$this->addLog(0, $this->money, 'withdrawMoney');
// Отдаём сумму в кошелёк получателя
User::getInstance($this->user_id)->money()->earn($amount);
User::getInstance($this->userId)->money()->earn($amount);
}
private function save()
{
Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$this->money, $this->user_id]);
Db::getInstance()->execute('UPDATE bank SET money = ? WHERE user_id = ?', [$this->money, $this->userId]);
}
public function getMoney(): int

View File

@ -18,21 +18,21 @@ class Chat
public function getMessages(): ?string
{
$query = 'select
$query = 'select
msg,
msgdate,
type,
s.login as sender,
r.login as receiver,
s.id as sid,
r.id as rid
from chat
left join users s on s.id = chat.user_id
left join users r on r.id = chat.receiver_id
where
r.id = ?
or r.id is null
or s.id = ?
s.login as sender,
r.login as receiver,
s.id as sid,
r.id as rid
from chat
left join users s on s.id = chat.user_id
left join users r on r.id = chat.receiver_id
where
r.id = ?
or r.id is null
or s.id = ?
order by chat.id';
$chatrows = $this->db->ofetchALL($query, [User::getInstance()->getId(), User::getInstance()->getId()]);
$wrappedMessage = null;
@ -67,13 +67,14 @@ class Chat
$this->db->execute('insert into chat (user_id, msg) values (?,?)', [User::getInstance()->getId(), $msg]);
}
public static function sendSys(string $msg, ?int $receiver_id = null)
public static function sendSys(string $msg, ?int $receiverId = null)
{
Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiver_id, 'sys']);
}
public static function sendTelegraf(string $msg, int $receiver_id)
{
Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiver_id, 'sms']);
Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiverId, 'sys']);
}
}
public static function sendTelegraf(string $msg, int $receiverId)
{
Db::getInstance()->execute('insert into chat (user_id, msg, receiver_id, type) values (-1,?,?,?)', [$msg, $receiverId, 'sms']);
}
}

View File

@ -31,4 +31,4 @@ class Check
{
return Db::getInstance()->fetchColumn('select count(*) from users where id = ?', $id) > 0;
}
}
}

View File

@ -1,13 +1,16 @@
<?php
# Date: 26.10.2020 (17:56)
namespace Battles;
class City
{
use Rooms;
public static function showStreet(int $id)
{
echo '<div style="position:relative; display: inline-block;" id="ione">';
if ($id === 20) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/spring_cap_cp_day.jpg">' .
echo '<img alt="background" src="/i/city/spring_cap_cp_day.jpg">' .
self::showBuilding(1, "spring_cap_club", 30, 235, self::$roomNames[1]) .
self::showBuilding(2, "spring_cap_shop", 202, 171, self::$roomNames[22]) .
self::showBuilding(4, "spring_cap_rem", 202, 290, self::$roomNames[23]) .
@ -17,68 +20,61 @@ class City
self::showBuilding(9, "winter_cap_tree2", 215, 500, self::$roomNames[44]) .
self::showBuilding(13, "spring_cap_statue", 222, 365, self::$roomNames[24]) .
self::showBuilding(14, "winter_cap_statue", 210, 390, "Снеговик") .
self::showBuilding(222, "cap_arr_top", 180, 650, "Торговая улица") .
'</div>';
self::showBuilding(222, "cap_arr_top", 180, 650, "Торговая улица");
} elseif ($id === 21) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/spring_cap_strash_day.jpg">' .
echo '<img alt="background" src="/i/city/spring_cap_strash_day.jpg">' .
self::showBuilding(3, "cap_arr_right", 255, 708, "Ристалище") .
self::showBuilding(4, "cap_arr_left", 258, 21, self::$roomNames[20]) .
self::showBuilding(5, "spring_cap_bank", 180, 485, self::$roomNames[29]) .
self::showBuilding(13, "spring_cap_flowershop", 220, 613, self::$roomNames[34]) .
self::showBuilding(14, "spring_cap_registratura", 170, 113, self::$roomNames[30]) .
self::showBuilding(16, "spring_cap_tower", 5, 315, self::$roomNames[31]) .
'</div>';
self::showBuilding(16, "spring_cap_tower", 5, 315, self::$roomNames[31]);
} elseif ($id === 26) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/spring_cap_park_day.jpg">' .
echo '<img alt="background" src="/i/city/spring_cap_park_day.jpg">' .
self::showBuilding(3, "cap_arr_left", 259, 27, self::$roomNames[2601]) .
self::showBuilding(4, "cap_arr_right", 259, 715, self::$roomNames[20]) .
self::showBuilding(6, "cap_gate", 170, 340, "Городские ворота") .
self::showBuilding(660, "spring_cap_vokzal", 163, 43, self::$roomNames[661]) .
'</div>';
self::showBuilding(660, "spring_cap_vokzal", 163, 43, self::$roomNames[661]);
} elseif ($id === 2601) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/sub/cap_zamk_day.jpg">' .
echo '<img alt="background" src="/i/city/sub/cap_zamk_day.jpg">' .
self::showBuilding(1, "spring_cap_ruins", 166, 48, "Руины Старого замка") .
self::showBuilding(4, "cap_arr_right", 260, 710, self::$roomNames[26]) .
self::showBuilding(10, "ava_post", 240, 300, self::$roomNames[35]) .
self::showBuilding(55, "cap_arr_left", 258, 21, self::$roomNames[2655]) .
self::showBuilding(1051, "spring_cap_lab", 130, 327, self::$roomNames[33]) .
self::showBuilding(1052, "spring_cap_lavka", 240, 425, self::$roomNames[1053]) .
'</div>';
self::showBuilding(1052, "spring_cap_lavka", 240, 425, self::$roomNames[1053]);
} elseif ($id === 2655) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/ar_e_d.jpg">' .
echo '<img alt="background" src="/i/city/ar_e_d.jpg">' .
self::showBuilding(10, "arr_right_png2", 260, 710, self::$roomNames[2601]) .
self::showBuilding(2055, "altr_g", 230, 340, self::$roomNames[603]) .
'</div>';
self::showBuilding(2055, "altr_g", 230, 340, self::$roomNames[603]);
} elseif ($id === 2111) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/av_rist_day.jpg">' .
echo '<img alt="background" src="/i/city/av_rist_day.jpg">' .
self::showBuilding(1, "cap_arr_left", 240, 30, self::$roomNames[21]) .
self::showBuilding(14, "spring_cap_rist_solo", 210, 160, "Вход в Одиночные сражения") .
self::showBuilding(14, "spring_cap_rist_group", 243, 340, "Вход в Сражение отрядов") .
self::showBuilding(203, "spring_cap_rist_monstr", 145, 570, "Вход в Груповые сражения") .
self::showBuilding(1000, "av_zamk_rud", 80, 310, self::$roomNames[1001]) .
'</div>';
self::showBuilding(1000, "av_zamk_rud", 80, 310, self::$roomNames[1001]);
} elseif ($id === 2701) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/av_arena_bg1_day2.jpg">' .
echo '<img alt="background" src="/i/city/av_arena_bg1_day2.jpg">' .
self::showBuilding(1, "cap_3strelka", 260, 30, "Берег Залива") .
self::showBuilding(2, "cap_shar_dark", 234, 356, "Лабиринт Хаоса") .
'</div>';
self::showBuilding(2, "cap_shar_dark", 234, 356, "Лабиринт Хаоса");
} elseif ($id === 2702) {
echo '<div style="position:relative; display: inline-block;" id="ione"><img alt="background" src="/i/city/spring_cap_torg_day.jpg">' .
echo '<img alt="background" src="/i/city/spring_cap_torg_day.jpg">' .
self::showBuilding(6, "spring_cap_build1", 175, 70, "Академия") .
self::showBuilding(10, "cap_rist_arr_left", 259, 25, self::$roomNames[20]) .
self::showBuilding(16, "auk", 120, 300, "Аукцион") .
self::showBuilding(21, "spring_cap_build2", 150, 565, "Ломбард") .
self::showBuilding(16555, "spring_cap_build3", 155, 480, "Прокатная лавка") .
'</div>';
self::showBuilding(16555, "spring_cap_build3", 155, 480, "Прокатная лавка");
}
echo '</div>';
}
private static function showBuilding(int $id, string $image, int $top, int $left, string $description)
private static function showBuilding(int $id, string $image, int $top, int $left, string $description): string
{
return sprintf('
<div style="position:absolute; left:%spx; top:%spx; z-index:90; cursor: pointer;">
<img src="/i/city/sub/%s.png" alt="%s" title="%s" class="building" id="%s" onclick="window.location.href = \'city.php?got/level%s\'">
</div>',
$left, $top, $image, $description, $description, $id, $id);
return <<<HTML
<div style="position:absolute; left:{$left}px; top:{$top}px; z-index:90; cursor: pointer;">
<img src="/i/city/sub/$image.png" alt="$description" title="$description" class="building" id="$id" onclick="window.location.href = 'city.php?got/level$id'">
</div>
HTML;
}
}
}

View File

@ -7,7 +7,7 @@ use Battles\Models\User\Effects;
class Clan
{
private static ?self $_instance = null;
private static ?self $instance = null;
private $clan;
private function __construct()
@ -17,10 +17,10 @@ class Clan
public static function getInstance(): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$_instance;
return self::$instance;
}
public function addMember(string $login): string
@ -46,6 +46,11 @@ class Clan
return "Персонаж «{$login}» успешно принят в клан.";
}
private function getProverka($userId)
{
return Effects::count($userId, 20);
}
public function removeMember(string $login): string
{
$error = null;
@ -96,11 +101,6 @@ class Clan
return Db::getInstance()->fetchAll('select id, (select 1 from clans where short_name = clan and owner_id = id) as clan_owner, room from users where clan = ? order by clan_owner desc, room, login', User::getInstance()->getClan());
}
private function getProverka($user_id)
{
return Effects::count($user_id, 20);
}
public function getClanOwnerId(): ?int
{
return $this->clan->owner_id;
@ -115,4 +115,4 @@ class Clan
{
return $this->clan->short_name;
}
}
}

View File

@ -4,13 +4,14 @@ declare(strict_types=1);
namespace Battles\Database;
use Battles\GameConfigs;
use PDO, PDOException;
use PDO;
use PDOException;
class Db
{
private PDO $pdo;
private static ?self $_instance = null;
private static ?self $instance = null;
private function __construct()
{
@ -32,10 +33,10 @@ class Db
public static function getInstance(): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self();
if (is_null(self::$instance)) {
self::$instance = new self();
}
return self::$_instance;
return self::$instance;
}
public function execute($query, $values = null)
@ -74,11 +75,11 @@ class Db
// Allows the user to retrieve results using a
// column from the results as a key for the array
if (!is_null($key) && $results[0][$key]) {
$keyed_results = array();
$keyedResults = [];
foreach ($results as $result) {
$keyed_results[$result[$key]] = $result;
$keyedResults[$result[$key]] = $result;
}
$results = $keyed_results;
$results = $keyedResults;
}
return $results;
}
@ -107,11 +108,11 @@ class Db
// Allows the user to retrieve results using a
// column from the results as a key for the array
if (!is_null($key) && $results[0][$key]) {
$keyed_results = (object)[];
$keyedResults = (object)[];
foreach ($results as $result) {
$keyed_results->$result[$key] = $result;
$keyedResults->$result[$key] = $result;
}
$results = $keyed_results;
$results = $keyedResults;
}
return $results;
}
@ -131,4 +132,4 @@ class Db
$stmt = $this->execute($query, $values);
return $stmt->fetchColumn();
}
}
}

View File

@ -13,20 +13,20 @@ use stdClass;
class DressedItems
{
private int $USERID;
private int $userId;
private stdClass $dressedItem;
private static Db $db;
private object $dressed;
/**
* DressedItems constructor.
* @param int $user_id ID игрока.
* @param int $userId ID игрока.
*/
public function __construct(int $user_id)
public function __construct(int $userId)
{
self::$db = Db::getInstance();
$this->USERID = $user_id;
$this->dressed = self::$db->ofetchAll('select * from inventory where dressed_slot > 0 and owner_id = ?', $this->USERID);
$this->userId = $userId;
$this->dressed = self::$db->ofetchAll('select * from inventory where dressed_slot > 0 and owner_id = ?', $this->userId);
}
public static function getDressedItemBySlot($itemSlot, $ownerId)
@ -46,33 +46,33 @@ class DressedItems
/**
* Снимает с предмета статус одетого на персонажа в определённом слоте персонажа.
* @param $slot_id - номер слота.
* @param $slotId - номер слота.
*/
public function undressItem($slot_id)
public function undressItem($slotId)
{
self::getItemsInSlots();
// Проверяем, что используется один из 12 слотов и наличие предмета в слоте.
if (in_array($slot_id, Item::ITEM_TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem->$slot_id) {
Inventory::undressOne($slot_id, $this->USERID);
if (in_array($slotId, Item::TYPES_ALLOWED_IN_SLOTS) && $this->dressedItem->$slotId) {
Inventory::undressOne($slotId, $this->userId);
}
}
public static function undressAllItems($user_id)
public static function undressAllItems($userId)
{
return self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot BETWEEN 1 AND 12 AND owner_id = ?', $user_id);
return self::$db->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot BETWEEN 1 AND 12 AND owner_id = ?', $userId);
}
public function checkRequirements()
{
$stats = (new UserStats($this->USERID))->getFullStats();
$q = 'select count(*) from inventory where
dressed_slot > 0 and
$stats = (new UserStats($this->userId))->getFullStats();
$q = 'select count(*) from inventory where
dressed_slot > 0 and
need_strength > ? and
need_dexterity > ? and
need_intuition > ? and
need_endurance > ? and
need_dexterity > ? and
need_intuition > ? and
need_endurance > ? and
need_intelligence > ? and
need_wisdom > ? and
need_wisdom > ? and
owner_id = ?';
$args = [
$stats->strength,
@ -81,10 +81,10 @@ class DressedItems
$stats->endurance,
$stats->intelligence,
$stats->wisdom,
$this->USERID
$this->userId
];
if (self::$db->fetchColumn($q, $args) > 0) {
self::undressAllItems($this->USERID);
self::undressAllItems($this->userId);
}
}
}
}

View File

@ -23,4 +23,4 @@ class GameConfigs
const BANK_COMISSION = 0.05; // 5%
const DB_SQLITE = '/volume2/web/battles/databases/logs.sqlite';
}
}

View File

@ -3,11 +3,14 @@
namespace Battles;
use SQLite3;
use SQLite3Result;
use Battles\Database\Db;
class GameLogs
{
private const BANK = 1;
private const USER_ACTIONS = 2;
private const BATTLE = 3;
/**
* Добавление записи в лог банковских операций.
* @param int $senderId отправитель средств.
@ -18,15 +21,16 @@ class GameLogs
*/
public static function addBankLog(int $senderId, int $receiverId, int $amount, string $type, string $text)
{
$db = new SQLite3(GameConfigs::DB_SQLITE);
$row = $db->prepare("INSERT INTO bank_logs (sender_id, receiver_id, amount, type, text) VALUES (?, ?, ?, ?, ?)");
$row->bindParam(1, $senderId, SQLITE3_INTEGER);
$row->bindParam(2, $receiverId, SQLITE3_INTEGER);
$row->bindParam(3, $amount, SQLITE3_INTEGER);
$row->bindParam(4, $type, SQLITE3_TEXT);
$row->bindParam(5, $text, SQLITE3_TEXT);
$row->execute();
$row->close();
self::addLog(
json_encode([
'senderId' => $senderId,
'receiverId' => $receiverId,
'amount' => $amount,
'type' => $type,
'text' => $text,
]),
self::BANK,
);
}
/**
@ -44,48 +48,61 @@ class GameLogs
if (empty($type)) {
$type = "system";
}
$db = new SQLite3(GameConfigs::DB_SQLITE);
$row = $db->prepare("INSERT INTO users_logs (user_id, author_id, type, text) VALUES (?,?,?,?)");
$row->bindParam(1, $userId, SQLITE3_INTEGER);
$row->bindParam(2, $authorId, SQLITE3_INTEGER);
$row->bindParam(3, $type, SQLITE3_TEXT);
$row->bindParam(4, $text, SQLITE3_TEXT);
$row->execute();
$row->close();
self::addLog(
json_encode([
'userId' => $userId,
'authotId' => $authorId,
'type' => $type,
'text' => $text,
]),
self::USER_ACTIONS,
);
}
public static function getUserLogs($userId = null, $type = null): SQLite3Result
private static function addLog($jsonString, $logType)
{
$db = new SQLite3(GameConfigs::DB_SQLITE);
$row = false;
if ($userId && $type) {
$query = "SELECT * FROM users_logs WHERE user_id = ? AND type = ?";
$row = $db->prepare($query);
$row->bindValue(1, $userId, SQLITE3_INTEGER);
$row->bindValue(2, $type, SQLITE3_TEXT);
} elseif ($userId && !$type) {
$query = "SELECT * FROM users_logs WHERE user_id = ?";
$row = $db->prepare($query);
$row->bindValue(1, $userId, SQLITE3_INTEGER);
} elseif (!$userId && $type) {
$query = "SELECT * FROM users_logs WHERE type= ?";
$row = $db->prepare($query);
$row->bindValue(1, $type, SQLITE3_TEXT);
} elseif (!$userId && !$type) {
$query = "SELECT * FROM users_logs";
$row = $db->prepare($query);
Db::getInstance()->execute('insert into logs (json_data, type) VALUES (?,?)', [
$jsonString,
$logType
]);
}
private static function getLogByType(int $type): array
{
$result = [];
$logs = Db::getInstance()->fetchAll('select json_data from logs where type = ?', $type);
foreach ($logs as $log) {
$result[] = json_decode($log, true);
}
return $result;
}
public static function getUserLogs(?int $userId): array
{
$logs = self::getLogByType(self::USER_ACTIONS);
if (is_null($userId)) {
return $logs;
}
return $row->execute();
$result = [];
foreach ($logs as $log) {
if ($userId !== $log['userId']) {
continue;
}
$result[] = $log;
}
return $result;
}
public static function addBattleLog(int $battle_id, string $text)
public static function addBattleLog(int $battleId, string $text)
{
$db = new SQLite3(__DIR__ . '../../Database/battle.logs.getInstance');
$row = $db->prepare('insert into newbattles (battle_id, text) values (?,?)');
$row->bindParam(1, $battle_id, SQLITE3_INTEGER);
$row->bindParam(2, $text, SQLITE3_TEXT);
$row->execute();
$row->close();
self::addLog(
json_encode([
'battleId' => $battleId,
'text' => $text,
]),
self::BATTLE,
);
}
}
}

View File

@ -39,9 +39,9 @@ class Hostel
Db::getInstance()->execute('insert into hostel (uid, type, time) values (?,?,?)', [$this->uid, $type, time() + 60 * 60 * 24 * 7]);
}
private function addRentTime($hostel_id, $time)
private function addRentTime($hostelId, $time)
{
Db::getInstance()->execute('update hostel set time = ? where id = ? and uid = ?', [$time, $hostel_id, $this->uid]);
Db::getInstance()->execute('update hostel set time = ? where id = ? and uid = ?', [$time, $hostelId, $this->uid]);
}
private function removeItems()
@ -123,7 +123,7 @@ class Hostel
$this->newRent($type);
}
public function changeTime(int $ordered_time): bool
public function changeTime(int $orderedTime): bool
{
$daysByOrder = [
1 => 7,
@ -132,12 +132,12 @@ class Hostel
4 => 28,
];
if (
!$this->typeIsAllowed($ordered_time) ||
!$this->pay(self::PRICEPERTYPE[$this->type][$ordered_time - 1])
!$this->typeIsAllowed($orderedTime) ||
!$this->pay(self::PRICEPERTYPE[$this->type][$orderedTime - 1])
) {
return false;
}
$this->time += 60 * 60 * 24 * $daysByOrder[$ordered_time];
$this->time += 60 * 60 * 24 * $daysByOrder[$orderedTime];
$this->addRentTime($this->hid, $this->time);
$this->setSuccess('Всё прошло успешно!');
return true;

View File

@ -7,7 +7,7 @@ use Battles\Models\Inventory;
class InventoryItem extends Item
{
private ?string $present;
private int $owner_id;
private int $ownerId;
private const TOO_MANY_ITEMS_IN_SLOTS = 'Критическая ошибка: Переполнение слота!';
private const UNKNOWN_ITEM_TYPE = 'Неизвестный тип предмета!';
private const REQUIREMENTS_NOT_MET = 'Персонаж не соответствует требованиям!';
@ -20,7 +20,7 @@ class InventoryItem extends Item
public function __construct($row)
{
parent::__construct($row);
$this->owner_id = $row->owner_id;
$this->ownerId = $row->owner_id;
$this->present = $row->present;
}
@ -34,9 +34,9 @@ class InventoryItem extends Item
public function printImage()
{
if (in_array($this->item_type, range(1, 12))) {
if (in_array($this->type, range(1, 12))) {
echo <<<HTML
<a href=/main.php?edit=1&dress=$this->item_id title='Надеть'>
<a href=/main.php?edit=1&dress=$this->id title='Надеть'>
<img src="/i/sh/$this->image" class="item-wrap-normal" alt="">
</a>
HTML;
@ -47,21 +47,16 @@ IMG;
}
}
public function printControls()
{
// Для кнопок управления под картинкой.
}
private function dressStatsChecks(): bool
{
$checkStats = new UserStats($this->owner_id);
$checkStats = new UserStats($this->ownerId);
$stat = $checkStats->getFullStats();
return $this->need_strength > $stat->strength
|| $this->need_dexterity > $stat->dexterity
|| $this->need_intuition > $stat->intuition
|| $this->need_endurance > $stat->endurance
|| $this->need_intelligence > $stat->intelligence
|| $this->need_wisdom > $stat->wisdom;
return $this->needStrength > $stat->strength
|| $this->needDexterity > $stat->dexterity
|| $this->needIntuition > $stat->intuition
|| $this->needEndurance > $stat->endurance
|| $this->needIntelligence > $stat->intelligence
|| $this->needWisdom > $stat->wisdom;
}
/**
@ -77,33 +72,33 @@ IMG;
// считаем сколько ОДЕТЫХ предметов в слоте в который мы хотим одеть предмет. 1=просто вещь 1-3=шашни с кольцами
// Count добавленный в первый запрос возвращает одну строку в любом случае.
// fetch возвращает одну строку в любом случае.
$weared = Inventory::getDressed($this->item_type, $this->owner_id);
$wearedCount = Inventory::countDressed($this->item_type, $this->owner_id);
$weared = Inventory::getDressed($this->type, $this->ownerId);
$wearedCount = Inventory::countDressed($this->type, $this->ownerId);
// Если в слоте есть предмет(ы), забиваем их массив одетых в слот предметов.
if ($wearedCount) {
foreach ($weared as $item) {
$itemInSlot[] = $item->dressed_slot;
}
}
if (in_array($this->item_type, [
self::ITEM_TYPE_HELMET, self::ITEM_TYPE_ARMOR, self::ITEM_TYPE_LEGS, self::ITEM_TYPE_BOOTS,
self::ITEM_TYPE_GLOVES, self::ITEM_TYPE_WEAPON, self::ITEM_TYPE_SHIELD, self::ITEM_TYPE_BELT,
self::ITEM_TYPE_AMULET,
if (in_array($this->type, [
self::TYPE_HELMET, self::TYPE_ARMOR, self::TYPE_LEGS, self::TYPE_BOOTS,
self::TYPE_GLOVES, self::TYPE_WEAPON, self::TYPE_SHIELD, self::TYPE_BELT,
self::TYPE_AMULET,
])) {
//работаем с нормальными слотами
if ($wearedCount->c == 1) {
//если слот занят, снимаем старый предмет и одеваем новый предмет
Inventory::undressOne($itemInSlot[0], $this->owner_id);
Inventory::dressOne($this->item_id, $this->owner_id);
Inventory::undressOne($itemInSlot[0], $this->ownerId);
Inventory::dressOne($this->id, $this->ownerId);
} elseif (!$wearedCount->c) {
//если слот пуст, одеваем новый предмет
Inventory::dressOne($this->item_id, $this->owner_id);
Inventory::dressOne($this->id, $this->ownerId);
} else {
/* проверка на переполнение слотов */
$error = self::TOO_MANY_ITEMS_IN_SLOTS;
DressedItems::undressAllItems($this->owner_id);
DressedItems::undressAllItems($this->ownerId);
}
} elseif ($this->item_type == self::ITEM_TYPE_RING) {
} elseif ($this->type == self::TYPE_RING) {
// работаем с кольцами
if ($wearedCount->c < 3) {
// Сравниваем массив колец и массив слотов для колец.
@ -111,14 +106,14 @@ IMG;
// Сортируем массив свободных слотов по возрастанию.
sort($emptyRingSlots);
// Одеваем предмет в первый свободный слот.
Inventory::dressOneToSlot($this->item_id, $emptyRingSlots[0]);
Inventory::dressOneToSlot($this->id, $emptyRingSlots[0]);
} elseif ($wearedCount->c == 3) {
// Cнимаем предмет из последнего слота 11 и одеваем новый предмет
Inventory::changeRings($this->item_id);
Inventory::changeRings($this->id);
} else {
/* проверка на переполнение слотов */
$error = self::TOO_MANY_ITEMS_IN_SLOTS;
DressedItems::undressAllItems($this->owner_id);
DressedItems::undressAllItems($this->ownerId);
}
} else {
$error = self::UNKNOWN_ITEM_TYPE;
@ -130,26 +125,25 @@ IMG;
// Выбрасываем вещь.
public function drop(): string
{
if (empty($this->item_id)) {
if (empty($this->id)) {
return 'Ошибка: предмет не найден!';
}
if (Inventory::isWeared($this->item_id)) {
if (Inventory::isWeared($this->id)) {
return 'Ошибка: нельзя выбросить одетый предмет!';
}
Inventory::destroyItem($this->item_id, $this->owner_id);
GameLogs::addUserLog(User::getInstance()->getId(), User::getInstance()->getLogin() . ' выбросил предмет ' . $this->name . ' id:(cap' . $this->item_id . ')');
Inventory::destroyItem($this->id, $this->ownerId);
GameLogs::addUserLog(User::getInstance()->getId(), User::getInstance()->getLogin() . ' выбросил предмет ' . $this->name . ' id:(cap' . $this->id . ')');
return 'Предмет ' . $this->name . ' выброшен.';
}
/** Снятие всех предметов, которые не подходят по статам. */
public static function autoDrop()
{
$DI = new DressedItems(User::getInstance()->getId());
foreach ($DI->getItemsInSlots() as $dressedItem)
{
$ITM = new self($dressedItem);
if (!$ITM->dressStatsChecks()) {
$DI->undressItem($dressedItem->dressed_slot);
$di = new DressedItems(User::getInstance()->getId());
foreach ($di->getItemsInSlots() as $dressedItem) {
$itm = new self($dressedItem);
if (!$itm->dressStatsChecks()) {
$di->undressItem($dressedItem->dressed_slot);
}
}
}
@ -164,4 +158,4 @@ IMG;
$css = $all > $max ? ' style="color:maroon;"' : '';
return "<span$css>$all / $max</span>";
}
}
}

View File

@ -1,48 +1,49 @@
<?php
namespace Battles;
use Battles\Database\Db;
class Item
{
protected int $item_id;
protected int $id;
protected string $name = '';
protected int $item_type = self::ITEM_TYPE_TRASH;
protected int $type = self::TYPE_TRASH;
protected int $durability = 0;
protected int $need_strength = 0;
protected int $need_dexterity = 0;
protected int $need_intuition = 0;
protected int $need_endurance = 0;
protected int $need_intelligence = 0;
protected int $need_wisdom = 0;
protected int $add_strength = 0;
protected int $add_dexterity = 0;
protected int $add_intuition = 0;
protected int $add_endurance = 0;
protected int $add_intelligence = 0;
protected int $add_wisdom = 0;
protected int $add_accuracy = 0;
protected int $add_evasion = 0;
protected int $add_criticals = 0;
protected int $add_min_physical_damage = 0;
protected int $add_max_physical_damage = 0;
protected int $needStrength = 0;
protected int $needDexterity = 0;
protected int $needIntuition = 0;
protected int $needEndurance = 0;
protected int $needIntelligence = 0;
protected int $needWisdom = 0;
protected int $addStrength = 0;
protected int $addDexterity = 0;
protected int $addIntuition = 0;
protected int $addEndurance = 0;
protected int $addIntelligence = 0;
protected int $addWisdom = 0;
protected int $addAccuracy = 0;
protected int $addEvasion = 0;
protected int $addCriticals = 0;
protected int $addMinPhysicalDamage = 0;
protected int $addMaxPhysicalDamage = 0;
protected int $weight = 0;
protected string $image = '';
protected int $item_cost = 0;
public const ITEM_TYPES_ALLOWED_IN_SLOTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
public const ITEM_TYPE_HELMET = 1;
public const ITEM_TYPE_ARMOR = 2;
public const ITEM_TYPE_LEGS = 3;
public const ITEM_TYPE_BOOTS = 4;
public const ITEM_TYPE_GLOVES = 5;
public const ITEM_TYPE_WEAPON = 6;
public const ITEM_TYPE_SHIELD = 7;
public const ITEM_TYPE_BELT = 8;
public const ITEM_TYPE_RING = 9;
public const ITEM_TYPE_AMULET = 10;
public const ITEM_TYPE_CONSUMABLE = 20;
public const ITEM_TYPE_OTHER = 50;
public const ITEM_TYPE_TRASH = 100;
protected int $cost = 0;
public const TYPES_ALLOWED_IN_SLOTS = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
public const TYPE_HELMET = 1;
public const TYPE_ARMOR = 2;
public const TYPE_LEGS = 3;
public const TYPE_BOOTS = 4;
public const TYPE_GLOVES = 5;
public const TYPE_WEAPON = 6;
public const TYPE_SHIELD = 7;
public const TYPE_BELT = 8;
public const TYPE_RING = 9;
public const TYPE_AMULET = 10;
public const TYPE_CONSUMABLE = 20;
public const TYPE_OTHER = 50;
public const TYPE_TRASH = 100;
private string $typename;
/**
@ -66,45 +67,45 @@ class Item
}
}
switch ($this->item_type) {
case self::ITEM_TYPE_HELMET:
switch ($this->type) {
case self::TYPE_HELMET:
$this->typename = 'Шлем';
break;
case self::ITEM_TYPE_ARMOR:
case self::TYPE_ARMOR:
$this->typename = 'Броня';
break;
case self::ITEM_TYPE_LEGS:
case self::TYPE_LEGS:
$this->typename = 'Поножи';
break;
case self::ITEM_TYPE_BOOTS:
case self::TYPE_BOOTS:
$this->typename = 'Сапоги';
break;
case self::ITEM_TYPE_GLOVES:
case self::TYPE_GLOVES:
$this->typename = 'Перчатки';
break;
case self::ITEM_TYPE_WEAPON:
case self::TYPE_WEAPON:
$this->typename = 'Оружие';
break;
case self::ITEM_TYPE_SHIELD:
case self::TYPE_SHIELD:
$this->typename = 'Щит';
break;
case self::ITEM_TYPE_BELT:
case self::TYPE_BELT:
$this->typename = 'Пояс';
break;
case self::ITEM_TYPE_RING:
case self::TYPE_RING:
$this->typename = 'Кольцо';
break;
case self::ITEM_TYPE_AMULET:
case self::TYPE_AMULET:
$this->typename = 'Амулет';
break;
case self::ITEM_TYPE_CONSUMABLE:
case self::TYPE_CONSUMABLE:
$this->typename = 'Расходуемый предмет';
break;
default:
$this->typename = 'Хлам';
}
$this->item_cost = $this->calculateItemCost();
$this->cost = $this->calculateItemCost();
}
/** Рассчёт стоимости предмета в зависимости от его характеристик.
@ -112,26 +113,26 @@ class Item
*/
protected function calculateItemCost(): int
{
$sum_stats =
$this->add_strength +
$this->add_dexterity +
$this->add_intuition +
$this->add_endurance +
$this->add_intelligence +
$this->add_wisdom;
$sum_mods =
$this->add_accuracy +
$this->add_evasion +
$this->add_criticals;
$sum_damage =
$this->add_min_physical_damage +
$this->add_max_physical_damage;
$sumStats =
$this->addStrength +
$this->addDexterity +
$this->addIntuition +
$this->addEndurance +
$this->addIntelligence +
$this->addWisdom;
$sumMods =
$this->addAccuracy +
$this->addEvasion +
$this->addCriticals;
$sumDamage =
$this->addMinPhysicalDamage +
$this->addMaxPhysicalDamage;
// За каждые N параметров повышаем множитель на 1 чтобы цена пропрорционально росла.
$stats_cost_modifier = 5 + floor($sum_stats / 10);
$mods_cost_modifier = 2 + floor($sum_mods / 50);
$damage_cost_modifier = 1 + floor($sum_damage / 100);
$result = intval($sum_stats * $stats_cost_modifier + $sum_mods * $mods_cost_modifier + $sum_damage * $damage_cost_modifier);
return $result < 1 ? 1 : $result;
$statsCostModifier = 5 + floor($sumStats / 10);
$modsCostModifier = 2 + floor($sumMods / 50);
$damageCostModifier = 1 + floor($sumDamage / 100);
$result = intval($sumStats * $statsCostModifier + $sumMods * $modsCostModifier + $sumDamage * $damageCostModifier);
return max($result, 1);
}
protected function wrap(int $number): string
@ -146,26 +147,26 @@ class Item
public function getAllInfo(): string
{
$needsLines = [
'сила' => $this->need_strength,
'ловкость' => $this->need_dexterity,
'интуиция' => $this->need_intuition,
'выносливость' => $this->need_endurance,
'интеллект' => $this->need_intelligence,
'мудрость' => $this->need_wisdom,
'сила' => $this->needStrength,
'ловкость' => $this->needDexterity,
'интуиция' => $this->needIntuition,
'выносливость' => $this->needEndurance,
'интеллект' => $this->needIntelligence,
'мудрость' => $this->needWisdom,
];
$addsLines = [
'Сила' => $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->addStrength,
'Ловкость' => $this->addDexterity,
'Интуиция' => $this->addIntuition,
'Выносливость' => $this->addEndurance,
'Интеллект' => $this->addIntelligence,
'Мудрость' => $this->addWisdom,
'Точность' => $this->addAccuracy,
'Увёртливость' => $this->addEvasion,
'Шанс крита' => $this->addCriticals,
];
$str = "<b>$this->name</b> (Масса: $this->weight)";
$str .= '<br> Стоимость: ' . $this->item_cost;
$str .= '<br> Стоимость: ' . $this->cost;
$str .= '<br> Долговечность: ' . $this->durability;
$str .= "<br><em>$this->typename</em><br>";
foreach ($needsLines as $stat => $value) {
@ -178,12 +179,12 @@ class Item
$str .= "<br>$stat" . $this->wrap($value);
}
}
if ($this->add_min_physical_damage && !$this->add_max_physical_damage) {
$damage = $this->add_min_physical_damage . ' - ' . $this->add_min_physical_damage;
} elseif (!$this->add_min_physical_damage && $this->add_max_physical_damage) {
$damage = $this->add_max_physical_damage . ' - ' . $this->add_max_physical_damage;
} elseif ($this->add_min_physical_damage && $this->add_max_physical_damage) {
$damage = $this->add_min_physical_damage . ' - ' . $this->add_max_physical_damage;
if ($this->addMinPhysicalDamage && !$this->addMaxPhysicalDamage) {
$damage = $this->addMinPhysicalDamage . ' - ' . $this->addMinPhysicalDamage;
} elseif (!$this->addMinPhysicalDamage && $this->addMaxPhysicalDamage) {
$damage = $this->addMaxPhysicalDamage . ' - ' . $this->addMaxPhysicalDamage;
} elseif ($this->addMinPhysicalDamage && $this->addMaxPhysicalDamage) {
$damage = $this->addMinPhysicalDamage . ' - ' . $this->addMaxPhysicalDamage;
}
if (isset($damage)) {
$str .= '<br>Урон: ' . $damage;
@ -191,8 +192,8 @@ class Item
return $str;
}
public static function getItemById($item_id): Item
public static function getItemById($itemId): Item
{
return new Item(Db::getInstance()->ofetch('select * from items where id = ?', $item_id));
return new Item(Db::getInstance()->ofetch('select * from items where id = ?', $itemId));
}
}
}

View File

@ -25,16 +25,16 @@ class Sharpen extends Magic
if (!$this->isUsable()) {
return $this->status;
}
$item = DressedItems::getDressedItemBySlot(Item::ITEM_TYPE_WEAPON, $_SESSION['uid']);
$item = DressedItems::getDressedItemBySlot(Item::TYPE_WEAPON, $_SESSION['uid']);
// Проверяем, что в названии предмета нет цифр и плюсов.
if (preg_match('/[\W\S]+\+\[?[\d]]?/', $item->name)) {
if (preg_match('/\+\d/', $item->name)) {
return 'Этот предмет точить нельзя!';
}
$newMinPhysicalDamage = $item->add_min_physical_damage + $sharpenStrength;
$newMaxPhysicalDamage = $item->add_max_physical_damage + $sharpenStrength;
$newItemName = $item->name . " [+$sharpenStrength]";
Db::getInstance()->execute('UPDATE battles.inventory SET name = ?, add_min_physical_damage = ?, add_max_physical_damage = ? WHERE item_id = ? ', [$newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item->item_id]);
Db::getInstance()->execute('UPDATE inventory SET name = ?, add_min_physical_damage = ?, add_max_physical_damage = ? WHERE item_id = ? ', [$newItemName, $newMinPhysicalDamage, $newMaxPhysicalDamage, $item->item_id]);
return "У вас получилось изготовить предмет $newItemName!";
}
@ -42,4 +42,4 @@ class Sharpen extends Magic
{
return $this->isNotInBattle(User::getInstance()) && $this->isSuccess(User::getInstance(), $this->magicDifficulty);
}
}
}

View File

@ -6,130 +6,114 @@ use Battles\Database\Db;
class Inventory
{
public static function getWeight(int $user_id): int
public static function getWeight(int $userId): int
{
return Db::getInstance()->fetchColumn('
select
sum(weight)
from
inventory
where
owner_id = ?
and on_sale = 0
', $user_id);
return Db::getInstance()->fetchColumn(
'select sum(weight) from inventory where owner_id = ? and on_sale = 0',
$userId
);
}
public static function getBonuses(int $user_id)
public static function getBonuses(int $userId)
{
return Db::getInstance()->ofetch("
select
sum(add_strength) as item_strength,
sum(add_dexterity) as item_dexterity,
sum(add_intuition) as item_intuition,
sum(add_endurance) as item_endurance,
sum(add_intelligence) as item_intelligence,
sum(add_wisdom) as item_wisdom,
sum(add_accuracy) as item_accuracy,
sum(add_evasion) as item_evasion,
sum(add_criticals) as item_criticals,
sum(add_min_physical_damage) as item_min_physical_damage,
sum(add_max_physical_damage) as item_max_physical_damage
from
inventory
where
dressed_slot != 0 and
owner_id = ?
", $user_id);
return Db::getInstance()->ofetch(
"select
sum(add_strength) as item_strength,
sum(add_dexterity) as item_dexterity,
sum(add_intuition) as item_intuition,
sum(add_endurance) as item_endurance,
sum(add_intelligence) as item_intelligence,
sum(add_wisdom) as item_wisdom,
sum(add_accuracy) as item_accuracy,
sum(add_evasion) as item_evasion,
sum(add_criticals) as item_criticals,
sum(add_min_physical_damage) as item_min_physical_damage,
sum(add_max_physical_damage) as item_max_physical_damage
from
inventory
where
dressed_slot != 0 and owner_id = ?",
$userId
);
}
public static function getDressed(int $item_type, int $user_id): object
public static function getDressed(int $itemType, int $userId): object
{
return Db::getInstance()->ofetchAll('
SELECT
dressed_slot
FROM
inventory
WHERE
dressed_slot != 0
AND item_type = ?
AND owner_id = ?
', [$item_type, $user_id]);
return Db::getInstance()->ofetchAll(
'SELECT
dressed_slot
FROM
inventory
WHERE
dressed_slot != 0 AND item_type = ? AND owner_id = ?',
[$itemType, $userId]
);
}
public static function countDressed(int $item_type, int $user_id): object
public static function countDressed(int $itemType, int $userId): object
{
return Db::getInstance()->ofetchAll('
SELECT
count(dressed_slot)
FROM
inventory
WHERE
dressed_slot != 0
AND item_type = ?
AND owner_id = ?
', [$item_type, $user_id]);
return Db::getInstance()->ofetchAll(
'SELECT
count(dressed_slot)
FROM
inventory
WHERE
dressed_slot != 0 AND item_type = ? AND owner_id = ?',
[$itemType, $userId]
);
}
public static function undressOne(int $slot, int $user_id)
public static function undressOne(int $slot, int $userId)
{
Db::getInstance()->execute('
UPDATE
inventory
SET
dressed_slot = 0
WHERE
dressed_slot = ?
AND owner_id = ?
', [$slot, $user_id]);
Db::getInstance()->execute(
'UPDATE
inventory
SET
dressed_slot = 0
WHERE
dressed_slot = ? AND owner_id = ?',
[$slot, $userId]
);
}
public static function dressOne(int $item_id, int $user_id)
public static function dressOne(int $itemId, int $userId)
{
Db::getInstance()->execute('
UPDATE
inventory
SET
dressed_slot = item_type
WHERE
item_id = ?
AND owner_id = ?
', [$item_id, $user_id]);
Db::getInstance()->execute(
'UPDATE
inventory
SET
dressed_slot = item_type
WHERE
item_id = ? AND owner_id = ?',
[$itemId, $userId]
);
}
public static function dressOneToSlot(int $item_id, int $slot)
public static function dressOneToSlot(int $itemId, int $slot)
{
Db::getInstance()->execute('UPDATE inventory SET dressed_slot = ? WHERE item_id = ?', [$slot, $item_id]);
Db::getInstance()->execute('UPDATE inventory SET dressed_slot = ? WHERE item_id = ?', [$slot, $itemId]);
}
public static function destroyItem(int $item_id, int $user_id)
public static function destroyItem(int $itemId, int $userId)
{
Db::getInstance()->execute('
delete
from
inventory
where
dressed_slot = 0
and owner_id = ?
and item_id = ?
', [$user_id, $item_id]);
Db::getInstance()->execute(
'delete
from
inventory
where
dressed_slot = 0 and owner_id = ? and item_id = ?',
[$userId, $itemId]
);
}
public static function changeRings(int $item_id)
public static function changeRings(int $itemId)
{
Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 0 WHERE dressed_slot = 11');
Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $item_id);
Db::getInstance()->execute('UPDATE inventory SET dressed_slot = 11 WHERE item_id = ?', $itemId);
}
public static function isWeared(int $item_id): bool
public static function isWeared(int $itemId): bool
{
return Db::getInstance()->fetchColumn('
select
count(*)
from
inventory
where
item_id = ?
and dressed_slot > 0
', $item_id) > 0;
return Db::getInstance()->fetchColumn('select count(*) from inventory where item_id = ? and dressed_slot > 0', $itemId) > 0;
}
}
}

View File

@ -4,6 +4,7 @@
* Date: 04.07.2020
* Time: 13:17
*/
namespace Battles\Models;
use Battles\Database\Db;
@ -12,11 +13,11 @@ use Battles\User;
class Presents
{
public function getAll($user_id = null)
public function getAll($userId = null)
{
if (is_null($user_id)) {
$user_id = User::getInstance()->getId();
if (is_null($userId)) {
$userId = User::getInstance()->getId();
}
return Db::getInstance()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $user_id);
return Db::getInstance()->execute('SELECT sender_id, image FROM `users_presents` WHERE owner_id = ?', $userId);
}
}
}

View File

@ -6,30 +6,31 @@ use Battles\Database\Db;
class Effects
{
public static function getStatMods(int $user_id)
public static function getStatMods(int $userId)
{
return Db::getInstance()->ofetch("
select
sum(mod_strength) as effect_strength,
sum(mod_dexterity) as effect_dexterity,
sum(mod_intuition) as effect_intuition,
sum(mod_endurance) as effect_endurance,
sum(mod_intelligence) as effect_intelligence,
sum(mod_wisdom) as effect_wisdom
from
users_effects
where
owner_id = ?
", $user_id);
return Db::getInstance()->ofetch(
"select
sum(mod_strength) as effect_strength,
sum(mod_dexterity) as effect_dexterity,
sum(mod_intuition) as effect_intuition,
sum(mod_endurance) as effect_endurance,
sum(mod_intelligence) as effect_intelligence,
sum(mod_wisdom) as effect_wisdom
from
users_effects
where
owner_id = ?",
$userId
);
}
public static function getAll(int $user_id): object
public static function getAll(int $userId): object
{
return Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $user_id);
return Db::getInstance()->ofetchAll('SELECT * FROM users_effects WHERE owner_id = ?', $userId);
}
public static function count(int $user_id, int $type)
public static function count(int $userId, int $type)
{
return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = ? and owner_id = ?', [$type, $user_id]);
return Db::getInstance()->fetchColumn('select count(*) from users_effects where type = ? and owner_id = ?', [$type, $userId]);
}
}
}

View File

@ -15,38 +15,40 @@ class Stats
return Db::getInstance()->ofetch('select id, strength, dexterity, intuition, endurance, intelligence, wisdom, health, mana, free_stat_points, level from users where ' . $col . ' = ?', $user);
}
public static function addOne(string $stat, int $user_id)
public static function addOne(string $stat, int $userId)
{
Db::getInstance()->execute("
UPDATE
users
SET
$stat = $stat + 1,
free_stat_points = free_stat_points - 1
WHERE
id = ?
", $user_id);
Db::getInstance()->execute(
"UPDATE
users
SET
$stat = $stat + 1,
free_stat_points = free_stat_points - 1
WHERE
id = ?",
$userId
);
}
public static function save(array $vars)
{
Db::getInstance()->execute('
update
users
set
strength = ?,
dexterity = ?,
intuition = ?,
Db::getInstance()->execute(
'update
users
set
strength = ?,
dexterity = ?,
intuition = ?,
endurance = ?,
intelligence = ?,
wisdom = ?,
health = ?,
mana = ?,
intelligence = ?,
wisdom = ?,
health = ?,
mana = ?,
free_stat_points = ?,
level = ?
where
id = ?
', $vars);
level = ?
where
id = ?',
$vars
);
}
}
}

View File

@ -83,4 +83,4 @@ class Moderation
self::addEffectStatusToUserLog($target, UserEffect::$effectName[20]);
UserEffect::add($target, 20, UserEffect::$effectName[20], strtotime('3days'));
}
}
}

View File

@ -98,4 +98,4 @@ class Nick
{
return $this->full() . "<img src='i/herz.gif' alt='HP'> [" . $this->user->stats()->getHealth() . "/" . $this->user->stats()->getMaxHealth() . "]";
}
}
}

View File

@ -44,9 +44,15 @@ class RememberPassword
$hash = uniqid();
$tomorrow = date('d-M-Y', strtotime('+1 days'));
Db::getInstance()->execute('INSERT INTO users_recovery (login, hash, ip, date) VALUES (?,?,?,?)', [$to, $hash, $tomorrow, $_SERVER['REMOTE_ADDR']]);
$message = sprintf('Здравствуйте!<br><br>Кто-то запросил восстановление пароля к вашему персонажу %s <br><br>
Для смены пароля пройдите по <a href="//%s/rememberpassword.php?change=%s">данной ссылке</a>.<br><br>
Ссылка будет действовать до <em>%s</em>',$to, GAMEDOMAIN, $hash, $tomorrow);
$message = sprintf(
'Здравствуйте!<br><br>Кто-то запросил восстановление пароля к вашему персонажу %s <br><br>
Для смены пароля пройдите по <a href="//%s/rememberpassword.php?change=%s">данной ссылке</a>.<br><br>
Ссылка будет действовать до <em>%s</em>',
$to,
GAMEDOMAIN,
$hash,
$tomorrow
);
return self::mailSend($check->email, $message) ? self::OK_MAIL_SENT : self::ERROR_MAIL_NOT_SENT;
}
public function isAllowed($hash)
@ -65,4 +71,4 @@ class RememberPassword
Db::getInstance()->execute('DELETE FROM users_recovery WHERE hash = ?', $hash);
return self::OK_PASSWORD_CHANGED;
}
}
}

View File

@ -1,11 +1,12 @@
<?php
namespace Battles;
/*
* Список наименований игровых комнат.
*/
trait Rooms
{
public static $roomNames = [
public static array $roomNames = [
0 => "Секретная Комната",
1 => "Дом поединков",
20 => "Центральная площадь",
@ -186,4 +187,4 @@ trait Rooms
2601 => "Замковая Площадь",
2702 => "Центральная площадь (мираж)",
];
}
}

View File

@ -12,9 +12,9 @@ class Shop
public int $categoryType = 0;
private int $shopId;
private function __construct($shop_id)
private function __construct($shopId)
{
$this->shopId = $shop_id;
$this->shopId = $shopId;
}
public static function id($shopid): self
@ -70,18 +70,18 @@ class Shop
public function getCategoryName(): string
{
$names = [
Item::ITEM_TYPE_HELMET => 'Шлемы',
Item::ITEM_TYPE_ARMOR => 'Броня',
Item::ITEM_TYPE_LEGS => 'Поножи',
Item::ITEM_TYPE_BOOTS => 'Сапоги',
Item::ITEM_TYPE_GLOVES => 'Перчатки',
Item::ITEM_TYPE_WEAPON => 'Оружие',
Item::ITEM_TYPE_SHIELD => 'Щиты',
Item::ITEM_TYPE_BELT => 'Пояса',
Item::ITEM_TYPE_RING => 'Кольца',
Item::ITEM_TYPE_AMULET => 'Амулеты',
Item::ITEM_TYPE_CONSUMABLE => 'Расходники',
Item::ITEM_TYPE_OTHER => 'Разное',
Item::TYPE_HELMET => 'Шлемы',
Item::TYPE_ARMOR => 'Броня',
Item::TYPE_LEGS => 'Поножи',
Item::TYPE_BOOTS => 'Сапоги',
Item::TYPE_GLOVES => 'Перчатки',
Item::TYPE_WEAPON => 'Оружие',
Item::TYPE_SHIELD => 'Щиты',
Item::TYPE_BELT => 'Пояса',
Item::TYPE_RING => 'Кольца',
Item::TYPE_AMULET => 'Амулеты',
Item::TYPE_CONSUMABLE => 'Расходники',
Item::TYPE_OTHER => 'Разное',
self::CATEGORY_SALE_ITEMS => 'Предметы в инвентаре',
0 => 'Все товары',
];
@ -92,4 +92,4 @@ class Shop
{
return $this->categoryType !== self::CATEGORY_SALE_ITEMS || $this->categoryType !== self::BARTER_SHOP ? $this->showGoods() : $this->showUserSellItems();
}
}
}

View File

@ -20,32 +20,32 @@ insert into inventory (
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
image, weight, price)
select
?, 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, greatest(
(
(add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) *
(5 + floor((add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) / 10))
) +
(
(add_accuracy + add_criticals + add_evasion) *
(2 + floor((add_accuracy + add_criticals + add_evasion) / 50))
) +
(
(add_min_physical_damage + add_max_physical_damage) *
(add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) *
(5 + floor((add_strength + add_dexterity + add_intuition + add_endurance + add_intelligence + add_wisdom) / 10))
) +
(
(add_accuracy + add_criticals + add_evasion) *
(2 + floor((add_accuracy + add_criticals + add_evasion) / 50))
) +
(
(add_min_physical_damage + add_max_physical_damage) *
(1 + floor((add_min_physical_damage + add_max_physical_damage) / 100))
)
,1)
,1)
from items where id = ?
SQL;
// Тип операции в магазине. Для отображения разных блоков в разных случаях.
private $optype;
private ?int $shop_item_quantity;
private ?int $shopItemQuantity;
private ?int $price;
public static string $status = '';
private ?string $jsonBarterList;
@ -59,8 +59,8 @@ SQL;
$this->optype = $operationType;
}
$this->price = $row->price ?? null;
$this->shop_item_quantity = $row->shop_item_quantity ?? null;
$this->item_id = $row->item_id ?? $row->id;
$this->shopItemQuantity = $row->shop_item_quantity ?? null;
$this->id = $row->item_id ?? $row->id;
if ($operationType === 'buyshop' || $operationType === 'buymarket') {
$this->offerId = $row->offer_id ?? 0; // Ид позиции в магазине.
$this->jsonBarterList = $row->barter_items_list_json ?? null;
@ -102,10 +102,10 @@ SQL;
private function getLowItemQuantityNote(): string
{
if ($this->shop_item_quantity < 1 || $this->shop_item_quantity > 19) {
if ($this->shopItemQuantity < 1 || $this->shopItemQuantity > 19) {
return '';
}
return "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shop_item_quantity единиц товара!</div>";
return "<div style='margin-top: 9px; font-style: italic;'>На складе осталось $this->shopItemQuantity единиц товара!</div>";
}
private function getTextBasedOnPrice(): string
@ -152,14 +152,14 @@ SQL;
self::$status = "Предмет " . $item->name . " куплен за " . $price . ".";
}
private static function checkAndRemoveBarteredItems(?string $json_list, int $user_id): bool
private static function checkAndRemoveBarteredItems(?string $jsonList, int $userId): bool
{
if (empty($json_list)) {
if (empty($jsonList)) {
return true;
}
$allowItemRemove = true;
foreach (json_decode($json_list) as $item) {
$row = Db::getInstance()->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $user_id]);
foreach (json_decode($jsonList) as $item) {
$row = Db::getInstance()->ofetch('select sum(1) as s from inventory where name = ? and owner_id = ?', [Item::getItemById($item->item_id)->name, $userId]);
if ($row->s < $item->quantity) {
$allowItemRemove = false;
}
@ -168,10 +168,10 @@ SQL;
self::$status = self::NO_BARTER_ITEMS;
return false;
}
foreach (json_decode($json_list) as $item) {
foreach (json_decode($jsonList) as $item) {
$query = 'delete from inventory where name = ? and owner_id = ? limit ' . (int)$item->quantity;
// У-у-у, сука! https://phpdelusions.net/pdo#limit
Db::getInstance()->execute($query, [Item::getItemById($item->item_id)->name, $user_id]);
Db::getInstance()->execute($query, [Item::getItemById($item->item_id)->name, $userId]);
}
return true;
}
@ -185,16 +185,16 @@ SQL;
return true;
}
private static function checkAndChangeRemainingItems(int $current_quantity, $item_id): bool
private static function checkAndChangeRemainingItems(int $currentQuantity, $itemId): bool
{
if (empty($current_quantity)) {
if (empty($currentQuantity)) {
self::$status = self::NO_ITEMS_IN_STOCK;
return false;
}
if ($current_quantity === -1) {
if ($currentQuantity === -1) {
return true;
}
Db::getInstance()->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_quantity != -1 and shop_item_id = ? ", $item_id);
Db::getInstance()->execute("update trade_offers set shop_item_quantity = shop_item_quantity -1 where shop_item_quantity != -1 and shop_item_id = ? ", $itemId);
return true;
}
@ -241,12 +241,12 @@ SQL;
return '';
}
$str = $this->optype == 'setmarket' ? '<input placeholder=" ' . $this->price . ' " name="cost">' : '';
$hiddenValue = $this->optype === 'buyshop' ? $this->offerId : $this->item_id;
$button_name = self::BUTTON[$this->optype];
$hiddenValue = $this->optype === 'buyshop' ? $this->offerId : $this->id;
$buttonName = self::BUTTON[$this->optype];
return <<<FORM
<form method="post">$str
<input type="hidden" name="itemId" value="$hiddenValue">
<br><input type="submit" name="$this->optype" value="$button_name">
<br><input type="submit" name="$this->optype" value="$buttonName">
</form>
FORM;
}
@ -256,28 +256,28 @@ FORM;
*/
public function getItemType(): int
{
return $this->item_type;
return $this->type;
}
/** Выдача магазинных предметов по запросу.
* Ввелась чтобы перебить takeshopitem() в functions с идентичным функционалом.
*
* @param int $item_id ИД предмета.
* @param int $itemId ИД предмета.
* @param int $to ИД пперсонажа-получателя.
*/
public static function giveNewItem(int $item_id, int $to): array
public static function giveNewItem(int $itemId, int $to): array
{
$check = Db::getInstance()->ofetch('select 1 from items where id = ?', $item_id);
$check = Db::getInstance()->ofetch('select 1 from items where id = ?', $itemId);
if (!$check) {
return [];
}
Db::getInstance()->execute(self::BUY_QUERY, [$to, $item_id]);
Db::getInstance()->execute(self::BUY_QUERY, [$to, $itemId]);
$return = Db::getInstance()->ofetch('select image, name from inventory where item_id = ?', Db::getInstance()->lastInsertId());
return [
'img' => $return->image,
'name' => $return->name,
'id' => $item_id,
'id' => $itemId,
];
}
}
}

View File

@ -1,6 +1,7 @@
<?php
# Date: 30.09.2020 (09:42)
namespace Battles;
class Template
{
/**
@ -47,4 +48,4 @@ HTML_HEADER;
<h1>$buildingName</h1>
HTML;
}
}
}

View File

@ -205,4 +205,4 @@ class Travel
exit;
}
}
}
}

View File

@ -7,7 +7,7 @@ use Battles\Database\Db;
class User
{
use Users;
private static ?self $_instance = null;
private static ?self $instance = null;
private ?UserProfile $profile = null;
private ?UserEffect $effect = null;
private ?UserStats $stats = null;
@ -19,6 +19,7 @@ class User
protected int $experience = 0;
protected int $battle = 0;
protected int $zayavka = 0;
private object $profileData;
protected function __construct($user = null)
{
@ -28,10 +29,10 @@ class User
// Отсекаем 2.0000~
$col = ctype_digit(strval($user)) ? 'id' : 'login';
$query = "select * from users where $col = ?";
$user_query = Db::getInstance()->fetch($query, $user);
$userQuery = Db::getInstance()->fetch($query, $user);
foreach ($this as $key => $value) {
if (isset($user_query[$key])) {
$this->$key = $user_query[$key];
if (isset($userQuery[$key])) {
$this->$key = $userQuery[$key];
}
}
@ -48,10 +49,10 @@ class User
public static function getInstance($user = null): self
{
if (is_null(self::$_instance)) {
self::$_instance = new self($user);
if (is_null(self::$instance)) {
self::$instance = new self($user);
}
return self::$_instance;
return self::$instance;
}
public function profile(): UserProfile
@ -100,7 +101,6 @@ class User
return $this->userMoney;
}
public function getId(): int
{
return $this->id;
@ -128,11 +128,11 @@ class User
}
/**
* @param string|null $short_name Короткое название клана. Передать null для очистки.
* @param string|null $shortName Короткое название клана. Передать null для очистки.
*/
public function setClan(?string $short_name)
public function setClan(?string $shortName)
{
$this->clan = is_null($short_name) ? null : $short_name;
$this->clan = is_null($shortName) ? null : $shortName;
$this->saveUser();
}
@ -224,4 +224,4 @@ class User
Db::getInstance()->execute($query, $vals);
}
}
}

View File

@ -94,11 +94,11 @@ class UserEffect
* @param int $type
* @param string $name
* @param int $time
* @param string|null $json_modifiers_list (str, dex, int, end, intel, wis).
* @param string|null $jsonModifiersList (str, dex, int, end, intel, wis).
*/
public static function add(int $userId, int $type, string $name, int $time, string $json_modifiers_list = null)
public static function add(int $userId, int $type, string $name, int $time, string $jsonModifiersList = null)
{
$mods = json_decode($json_modifiers_list);
$mods = json_decode($jsonModifiersList);
Db::getInstance()->execute('INSERT INTO users_effects (owner_id, type, name, remaining_time, mod_strength, mod_dexterity, mod_intuition, mod_endurance, mod_intelligence, mod_wisdom) VALUES (?,?,?,?,?,?,?,?,?,?)', [$userId, $type, $name, $time, $mods->str ?? null, $mods->dex ?? null, $mods->int ?? null, $mods->end ?? null, $mods->intel ?? null, $mods->wis ?? null]);
}
@ -159,4 +159,4 @@ class UserEffect
$query = 'select strength * 5 + ' . $addWeight . ' as max from inventory left join users u on owner_id = id where owner_id = ? having sum(weight) > max';
return Db::getInstance()->fetchColumn($query, $userid) > 0;
}
}
}

View File

@ -7,8 +7,27 @@ use Exceptions\GameException;
class UserInfo extends UserStats
{
private const STRENGTH = 'Сила';
private const DEXTERITY = 'Ловкость';
private const INTUITION = 'Интуиция';
private const ENDURANCE = 'Выносливость';
private const INTELLIGENCE = 'Интеллект';
private const WISDOM = 'Мудрость';
private const PERCENT_20 = (20 / 100);
private const PERCENT_80 = (80 / 100);
private const LEVEL = 'Уровень';
private const HEALTH = 'Здоровье';
private const MANA = 'Пыль';
private const EXPERIENCE = 'Опыт';
private const FREE_STAT_POINTS = 'Очки характеристик';
private const MONEY = 'Деньги';
private const MONEY_IN_BANK = self::MONEY . ' в банке';
private const EVASION = 'Уворот';
private const ACCURACY = 'Точность';
private const CRITICALS = 'Шанс крита';
private const DAMAGE = 'Урон';
private const LOCATION = 'Локация';
use Rooms;
/**
@ -16,12 +35,12 @@ class UserInfo extends UserStats
*
* @param int $isBattle установить 1, если куклу нужно отобразить в поединке (показывает параметры при наведении
* на образ).
* @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает
* @param int $isMain установить 1, если куклу надо показать на странице игрока (по клику на предмет снимает
* его).
*
* @throws GameException
*/
private function UserInfoDoll(int $isBattle = 0, int $isMain = 0): string
private function userInfoDoll(int $isBattle = 0, int $isMain = 0): string
{
$di = new DressedItems($this->id);
$stats = new UserStats($this->id);
@ -31,11 +50,21 @@ class UserInfo extends UserStats
$str .= sprintf('<div class="slot-%s">', $i);
if (!empty($dressedItems->$i)) {
if (!$isBattle && $isMain) {
$str .= sprintf('<a href="?edit=%s&drop=%s"><img src="/i/sh/%s" class="item-wrap-normal" alt="%s" title="%s"></a>',
mt_rand(), $i, $dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name);
$str .= sprintf(
'<a href="?edit=%s&drop=%s"><img src="/i/sh/%s" class="item-wrap-normal" alt="%s" title="%s"></a>',
mt_rand(),
$i,
$dressedItems->$i->image,
$dressedItems->$i->name,
$dressedItems->$i->name
);
} else {
$str .= sprintf('<img src="/i/sh/%s" class="item-wrap-normal tip" alt="%s"><span class="tiptext"><strong>%s</strong></span>',
$dressedItems->$i->image, $dressedItems->$i->name, $dressedItems->$i->name);
$str .= sprintf(
'<img src="/i/sh/%s" class="item-wrap-normal tip" alt="%s"><span class="tiptext"><strong>%s</strong></span>',
$dressedItems->$i->image,
$dressedItems->$i->name,
$dressedItems->$i->name
);
}
} else {
$str .= sprintf('<img src="/i/sh/noitem.png" class="item-wrap-normal" title="Пустой слот [%s]" alt="Пустой слот [%s]">', $i, $i);
@ -43,47 +72,42 @@ class UserInfo extends UserStats
$str .= sprintf('</div><!-- slot-%s -->', $i);
}
$str .= '<div class="slot-image">';
$str .= '<img src="/i/shadow/' . $this->shadow . '" alt="' . $this->login;
if ($isBattle) {
$str .= sprintf('<img src="/i/shadow/%s" alt="%s" class="tip"><span class="tiptext"><b>%s</b>Уровень: %s<br>Сила: %s<br>Ловкость: %s<br>Интуиция: %s<br>Выносливость: %s<br>Интеллект: %s<br>Мудрость: %s</span>',
$this->shadow, $stats->getLogin(), $stats->getLogin(), $stats->getLevel(), $stats->getStat('strength'), $stats->getStat('dexterity'), $stats->getStat('intuition'), $stats->getStat('endurance'), $stats->getStat('intelligence'), $stats->getStat('wisdom'));
unset($sh);
$str .= '" class = "tip">';
$str .= '<span class="tiptext"><b>' . $stats->getLogin() . '</b>';
$str .= self::LEVEL . ': ' . $stats->getLevel();
$str .= '<br>' . self::STRENGTH . ': ' . $stats->getStat('strength');
$str .= '<br>' . self::DEXTERITY . ': ' . $stats->getStat('dexterity');
$str .= '<br>' . self::INTUITION . ': ' . $stats->getStat('intuition');
$str .= '<br>' . self::ENDURANCE . ': ' . $stats->getStat('endurance');
$str .= '<br>' . self::INTELLIGENCE . ': ' . $stats->getStat('intelligence');
$str .= '<br>' . self::WISDOM . ': ' . $stats->getStat('wisdom');
$str .= '</span>';
} else {
$str .= '<img src="/i/shadow/' . $this->shadow . '" alt="' . $this->login . '">';
$str .= '">';
}
$str .= '</div><!-- slot-image -->';
return $str;
}
public function test(): array
{
return [
'Сила' => $this->strength,
'Ловкость' => $this->dexterity,
'Интуиция' => $this->intuition,
'Выносливость' => $this->endurance,
'Интеллект' => $this->intelligence,
'Мудрость' => $this->wisdom,
];
}
/** Вызов из inf.php */
private function ttz(): string
{
$stat = $this->getFullStats();
$arr = [
'Уровень' => $this->level,
'Сила' => $this->strength,
'Ловкость' => $this->dexterity,
'Интуиция' => $this->intuition,
'Выносливость' => $this->endurance,
'Интеллект' => $this->intelligence,
'Мудрость' => $this->wisdom,
'Уворот' => $stat->evasion,
'Точность' => $stat->accuracy,
'Шанс крита' => $stat->criticals,
'Урон' => $stat->min_physical_damage . ' - ' . $stat->max_physical_damage,
'Локация' => Rooms::$roomNames[$this->room],
self::LEVEL => $this->level,
self::STRENGTH => $this->strength,
self::DEXTERITY => $this->dexterity,
self::INTUITION => $this->intuition,
self::ENDURANCE => $this->endurance,
self::INTELLIGENCE => $this->intelligence,
self::WISDOM => $this->wisdom,
self::EVASION => $stat->evasion,
self::ACCURACY => $stat->accuracy,
self::CRITICALS => $stat->criticals,
self::DAMAGE => $stat->min_physical_damage . ' - ' . $stat->max_physical_damage,
self::LOCATION => Rooms::$roomNames[$this->room],
];
$str = null;
@ -102,13 +126,13 @@ class UserInfo extends UserStats
);
}
private function showProgressBar(int $value, int $max_value)
private function showProgressBar(int $value, int $maxValue)
{
$values = [
'%20%' => (int)round(self::PERCENT_20 * $max_value),
'%80%' => (int)round(self::PERCENT_80 * $max_value),
'%20%' => (int)round(self::PERCENT_20 * $maxValue),
'%80%' => (int)round(self::PERCENT_80 * $maxValue),
'%value' => $value,
'%max' => $max_value
'%max' => $maxValue
];
$string = '<meter max="%max" low="%20%" high="%80%" optimum="%max" value="%value">%value / %max</meter>';
return str_replace(array_keys($values), array_values($values), $string);
@ -117,60 +141,57 @@ class UserInfo extends UserStats
/** Для вызова из main.php
* @throws GameException
*/
private function UserInfoStats(): string
private function userInfoStats(): string
{
$captions = 'Уровень:<br>Здоровье:<br>Пыль:
<br>Сила:<br>Ловкость:<br>Интуиция:<br>Выносливость:<br>Интеллект:<br>Мудрость:
<br>Опыт:<br>Очки характеристик:<br>Деньги:<br>Деньги в банке:
';
$variables =
$this->level . '<br>' .
$this->showProgressBar($this->health, $this->maxHealth) . '<br>' .
$this->showProgressBar($this->mana, $this->maxMana) . '<br>' .
parent::getStat('strength', 1) . '<br>' .
parent::getStat('dexterity', 1) . '<br>' .
parent::getStat('intuition', 1) . '<br>' .
parent::getStat('endurance', 1) . '<br>' .
parent::getStat('intelligence', 1) . '<br>' .
parent::getStat('wisdom', 1) . '<br>' .
$this->experience . '<br>' .
$this->free_stat_points . '<br>' .
User::getInstance()->money()->get() . '<br>' .
User::getInstance()->money()->getBank();
$data = [
self::LEVEL => $this->level,
self::HEALTH => $this->showProgressBar($this->health, $this->maxHealth),
self::MANA => $this->showProgressBar($this->mana, $this->maxMana),
self::STRENGTH => parent::getStat('strength', 1),
self::DEXTERITY => parent::getStat('dexterity', 1),
self::INTUITION => parent::getStat('intuition', 1),
self::ENDURANCE => parent::getStat('endurance', 1),
self::INTELLIGENCE => parent::getStat('intelligence', 1),
self::WISDOM => parent::getStat('wisdom', 1),
self::EXPERIENCE => $this->experience,
self::FREE_STAT_POINTS => $this->freeStatPoints,
self::MONEY => User::getInstance()->money()->get(),
self::MONEY_IN_BANK => User::getInstance()->money()->getBank(),
];
$nameString = Nick::id($this->id)->full();
$str = '<div class="user-info">';
$str .= '<div class="info"><b>' . Nick::id($this->id)->full() . '</b></div><!-- info -->';
$str .= '<div class="stats-container">';
foreach ($data as $caption => $variable) {
$str .= '<div class="column" style="float: left;">' . $caption . '</div><!-- column -->';
$str .= '<div class="column">' . $variable . '</div><!-- column -->';
}
$str .= '</div><!-- stats-container -->';
$str .= '</div><!-- user-info -->';
return <<<HTML
<div class="user-info">
<div class="info"><b>$nameString</b></div><!-- info -->
<div class="stats-container">
<div class="column" style="float: left;">$captions</div><!-- column -->
<div class="column">$variables</div><!-- column -->
</div><!-- stats-container -->
</div><!-- user-info -->
HTML;
return $str;
}
public function userInfoStatsTest(): array
{
$stat = $this->getFullStats();
return [
'Сила' => $this->strength,
'Ловкость' => $this->dexterity,
'Интуиция' => $this->intuition,
'Выносливость' => $this->endurance,
'Интеллект' => $this->intelligence,
'Мудрость' => $this->wisdom,
'<br>HP' => $this->health . ' / ' . $this->maxHealth,
'MP' => $this->mana . ' / ' . $this->maxMana,
'Уворот' => $stat->evasion,
'Точность' => $stat->accuracy,
'Шанс крита' => $stat->criticals,
'Урон' => $stat->min_physical_damage . ' - ' . $stat->max_physical_damage,
'<br>Уровень' => $this->level,
'Опыт' => $this->experience,
'Деньги' => $this->money()->get(),
'<br>Локация' => Rooms::$roomNames[$this->room],
self::STRENGTH => $this->strength,
self::DEXTERITY => $this->dexterity,
self::INTUITION => $this->intuition,
self::ENDURANCE => $this->endurance,
self::INTELLIGENCE => $this->intelligence,
self::WISDOM => $this->wisdom,
'<br>' . self::HEALTH => $this->health . ' / ' . $this->maxHealth,
self::MANA => $this->mana . ' / ' . $this->maxMana,
self::EVASION => $stat->evasion,
self::ACCURACY => $stat->accuracy,
self::CRITICALS => $stat->criticals,
self::DAMAGE => $stat->min_physical_damage . ' - ' . $stat->max_physical_damage,
'<br>' . self::LEVEL => $this->level,
self::EXPERIENCE => $this->experience,
self::MONEY => $this->money()->get(),
'<br>' . self::LOCATION => Rooms::$roomNames[$this->room],
];
}
@ -188,7 +209,7 @@ HTML;
$str .= "<span class='error'>Персонаж $this->login обезличен $hidden.</span>";
} else {
$str .= '<div class="user-info-container">';
$str .= $this->UserInfoDoll();
$str .= $this->userInfoDoll();
$str .= $this->ttz();
$str .= '<div class="slot-lower" style="font-size: xxx-large">' . $this->showProgressBar($this->health, $this->maxHealth) . '<br>' . $this->showProgressBar($this->mana, $this->maxMana) . '</div>';
$str .= '</div><!-- u-i-c -->';
@ -208,7 +229,7 @@ HTML;
public function showUserDoll($isBattle = 0, $isMain = 0): string
{
try {
return '<div class="user-info-container">' . $this->UserInfoDoll($isBattle, $isMain) . '</div><!-- u-i-c -->';
return '<div class="user-info-container">' . $this->userInfoDoll($isBattle, $isMain) . '</div><!-- u-i-c -->';
} catch (GameException $e) {
return $e;
}
@ -219,7 +240,7 @@ HTML;
public function showUserInfoMain(): string
{
try {
return '<div class="user-doll-container">' . $this->UserInfoDoll() . '</div><!-- user-doll-container -->' . $this->userInfoStats();
return '<div class="user-doll-container">' . $this->userInfoDoll() . '</div><!-- user-doll-container -->' . $this->userInfoStats();
} catch (GameException $e) {
return $e;
}
@ -242,4 +263,4 @@ HTML;
}
return $r;
}
}
}

View File

@ -7,13 +7,13 @@ use Battles\Database\Db;
class UserMoney
{
private int $uid;
private int $wallet_money;
private int $walletMoney;
private Bank $bank;
public function __construct(int $uid, int $money)
{
$this->uid = $uid;
$this->wallet_money = $money;
$this->walletMoney = $money;
$this->initBank();
}
@ -24,12 +24,12 @@ class UserMoney
public function get(): int
{
return $this->wallet_money;
return $this->walletMoney;
}
public function set(int $money)
{
$this->wallet_money = max($money, 0);
$this->walletMoney = max($money, 0);
}
public function getBank(): int
@ -44,14 +44,14 @@ class UserMoney
private function save()
{
Db::getInstance()->execute('update users set money = ? where id = ?', [$this->wallet_money, $this->uid]);
Db::getInstance()->execute('update users set money = ? where id = ?', [$this->walletMoney, $this->uid]);
}
/** Тратим деньги */
public function spend(int $value): bool
{
if ($this->wallet_money > $value && $value > 0) {
$this->wallet_money -= $value;
if ($this->walletMoney > $value && $value > 0) {
$this->walletMoney -= $value;
$this->save();
return true;
}
@ -64,8 +64,8 @@ class UserMoney
if ($value <= 0) {
return false;
}
$this->wallet_money += $value;
$this->walletMoney += $value;
$this->save();
return true;
}
}
}

View File

@ -9,11 +9,12 @@ class UserPrivateInfo
/** Блок информации для модераторов. */
public static function get(User $user)
{
$log = '';
$userLogs = GameLogs::getUserLogs($user->getId());
$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']);
foreach ($userLogs as $row) {
$log .= sprintf('<code>%s</code><br>', date('d.m.Y H:i ', strtotime($row['date'])) . $row['text']);
}
$data = [
'%email' => $user->profile()->getEmail(),
'%bday' => date('d.m.Y', strtotime($user->profile()->getBorndate())),
@ -33,4 +34,4 @@ class UserPrivateInfo
</div><!-- secret-info -->';
return str_replace(array_keys($data), array_values($data), $string);
}
}
}

View File

@ -47,10 +47,10 @@ class UserProfile
public function changePassword($old_password, $new_password)
public function changePassword($oldPassword, $newPassword)
{
if (password_verify($old_password, $this->pass)) {
$this->pass = password_hash($new_password, PASSWORD_DEFAULT);
if (password_verify($oldPassword, $this->pass)) {
$this->pass = password_hash($newPassword, PASSWORD_DEFAULT);
} else {
$this->status .= 'Неверный пароль!';
}
@ -160,4 +160,4 @@ class UserProfile
return 'Успешно!';
}
}
}

View File

@ -19,7 +19,7 @@ class UserStats extends User
protected int $wisdom;
protected int $health;
protected int $mana;
protected int $free_stat_points = 0;
protected int $freeStatPoints = 0;
protected int $level;
private const STAT_MAXIMUM_AMOUNT = 40;
private const ERROR_STAT_IS_MAXIMUM = 'Ошибка: Параметр достиг своего лимита!';
@ -54,7 +54,7 @@ class UserStats extends User
$this->wisdom = $data->wisdom;
$this->health = $data->health;
$this->mana = $data->mana;
$this->free_stat_points = $data->free_stat_points;
$this->freeStatPoints = $data->free_stat_points;
$this->level = $data->level;
parent::__construct($user);
$this->maxHealth = round(($this->endurance * 3) + ($this->endurance / 2) * ($this->level - 1) + ($this->endurance / 5) * (($this->level - 1) * ($this->level - 2) / 2));
@ -64,7 +64,7 @@ class UserStats extends User
/**
* Отдаёт информацию о базовом(!) стате.
*
* @param string $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition',
* @param string $statName - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition',
* 'endurance', 'intelligence', 'wisdom'.
* @param int $isMainWindow - переключатель "главного окна". Если включить, дополнительно будет показывать ссылку
* на повышение стата на 1, при условии наличия свободных очков статов.
@ -72,15 +72,15 @@ class UserStats extends User
* @return string
* @throws GameException
*/
public function getStat(string $stat_name, int $isMainWindow = 0): string
public function getStat(string $statName, int $isMainWindow = 0): string
{
if (!in_array($stat_name, self::STAT_NAMES_ARRAY)) {
if (!in_array($statName, self::STAT_NAMES_ARRAY)) {
throw new GameException(self::ERROR_STAT_UNKNOWN);
}
$stat = strval($this->$stat_name);
if ($this->free_stat_points && $isMainWindow && $this->$stat_name < self::STAT_MAXIMUM_AMOUNT) {
$stat = strval($this->$statName);
if ($this->freeStatPoints && $isMainWindow && $this->$statName < self::STAT_MAXIMUM_AMOUNT) {
$rand = strval(mt_rand());
$stat .= " <a href='/main.php?edit=$rand&ups=$stat_name'>[+]</a>";
$stat .= " <a href='/main.php?edit=$rand&ups=$statName'>[+]</a>";
}
return $stat;
}
@ -89,20 +89,20 @@ class UserStats extends User
* Повышает один из выбранных статов на 1, но не выше self::STAT_MAXIMUM_AMOUNT при условии наличия свободных очков
* статов.
*
* @param string $stat_name - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition',
* @param string $statName - имя стата. Может принимать значения 'strength', 'dexterity', 'intuition',
* 'endurance', 'intelligence', 'wisdom'.
*
* @throws GameException
*/
public function addOnePointToStat(string $stat_name)
public function addOnePointToStat(string $statName)
{
if (!in_array($stat_name, self::STAT_NAMES_ARRAY)) {
if (!in_array($statName, self::STAT_NAMES_ARRAY)) {
throw new GameException(self::ERROR_STAT_UNKNOWN);
}
if ($this->free_stat_points <= 0 || $this->$stat_name >= self::STAT_MAXIMUM_AMOUNT) {
if ($this->freeStatPoints <= 0 || $this->$statName >= self::STAT_MAXIMUM_AMOUNT) {
throw new GameException(self::ERROR_STAT_IS_MAXIMUM);
} else {
Stats::addOne($stat_name, $this->id);
Stats::addOne($statName, $this->id);
}
}
@ -132,7 +132,7 @@ class UserStats extends User
*/
public function getFreeStatPoints()
{
return $this->free_stat_points;
return $this->freeStatPoints;
}
/**
@ -160,12 +160,6 @@ class UserStats extends User
foreach (self::STAT_NAMES_ARRAY as $stat) {
$obj->$stat = max(0, $stats->$stat + $itemBonuses->{'item_' . $stat} + $effectBonuses->{'effect_' . $stat});
}
//$obj->strength = max(0, $stats->strength + $itemBonuses->item_strength + $effectBonuses->effect_strength);
//$obj->dexterity = max(0, $stats->dexterity + $itemBonuses->item_dexterity + $effectBonuses->effect_dexterity);
//$obj->intuition = max(0, $stats->intuition + $itemBonuses->item_intuition + $effectBonuses->effect_intuition);
//$obj->endurance = max(0, $stats->endurance + $itemBonuses->item_endurance + $effectBonuses->effect_endurance);
//$obj->intelligence = max(0, $stats->intelligence + $itemBonuses->item_intelligence + $effectBonuses->effect_intelligence);
//$obj->wisdom = max(0, $stats->wisdom + $itemBonuses->item_wisdom + $effectBonuses->effect_wisdom);
$obj->accuracy = max(0, $itemBonuses->item_accuracy);
$obj->evasion = max(0, $itemBonuses->item_evasion);
$obj->criticals = max(0, $itemBonuses->item_criticals);
@ -177,9 +171,9 @@ class UserStats extends User
public function levelUp(): string
{
$this->level += 1;
$this->free_stat_points += 2;
$this->freeStatPoints += 2;
$this->save();
Chat::addSYSMessage('Внимание, вы получили ' . $this->level . 'уровень. Доступны очки распределения параметров.');
Chat::sendSys('Внимание, вы получили ' . $this->level . 'уровень. Доступны очки распределения параметров.');
return 'Персонаж перешёл на ' . $this->level . 'уровень.';
}
@ -197,9 +191,9 @@ class UserStats extends User
$this->wisdom,
$this->health,
$this->mana,
$this->free_stat_points,
$this->freeStatPoints,
$this->level,
$this->id //where
]);
}
}
}

View File

@ -26,4 +26,4 @@ trait Users
private bool $fuk;
}
}

View File

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

View File

@ -17,11 +17,13 @@ class Register
) {
return 0;
}
Db::getInstance()->execute('insert into users (login,pass,email,borndate,ip,session_id,shadow) values (?,?,?,?,?,?,?)',
[$login, $password, $email, $birthday, $_SERVER['REMOTE_ADDR'], session_id(), '0.png']);
Db::getInstance()->execute(
'insert into users (login,pass,email,borndate,ip,session_id) values (?,?,?,?,?,?)',
[$login, $password, $email, $birthday, $_SERVER['REMOTE_ADDR'], session_id()]
);
$userId = Db::getInstance()->lastInsertId();
Db::getInstance()->execute('insert into online (user_id, login_time, room, real_time) values (?,?,1,?)', [$userId, time(), time()]);
Db::getInstance()->execute('insert into bank (user_id) values ?', $userId);
return $userId;
}
}
}

View File

@ -5,6 +5,7 @@
* Project name: Battles-Game
*/
use Battles\Chat;
use Battles\Database\Db;
use Battles\Travel;
use Battles\User;
@ -76,17 +77,17 @@ function savecavedata($cavedata, $caveleader, $floor)
*
* @param $current - Текущее значение.
* @param $maximum - Максимальное значение.
* @param string $line_color - Цвет полоски прогрессбара.
* @param string $bg_color - Фон прогрессбара.
* @param string $lineColor - Цвет полоски прогрессбара.
* @param string $bgColor - Фон прогрессбара.
*
* @return string
*/
function showProgressBar($current, $maximum, string $line_color = 'limegreen', string $bg_color = 'silver'): string
function showProgressBar($current, $maximum, string $lineColor = 'limegreen', string $bgColor = 'silver'): string
{
$bar = round($current / $maximum * 100);
return <<<HTML
<div style="width: 100%; height: 16px; background: $bg_color; overflow: hidden; border-radius: 3px;">
<div style="height: 16px; background: $line_color; border-radius: 3px; width: $bar%;"></div>
<div style="width: 100%; height: 16px; background: $bgColor; overflow: hidden; border-radius: 3px;">
<div style="height: 16px; background: $lineColor; border-radius: 3px; width: $bar%;"></div>
</div>
<div style="width: 100%; height: 16px; font-size: 14px; text-align: center; margi
n-top: -16px;">
@ -105,26 +106,25 @@ HTML;
*/
function echoscroll($slot): string
{
$all_magic = 0;
$allMagic = 0;
if (User::getInstance()->getBattle()) {
$script = 'fbattle';
$all_magic = Db::getInstance()->fetchColumn('select magic from battle where id = ?', User::getInstance()->getBattle());
$all_magic = unserialize($all_magic);
$allMagic = Db::getInstance()->fetchColumn('select magic from battle where id = ?', User::getInstance()->getBattle());
$allMagic = unserialize($allMagic);
} else {
$script = 'main';
}
$dress = Db::getInstance()->fetch('select magic, name, image, durability from inventory where item_id - ?', User::getInstance()->$slot);
$need_charge = Db::getInstance()->fetchColumn('select needcharge from magic where id = ?', $dress['magic']);
$dress = Db::getInstance()->fetch('select magic, name, image, durability from inventory where item_id = ?', User::getInstance()->$slot);
$needCharge = Db::getInstance()->fetchColumn('select needcharge from magic where id = ?', $dress['magic']);
$str = null;
if ((User::getInstance()->$slot > 0) && ($all_magic[User::getInstance()->getId()] < 1 || empty($need_charge))) {
if ((User::getInstance()->$slot > 0) && ($allMagic[User::getInstance()->getId()] < 1 || empty($needCharge))) {
$row['id'] = User::getInstance()->$slot;
if ($dress['magic']) {
$magic_targeted = Db::getInstance()->fetchColumn('select targeted from magic where id = ?', $dress['magic']);
$magicTargeted = Db::getInstance()->fetchColumn('select targeted from magic where id = ?', $dress['magic']);
$str .= "<a onclick=\"";
if ($magic_targeted === 1) {
if ($magicTargeted === 1) {
$str .= "okno('Введите название предмета', '" . $script . ".php?use={$row['id']}', 'target'); ";
} else
if ($magic_targeted === 2) {
} elseif ($magicTargeted === 2) {
$str .= "findlogin('Введите имя персонажа', '" . $script . ".php?use={$row['id']}', 'target'); ";
} else {
$str .= "if(confirm('Использовать сейчас?')) { window.location='" . $script . ".php?use=" . $row['id'] . "';}";
@ -134,7 +134,7 @@ function echoscroll($slot): string
$str .= <<<ACTIVE_SCROLL
<img class='tooltip' src="i/sh/{$dress['img']}" width='40' title="<b>{$dress['name']}</b><br> Прочность {$dress['duration']} / {$dress['maxdur']} " height='25' alt="Свиток"></a>
ACTIVE_SCROLL;
} elseif ((User::getInstance()->$slot > 0) && ($all_magic[User::getInstance()->getId()] >= 1) && $need_charge['needcharge'] > 0) {
} elseif ((User::getInstance()->$slot > 0) && ($allMagic[User::getInstance()->getId()] >= 1) && $needCharge['needcharge'] > 0) {
$str .= <<<INACTIVE_SCROLL
<img src="i/sh/magicclock.gif" width="40" height="25" title='Произведите размен ударами и магия снова станет доступна' alt="Свиток">
INACTIVE_SCROLL;
@ -176,12 +176,26 @@ function addActions($time, $vars, $vls, $uid)
* по нескольку раз вызывают эти функции.
*/
function addch($text, $room = 0)
/**
* @param $text
* @param $room
* @param $smth
* @return void
* @deprecated use Chat::sendSys($msg) instead.
*/
function addch($text, $room = 0, $smth = null)
{
Chat::sendSys($text);
}
/**
* @param $text
* @param $who
* @param $room
* @return void
* @deprecated use Chat::sendSys($msg, $receiverId) instead.
*/
function addchp($text, $who, $room = 0)
{
Chat::sendSys($text, $who);
@ -200,9 +214,8 @@ function err($t)
*/
function telegraph(int $userId, string $text)
{
$userExists = Db::getInstance()->fetchColumn('select count(*) from users where id = ?', $userId) > 0;
if ($userExists) {
Db::getInstance()->execute('INSERT INTO chat (user_id,receiver_id,msg,type) VALUES (-1,?,?,?)', [$userId, $text, 'sms']);
if (User::getInstance($userId)->getId() > 0) {
Chat::sendTelegraf($text, $userId);
}
}
@ -334,4 +347,4 @@ function SolveExp($at_id, $def_id, $damage): float
}
return round((($baseexp[$defInfo->getLevel()]) * ($defAllPrice / (($atAllPrice + $defAllPrice) / 2)) * ($damage / $defInfo->getMaxHealth()) * $expmf * $mfit * $mfbot * $mfbot2) / 3);
}
}

View File

@ -32,7 +32,7 @@ Template::header('Подземелье Луки');
</div>
</TD>
<TD>
<i>
<em>
<?php
$gag = Db::getInstance()->fetchAll('select * from qwest where login = ?', User::getInstance()->getLogin());
foreach ($gag as $qw) {
@ -74,7 +74,7 @@ Template::header('Подземелье Луки');
$item_name = 'Гайка ловкости';
}
if ($ok_qwest == 1 && ($_GET['d'] == 1.3 || $_GET['d'] == 1.4)) {
Db::getInstance()->execute($query, [User::getInstance()->getId(), $item_name, 3, 30, Item::ITEM_TYPE_AMULET, 20]);
Db::getInstance()->execute($query, [User::getInstance()->getId(), $item_name, 3, 30, Item::TYPE_AMULET, 20]);
$query = 'delete from inventory where owner_id = ? and item_type = 200 and name = ?';
Db::getInstance()->execute($query, [User::getInstance()->getId(), QUEST_ITEM_NAME['k']]);
$query = 'update qwest set status = ? where name_qwest = ? and login = ?';
@ -221,7 +221,7 @@ Template::header('Подземелье Луки');
}
}
?>
</i><BR><BR>
</em><BR><BR>
<?php
//Вопросы)
if (!isset($_GET['d'])) {
@ -296,6 +296,5 @@ Template::header('Подземелье Луки');
</TD>
</TR>
</TABLE>
<!-- <DIV ID=oMenu CLASS=menu onmouseout="closeMenu()"></DIV> -->
<DIV ID="oMenu" style="position:absolute; border:1px solid #666; background-color:#CCC; display:none; "></DIV>
<TEXTAREA ID=holdtext STYLE="display:none;"></TEXTAREA>
<label for=holdtext></label><TEXTAREA ID=holdtext STYLE="display:none;"></TEXTAREA>

View File

@ -29,18 +29,18 @@ Template::header('Магазин');
</div>
<hr>
<div>Отделы магазина</div>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_WEAPON ?>&rnd=<?= mt_rand() ?>">Оружие</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_HELMET ?>&rnd=<?= mt_rand() ?>">Шлемы</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_ARMOR ?>&rnd=<?= mt_rand() ?>">Броня</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_LEGS ?>&rnd=<?= mt_rand() ?>">Поножи</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_BOOTS ?>&rnd=<?= mt_rand() ?>">Сапоги</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_GLOVES ?>&rnd=<?= mt_rand() ?>">Перчатки</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_SHIELD ?>&rnd=<?= mt_rand() ?>">Щиты</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_BELT ?>&rnd=<?= mt_rand() ?>">Пояса</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_RING ?>&rnd=<?= mt_rand() ?>">Кольца</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_AMULET ?>&rnd=<?= mt_rand() ?>">Амулеты</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_CONSUMABLE ?>&rnd=<?= mt_rand() ?>">Расходники</a>
<a class="waretype" href="?otdel=<?= Item::ITEM_TYPE_OTHER ?>&rnd=<?= mt_rand() ?>">Разное</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_WEAPON ?>&rnd=<?= mt_rand() ?>">Оружие</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_HELMET ?>&rnd=<?= mt_rand() ?>">Шлемы</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_ARMOR ?>&rnd=<?= mt_rand() ?>">Броня</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_LEGS ?>&rnd=<?= mt_rand() ?>">Поножи</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_BOOTS ?>&rnd=<?= mt_rand() ?>">Сапоги</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_GLOVES ?>&rnd=<?= mt_rand() ?>">Перчатки</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_SHIELD ?>&rnd=<?= mt_rand() ?>">Щиты</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_BELT ?>&rnd=<?= mt_rand() ?>">Пояса</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_RING ?>&rnd=<?= mt_rand() ?>">Кольца</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_AMULET ?>&rnd=<?= mt_rand() ?>">Амулеты</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_CONSUMABLE ?>&rnd=<?= mt_rand() ?>">Расходники</a>
<a class="waretype" href="?otdel=<?= Item::TYPE_OTHER ?>&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>
@ -50,4 +50,4 @@ Template::header('Магазин');
с вычетом банковской комиссии за услуги.</small>
</div>
</div>
</div>
</div>