Merge branch 'dev' into dev-moderation

This commit is contained in:
Ivor Barhansky 2023-12-01 23:37:51 +02:00
commit c487c8b465
17326 changed files with 64515 additions and 187313 deletions

80
.gitignore vendored
View File

@ -1 +1,79 @@
/.idea/
# ---> JetBrains
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio, WebStorm and Rider
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
# User-specific stuff
.idea/**/workspace.xml
.idea/**/tasks.xml
.idea/**/usage.statistics.xml
.idea/**/dictionaries
.idea/**/shelf
# AWS User-specific
.idea/**/aws.xml
# Generated files
.idea/**/contentModel.xml
# Sensitive or high-churn files
.idea/**/dataSources/
.idea/**/dataSources.ids
.idea/**/dataSources.local.xml
.idea/**/sqlDataSources.xml
.idea/**/dynamic.xml
.idea/**/uiDesigner.xml
.idea/**/dbnavigator.xml
# Gradle
.idea/**/gradle.xml
.idea/**/libraries
# Gradle and Maven with auto-import
# When using Gradle or Maven with auto-import, you should exclude module files,
# since they will be recreated, and may cause churn. Uncomment if using
# auto-import.
# .idea/artifacts
# .idea/compiler.xml
# .idea/jarRepositories.xml
# .idea/modules.xml
# .idea/*.iml
# .idea/modules
# *.iml
# *.ipr
# CMake
cmake-build-*/
# Mongo Explorer plugin
.idea/**/mongoSettings.xml
# File-based project format
*.iws
# IntelliJ
out/
# mpeltonen/sbt-idea plugin
.idea_modules/
# JIRA plugin
atlassian-ide-plugin.xml
# Cursive Clojure plugin
.idea/replstate.xml
# SonarLint plugin
.idea/sonarlint/
# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties
# Editor-based Rest Client
.idea/httpRequests
# Android studio 3.1+ serialized cache file
.idea/caches/build_file_checksums.ser

660
AI.php
View File

@ -1,224 +1,486 @@
<?php
/*
use Core\Db;
use Helper\Conversion;
use Item\Data\Bonuses;
use Item\Data\Properties;
use Item\Data\Requirements;
use Model\Constant\ShopOtdel;
Ядро для обработки данных.
Обработка поединков, обработка заявок, обработка ботов, обработка пещер, обработка турниров, обработка временных генераций
ini_set('xdebug.var_display_max_depth', 10);
ini_set('xdebug.var_display_max_children', 256);
ini_set('xdebug.var_display_max_data', 1024);
*/
use User\UserIp;
if (isset($_GET['m1'])) {
define('GAME', true);
include_once '_incl_data/__config.php';
include_once '_incl_data/class/__db_connect.php';
$sp = mysql_query('SELECT * FROM `users_recombats` WHERE `email` != "" ORDER BY `name` DESC LIMIT 7000');
while ($pl = mysql_fetch_array($sp)) {
echo "<br>" . $pl['email'];
}
} elseif (isset($_GET['bk1'])) {
define('GAME', true);
include('_incl_data/__config.php');
include('_incl_data/class/__db_connect.php');
$u = User::start();
$ins = 'Вещи БК-1:<hr>';
$sp = mysql_query('SELECT * FROM `items_main` WHERE `geni` = 1');
while ($pl = mysql_fetch_array($sp)) {
$po = mysql_fetch_array(
mysql_query('SELECT * FROM `items_main_data` WHERE `items_id` = "' . $pl['id'] . '" LIMIT 1')
);
$po = ConversionHelper::dataStringToArray($po['data']);
if (!isset($po['add_minAtack']) && isset($po['sv_minAtack'])) {
$po['add_minAtack'] = $po['sv_minAtack'];
$po['add_maxAtack'] = $po['sv_maxAtack'];
}
$ins .= 'INSERT INTO `items_main` (
`id`, `name`, `img`, `art`, `type`, `inslot`, `use_magic`, `price`, `price2`, `iznosMAXi`, `massa`, `tr_level`, `tr_s1`, `tr_s2`, `tr_s3`, `tr_s4`, `tr_s5`, `tr_s6`, `add_s1`, `add_s2`, `add_s3`, `add_s4`, `add_s5`, `add_s6`, `add_hp`, `add_mp`, `add_m1`, `add_m2`, `add_m3`, `add_m4`, `add_b1`, `add_b2`, `add_b3`, `add_b4`, `add_attack_min`, `add_attack_max`
,`tr_a1`,`tr_a2`,`tr_a3`,`tr_a4`,`tr_mg1`,`tr_mg2`,`tr_mg3`,`tr_mg4`,`tr_mg5`,`tr_mg6`,`tr_mg7`
,`add_a1`,`add_a2`,`add_a3`,`add_a4`,`add_mg1`,`add_mg2`,`add_mg3`,`add_mg4`,`add_mg5`,`add_mg6`,`add_mg7`
) VALUES ';
$ins .= '(
NULL,
"' . $pl['name'] . '",
"' . $pl['img'] . '",
"' . (0 + round($po['art'])) . '",
"' . $pl['type'] . '",
"' . $pl['inslot'] . '",
"",
"' . $pl['price1'] . '",
"' . $pl['price2'] . '",
"' . $pl['iznosMAXi'] . '",
"' . $pl['massa'] . '",
"' . (0 + round($po['tr_lvl'])) . '",
"' . (0 + round($po['tr_s1'])) . '",
"' . (0 + round($po['tr_s2'])) . '",
"' . (0 + round($po['tr_s3'])) . '",
"' . (0 + round($po['tr_s4'])) . '",
"' . (0 + round($po['tr_s5'])) . '",
"' . (0 + round($po['tr_s6'])) . '",
"' . (0 + round($po['add_s1'])) . '",
"' . (0 + round($po['add_s2'])) . '",
"' . (0 + round($po['add_s3'])) . '",
"' . (0 + round($po['add_s4'])) . '",
"' . (0 + round($po['add_s5'])) . '",
"' . (0 + round($po['add_s6'])) . '",
"' . (0 + round($po['add_hpAll'])) . '",
"' . (0 + round($po['add_mpAll'])) . '",
"' . (0 + round($po['add_m1'])) . '",
"' . (0 + round($po['add_m2'])) . '",
"' . (0 + round($po['add_m3'])) . '",
"' . (0 + round($po['add_m4'])) . '",
"' . (0 + round($po['add_mib1'])) . '",
"' . (0 + round($po['add_mib2'])) . '",
"' . (0 + round($po['add_mib3'])) . '",
"' . (0 + round($po['add_mib4'])) . '",
"' . (0 + round($po['add_minAtack'])) . '",
"' . (0 + round($po['add_maxAtack'])) . '",
"' . (0 + round($po['tr_a1'])) . '",
"' . (0 + round($po['tr_a2'])) . '",
"' . (0 + round($po['tr_a3'])) . '",
"' . (0 + round($po['tr_a4'])) . '",
"' . (0 + round($po['tr_mg1'])) . '",
"' . (0 + round($po['tr_mg2'])) . '",
"' . (0 + round($po['tr_mg3'])) . '",
"' . (0 + round($po['tr_mg4'])) . '",
"' . (0 + round($po['tr_mg5'])) . '",
"' . (0 + round($po['tr_mg6'])) . '",
"' . (0 + round($po['tr_mg7'])) . '",
"' . (0 + round($po['add_a1'])) . '",
"' . (0 + round($po['add_a2'])) . '",
"' . (0 + round($po['add_a3'])) . '",
"' . (0 + round($po['add_a4'])) . '",
"' . (0 + round($po['add_mg1'])) . '",
"' . (0 + round($po['add_mg2'])) . '",
"' . (0 + round($po['add_mg3'])) . '",
"' . (0 + round($po['add_mg4'])) . '",
"' . (0 + round($po['add_mg5'])) . '",
"' . (0 + round($po['add_mg6'])) . '",
"' . (0 + round($po['add_mg7'])) . '"
);';
$ins .= "\n" . '<br>';
}
echo $ins;
die();
if (!defined('GAME_VERSION')) {
require_once '_incl_data/autoload.php';
}
if (isset($_GET['test'])) {
$i = 3;
//const GAME = true;
$user = User::start();
//var_dump($user->info['testStats'], $user->info['testStats2']);
//exit();
$im = Db::getColumn("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'items_main'");
$iu = Db::getColumn("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'items_users'");
$u = Db::getColumn("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'users'");
$s = Db::getColumn("SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'stats'");
$p = Db::getRows('select * from const_stats');
var_dump((new ShopOtdel())->getGroups());
?>
function yrn($sila)
{
return 2 + $_GET['test'] + $sila - round($sila / 5);
}
<div style="display: grid; grid-template-columns: 50% 50%; word-wrap: break-word;">
<div>
<b><u>$user->[info]</u></b><br>
<?php
$rr = 1;
foreach ($user->info as $k => $v) {
if (isset($user->is[$k])) {
$k .= " <span style='background-color: lightcyan;'>[{$user->is[$k]}]</span>";
}
if ($k == 'stats') {
echo 'stats = ARRAY<br>';
foreach (Conversion::dataStringToArray($v) as $dk => $dv) {
if (isset($user->is[$dk])) {
$dk .= " <span style='background-color: lightcyan;'>[{$user->is[$dk]}]</span>";
}
echo "<span style='background-color: #99FFCC; margin-left: 5px;'>$dk = $dv</span><br>";
}
$k = '';
$v = '';
}
echo "$rr. $k = $v<br>";
$rr++;
}
?>
</div>
<div>
<b><u>$user->[stats]</u></b><br>
<?php
$rr = 1;
foreach ($user->stats as $k => $v) {
if (isset($user->is[$k])) {
$k .= " <span style='background-color: lightcyan;'>[{$user->is[$k]}]";
} else {
$k = "<span>$k";
}
echo "$rr. $k</span> = $v<br>";
$rr++;
if (is_array($v)) {
foreach ($v as $k2 => $v2) {
echo "<span style='background-color: #99FFCC; margin-left: 5px;'>$k2 = $v2</span><br>";
while ($i <= 100) {
echo '<div';
if ($i == 8 || $i == 13 || $i == 18 || $i == 23) {
echo ' style="background-color:green;color:#fff;"';
} elseif ($i == 7 || $i == 12 || $i == 17 || $i == 22) {
echo ' style="background-color:grey;color:#fff;"';
}
echo '>&nbsp;';
echo $i . ' = ' . yrn($i);
echo '</div>';
if (is_array($v2)) {
foreach ($v2 as $k3 => $v3) {
echo "<span style='background-color: aliceblue; margin-left: 10px;'>$k3 = $v3</span><br>";
if ($k3 === 'data' && $v3 !== '[]') {
$v3 .= '|add_mib2=43';
$itemData = Conversion::dataStringToArray($v3);
echo 'DATA TR_<br>';
foreach ((new Requirements($itemData))->get() as $k => $v) {
echo "$k = $v<br>";
}
echo 'DATA ADD_<br>';
foreach ((new Bonuses($itemData))->get() as $k => $v) {
echo "$k = $v<br>";
}
}
}
}
}
}
}
?>
</div>
</div>
<hr>
Совпадения по параметрам $user->info и $user->stats. Возможно, это ничего не значит, а может и дублирование.<br><br>
<?php
$i = 1;
$i2 = 1;
foreach ($user->info as $a => $b) {
if (isset($user->stats[$a])) {
echo "$i. info = stats: $a = $b<br>";
$i++;
}
die();
}
if (!isset($_GET['robot']) && UserIp::get() != $_SERVER['SERVER_ADDR'] && UserIp::get() != '127.0.0.1' && UserIp::get(
) != '' && UserIp::get() != '31.131.116.166') {
die(UserIp::get() . '<br>' . $_SERVER['SERVER_ADDR']);
}
const GAME = true;
include('_incl_data/__config.php');
include('_incl_data/class/__db_connect.php');
$count = [0, 0, 0, 0, 0, 0];
function inuser_go_btl($id)
{
if (isset($id['id'])) {
file_get_contents(
'/jx/battle/refresh.php?uid=' . $id['id'] . '&cron_core=' . md5(
$id['id'] . '_brfCOreW@!_' . $id['pass']
) . '&pass=' . $id['pass']
);
echo '<br>';
foreach ($user->stats as $a2 => $b2) {
if (isset($user->info[$a2])) {
echo "$i2. stats = info: $a2 = $b2<br>";
$i2++;
}
}
?>
<br>
<div style="display: grid; grid-template-columns: auto auto;">
<div> Поля в базе users
<?php var_dump($u); ?>
</div>
<div> Поля в базе stats
<?php var_dump($s); ?>
</div>
</div>
$sp = mysql_query(
'SELECT `u`.* , `s`.* FROM `stats` AS `s` LEFT JOIN `users` AS `u` ON `u`.`id` = `s`.`id` WHERE `u`.`pass` = "botforpeople" ORDER BY `s`.`nextAct` ASC LIMIT 200'
);
$btltest = [];
<div style="margin-top: 10px; background-color: aliceblue">Отдельно, уже согласованные параметры предметов, которые могут находиться исключительно в поле data</div>
<div style="display: grid; grid-template-columns: auto auto auto; background-color: aliceblue">
<div> sv_* (хотим убрать)
<?php var_dump(Properties::$names); ?>
</div>
</div>
while ($pl = mysql_fetch_array($sp)) {
<div style="display: grid; grid-template-columns: auto auto;">
<div> Поля в базе items_main
<?php var_dump($im); ?>
</div>
<div> Поля в базе items_users
<?php var_dump($iu); ?>
</div>
</div>
$i++;
<hr>
<hr> Параметры игрока.<br><br>
<div style="display: grid; grid-template-columns: auto auto auto;">
<div> Заскриптованные
<?php var_dump($user->is); ?>
</div>
<div> Хотим оставить
if ($pl['zv'] == 0 && ($pl['battle'] == 0 || !isset($btltest[$pl['battle']]) || $btltest[$pl['battle']] < 10)) {
</div>
<div> Хотим убрать
$btltest[$pl['battle']]++;
</div>
</div>
<hr> Все возможные поля в $user->stats. Некоторые имена полей генерируются динамически на лету, поэтому соответствия имени нет. А каких-то, возможно просто не существует.<br><br>
<?php
if ($pl['timereg'] == 0) {
mysql_query('UPDATE `users` SET `timereg` = "' . time() . '" WHERE `id` = "' . $pl['id'] . '" LIMIT 1');
} else {
User::setOnline($pl['id']);
}
$st['clanpos'] = 0;
$st['levels'] = 0;
$st['levels'] = 0;
$st['id'] = 0;
$st['login'] = 0;
$st['lvl'] = 0;
$st['hpNow'] = 0;
$st['hpAll'] = 0;
$st['mpNow'] = 0;
$st['mpAll'] = 0;
$st['zona'] = 0;
$st['zonb'] = 0;
$st['items'] = 0;
$st['effects'] = 0;
$st['reting'] = 0;
$st['vip'] = 0;
$st['items_img'] = 0;
$st['reting'] = 0;
$st['wp'] = 0;
$st['items'] = 0;
$st['reting'] = 0;
$st['art'] = 0;
$st['maks_itm'] = 0;
$st['zonb'] = 0;
$st['zona'] = 0;
$st['a'] = 0;
$st['mg'] = 0;
$st['s'] = 0;
$st['effects'] = 0;
$st['puti'] = 0;
$st['slvtm'] = 0;
$st['act'] = 0;
$st['noeffectbattle1'] = 0;
$st['items_img'] = 0;
$st['set_pog'] = 0;
$st['set_pog2'] = 0;
$st['act'] = 0;
$st['effects'] = 0;
$st['raztac'] = 0;
$st['set_natoe'] = 0;
$st['act'] = 0;
$st['hpAll'] = 0;
$st['s4'] = 0;
$st['mpAll'] = 0;
$st['m1'] = 0;
$st['s3'] = 0;
$st['m2'] = 0;
$st['s6'] = 0;
$st['s3'] = 0;
$st['m4'] = 0;
$st['s2'] = 0;
$st['m5'] = 0;
$st['za'] = 0;
$st['s4'] = 0;
$st['zm'] = 0;
$st['zaproc'] = 0;
$st['s5'] = 0;
$st['m19'] = 0;
$st['s3'] = 0;
$st['antm3'] = 0;
$st['s5'] = 0;
$st['m10'] = 0;
$st['m11'] = 0;
$st['m11a'] = 0;
$st['m8'] = 0;
$st['zona'] = 0;
$st['zonb'] = 0;
$st['pm'] = 0;
$st['a'] = 0;
$st['mg'] = 0;
$st['zm'] = 0;
$st['s5'] = 0;
$st['pm'] = 0;
$st['s5'] = 0;
$st['m11a'] = 0;
$st['pm'] = 0;
$st['a'] = 0;
$st['aall'] = 0;
$st['m2all'] = 0;
$st['mg'] = 0;
$st['m2all'] = 0;
$st['zm'] = 0;
$st['zma'] = 0;
$st['mib'] = 0;
$st['mab'] = 0;
$st['mg'] = 0;
$st['pm'] = 0;
$st['pa'] = 0;
$st['za'] = 0;
$st['mall'] = 0;
$st['mg'] = 0;
$st['mall'] = 0;
$st['m11'] = 0;
$st['pm'] = 0;
$st['m11'] = 0;
$st['m10'] = 0;
$st['pa'] = 0;
$st['m10'] = 0;
$st['za'] = 0;
$st['za'] = 0;
$st['za'] = 0;
$st['yzm'] = 0;
$st['yzma'] = 0;
$st['yza'] = 0;
$st['za'] = 0;
$st['hpVinos'] = 0;
$st['hpAll'] = 0;
$st['s4'] = 0;
$st['mpAll'] = 0;
$st['mpVinos'] = 0;
$st['s6'] = 0;
$st['hpProc'] = 0;
$st['hpAll'] = 0;
$st['mpProc'] = 0;
$st['hpNow'] = 0;
$st['hpAll'] = 0;
$st['hpNow'] = 0;
$st['hpAll'] = 0;
$st['mpNow'] = 0;
$st['mpAll'] = 0;
$st['mpNow'] = 0;
$st['mpAll'] = 0;
$st['zona'] = 0;
$st['zonb'] = 0;
$st['ozash'] = 0;
$st['ozmsh'] = 0;
$st['weapon1'] = 0;
$st['weapon2'] = 0;
$st['sheld1'] = 0;
$st['sv_'] = 0;
$st['sv_i'] = 0;
$st['dom'] = 0;
$st['prsu'] = 0;
$st['x'] = 0;
$st['y'] = 0;
$st['s'] = 0;
$st['reting'] = 0;
$st['reting'] = 0;
$st['maxves'] = 0;
$st['speed_dungeon'] = 0;
$st['speedhp'] = 0;
$st['exp'] = 0;
$st['reting'] = 0;
$st['reting'] = 0;
$st['btl_cof'] = 0;
$st['prckr'] = 0;
$st['btl_cof'] = 0;
$st['prckr'] = 0;
$st['btl_cof'] = 0;
$st['prckr'] = 0;
$st['prckr'] = 0;
$st['id'] = 0;
$st['hpAll'] = 0;
$st['hpAll'] = 0;
$st['mpAll'] = 0;
$st['mpAll'] = 0;
$st['this_animal'] = 0;
$st['this_animal'] = 0;
$st['hpAll'] = 0;
$st['mpAll'] = 0;
$st['hpAll'] = 0;
$st['mpAll'] = 0;
$st['add_'] = 0;
$st['add_'] = 0;
$st['add_'] = 0;
$st['s1'] = 0;
$st['s1'] = 0;
$st['m2'] = 0;
$st['s1'] = 0;
$st['s1'] = 0;
$st['pa2'] = 0;
$st['m2'] = 0;
$st['s1'] = 0;
$st['s1'] = 0;
$st['pa2'] = 0;
$st['m2'] = 0;
$st['s1'] = 0;
$st['s1'] = 0;
$st['pa2'] = 0;
$st['m7'] = 0;
$st['s1'] = 0;
$st['s1'] = 0;
$st['pa2'] = 0;
$st['m7'] = 0;
$st['s1'] = 0;
$st['pa2'] = 0;
$st['m7'] = 0;
$st['s2'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m4'] = 0;
$st['s2'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m2'] = 0;
$st['m4'] = 0;
$st['s2'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m2'] = 0;
$st['m4'] = 0;
$st['m15'] = 0;
$st['s2'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m2'] = 0;
$st['m4'] = 0;
$st['m15'] = 0;
$st['s2'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m2'] = 0;
$st['m4'] = 0;
$st['m15'] = 0;
$st['s2'] = 0;
$st['pa1'] = 0;
$st['m2'] = 0;
$st['m4'] = 0;
$st['m15'] = 0;
$st['s3'] = 0;
$st['s3'] = 0;
$st['pa4'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['s3'] = 0;
$st['s3'] = 0;
$st['pa4'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['s3'] = 0;
$st['s3'] = 0;
$st['pa4'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['m5'] = 0;
$st['s3'] = 0;
$st['s3'] = 0;
$st['pa4'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['m5'] = 0;
$st['s3'] = 0;
$st['s3'] = 0;
$st['pa4'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['m5'] = 0;
$st['m14'] = 0;
$st['m3'] = 0;
$st['m1'] = 0;
$st['m5'] = 0;
$st['m14'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['m19'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['m19'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['za'] = 0;
$st['zm'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['za'] = 0;
$st['zm'] = 0;
$st['s4'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['za'] = 0;
$st['zm'] = 0;
$st['s4'] = 0;
$st['hpAll'] = 0;
$st['za'] = 0;
$st['zm'] = 0;
$st['s5'] = 0;
$st['m11'] = 0;
$st['pzm'] = 0;
$st['s6'] = 0;
$st['mpAll'] = 0;
$st['speedmp'] = 0;
$st['s6'] = 0;
$st['pzm'] = 0;
$st['m10'] = 0;
if ($pl['bot'] == 0) {
mysql_query('UPDATE `stats` SET `bot` = "2" WHERE `id` = "' . $pl['id'] . '" LIMIT 1');
}
User::setOnline($pl['id']);
BotLogic::start($pl['id']);
} else {
if ($pl['zv'] > 0) {
BotLogic::start($pl['id']);
}
if ($pl['timereg'] == 0) {
mysql_query('UPDATE `users` SET `timereg` = "' . time() . '" WHERE `id` = "' . $pl['id'] . '" LIMIT 1');
} else {
User::setOnline($pl['id']);
}
if ($pl['bot'] == 0) {
mysql_query('UPDATE `stats` SET `bot` = "2" WHERE `id` = "' . $pl['id'] . '" LIMIT 1');
}
mysql_query('UPDATE `stats` SET `nextAct` = "' . time() . '" WHERE `id` = "' . $pl['id'] . '" LIMIT 1');
User::setOnline($pl['id']);
echo '*';
$stnames = [];
foreach ($st as $k => $v) {
if (isset($user->is[$k])) {
$v = $user->is[$k];
}
echo '+';
echo '[' . $pl['login'] . '] -> Действие: ' . $pl['ipreg'] . ' , ожидаем: ' . ($pl['timeMain'] - time(
)) . ' сек., заявка: ' . $pl['zv'] . ', поединок: ' . $pl['battle'] . '';
echo '<hr>';
$stnames[$k] = $v;
}
var_dump($stnames);
echo "<h5>Текущая таблица параметров</h5>";
foreach ($p as $prow) {
echo "{$prow['sys_name']}{$prow['name']}";
if ($prow['is_percentage']) {
echo " (%)";
}
if ($prow['is_requirement']) {
echo " <span style='background-color: lightpink;'>[требуется]</span> ";
}
if ($prow['is_bonus']) {
echo " <span style='background-color: lightgreen;'>[даёт]</span> ";
}
echo "<br>";
}

View File

@ -0,0 +1,192 @@
<?php
use Enum\ShopId;
?>
<style>
.wares {
display: grid;
grid-template-columns: 100px auto;
background-color: #d4d4d4;
}
.wares > div:nth-child(odd of .left), .wares > div:nth-child(odd of .left) + div {
background-color: #c8c8c8;
}
table.zerowide {
width: 100%;
border-spacing: 0;
border-collapse: collapse;
}
table.zerowide td {
padding: 0;
}
</style>
<form id="F1" name="F1" method="post"></form>
<table class="zerowide">
<tr>
<td style="vertical-align: top;">
<h3><?= $shopName ?></h3>
<div style="text-align: center; font-weight: bold;"><span style="color: crimson;">&nbsp;<?= $status ?></span></div>
<table class="zerowide">
<tr>
<td style="text-align: left; vertical-align: top; padding: 4px;">
<!--Магазин-->
<div id="hint3" style="visibility:hidden"></div>
<table class="zerowide" style="background-color: darkgrey;">
<tr>
<td style="text-align: center; height: 21px;">
<?php if ($actionSale): ?>
<strong>Отдел «Скупка»</strong><br>
Здесь вы можете продать свои вещи, за жалкие гроши...<br>
У вас в наличии:
<?php elseif ($actionGifts): ?>
<strong>Отдел «Сделать подарки»</strong>
<?php elseif ($shop->shopOtdel->getName($otdel)): ?>
<strong>Отдел «<?= $shop->shopOtdel->getName($otdel) ?>»</strong>
<?php endif; ?>
</td>
</tr>
<tr>
<td>
<!--Рюкзак / Прилавок-->
<table class="zerowide" style="background-color: dimgrey;">
<?php if ($actionGifts): ?>
<tr>
<td style="background-color: #d5d5d5;">
Вы можете сделать подарок дорогому человеку. Ваш подарок будет отображаться в информации о персонаже.
<input name="itemgift" id="itemgift" type="hidden" value="0" form="F1">
<ol>
<li>
Укажите имя персонажа, которому хотите сделать подарок.
<label>Имя <input name="to_login" form="F1"></label>
</li>
<?php if ($u->info['exp'] >= Present::EXP_NEEDED_FOR_ADD_PRESENT_TEXT): ?>
<li>
Поздравление. Будет отображаться в информации о персонаже (не более 60 символов).
<label><input name="podarok2" size="50" maxlength="60" form="F1"></label>
</li>
<li>
Приватное поздравление (в информации о персонаже не отображается).
<label><textarea name="txt" cols="80" rows="6" form="F1"></textarea></label>
</li>
<?php endif; ?>
<li>
Выберите, от чьего имени подарок:<br>
<label style="font-weight: bold;"><input type="radio" name="from" value="0" checked form="F1"> <?= $u->info['login'] ?></label><br>
<label><input type="radio" name="from" value="1" form="F1">анонимно</label><br>
<?php if ($uc->isRegistered()): ?>
<label><input type="radio" name="from" value="2" form="F1">от имени клана <?= $uc->getName() ?></label>
<?php endif; ?>
</li>
<li>
Нажмите кнопку <strong>Подарить</strong> под предметом, который хотите преподнести в подарок:<br>
</li>
</ol>
</td>
</tr>
<?php if ($giftsvars): ?>
<?php foreach ($giftsvars as $k => $v): ?>
<tr>
<td style="text-align: center; background-color: lightgrey;">
<?php if ($k === 0): ?>
<h3>Уникальные подарки</h3>
<?php endif; ?>
<table class="zerowide">
<tr>
<td style="width: 160px; text-align: center; border-right: 1px solid #a5a5a5; padding: 5px;">
<img style="padding-bottom: 5px;" src="<?= $v['img'] ?>" alt=""><br>
<button onclick="document.getElementById('itemgift').value=<?= $v['jsvalue'] ?>;document.getElementById('F1').submit();">
Подарить за <?= $v['money'] ?> кр.
</button>
</td>
<td style="vertical-align: top; border-right: 1px solid #a5a5a5; padding: 5px;">
<a href="/item/0"><?= $v['linkname'] ?></a><br><small>Это именной подарок, его можете подарить только вы.</small>
</td>
</tr>
</table>
</td>
</tr>
<?php endforeach; ?>
<tr>
<td style="text-align: center; background-color: lightgrey;"><h3>Стандартные подарки</h3></td>
</tr>
<?php endif; ?>
<?= $itmAllSee ?>
<?php elseif ($actionSale): ?>
<?= $itmAllSee ?>
<?php else: ?>
<div class="wares">
<?php $shop->printWares(); ?>
</div>
<?php endif; ?>
</table>
</td>
</tr>
</table>
</td>
</tr>
</table>
<td style="width: 280px; vertical-align: top;">
<div style="display: flex; align-items: flex-end; font-size: smaller; flex-direction: column; gap: 2px;">
<?= $goLis; ?>
<?php if ($shopId === ShopId::MAIN): ?>
<button onclick="location.href='main.php?loc=1.180.0.9&rnd=<?= $code; ?>'">Центральная Площадь</button>
<button onclick="location.href='main.php?loc=1.180.0.368&rnd=<?= $code; ?>'">Подпольная лавка</button>
<button onclick="location.href='main.php?loc=1.180.0.13&rnd=<?= $code; ?>'">Магазин «Берёзка»</button>
<?php else: ?>
<button onclick="location.href='main.php?loc=1.180.0.10&rnd=<?= $code; ?>'">Государственный магазин</button>
<?php endif; ?>
</div>
<div>
<div style="display: grid; grid-template-columns: max-content max-content; font-size: smaller; justify-content: end; margin: 10px 0;">
<div style="text-align: right; margin-right: 5px;">Масса:</div>
<div style="font-weight: bold;"><?= $u->aves['now'] ?>/<?= $u->aves['max'] ?></div>
<div style="text-align: right; margin-right: 5px;">У вас в наличии:</div>
<div style="font-weight: bold; color: green"><?= $shop->getUserWallet() ?></div>
</div>
<div style="text-align: center;">
<?php if (!$actionSale): ?>
<INPUT class="btn" TYPE="button" value="Продать вещи" onclick="location='?otdel=<?= $otdel ?>&sale=1'">
<?php else: ?>
<INPUT class="btn" TYPE="button" value="Купить вещи" onclick="location='?otdel=<?= $otdel ?>'">
<?php endif; ?>
&nbsp;
<INPUT class="btn" TYPE="button" value="Обновить" onclick="location = '<?= str_replace('item', '', str_replace('buy', '', $_SERVER['REQUEST_URI'])); ?>';">
</div>
<BR>
</div>
<div style="background-color:#A5A5A5; padding:1px; text-align: center; font-weight: bold;">Отделы магазина</div>
<div style="line-height:17px;">
<?php
/*названия разделов (справа)*/
//$otdels = $shop->getUsedOtdels();
$otdels[37] = "<span style='color: red'>$otdels[37]</span>";
$otdels[100] = 'Сделать подарки';
//$i = 1;
foreach ($otdels as $k => $v) {
$color = $otdel === $k ? '#C7C7C7' : '#e2e0e0';
if (in_array($k, array_keys($shop->shopOtdel->getGroups()))) {
if ($i !== 1) {
echo '<br>';
}
echo sprintf('<div style="background-color: #d5d5d5;"><img src="/i/shop_ico/%s.png" alt="%s"> <strong>%s</strong></div>',
$i, $shop->shopOtdel->getGroups()[$k], $shop->shopOtdel->getGroups()[$k]);
$i++;
}
if ($k === 100) {
echo '<br><div style="background-color: #d5d5d5;"><b>Возможности:</b></div>';
$k = '32&gifts=1';
}
echo '<a href="?otdel=' . $k . '"><div style="background-color: ' . $color . '">&nbsp;&nbsp;' . $v . '</a></div>';
}
?>
</div>
</td>
</table>
<br>
<div id="textgo" style="visibility:hidden;"></div>

View File

@ -1,10 +1,9 @@
<?php
use Core\Config;
use Insallah\Tournaments\Tournament;
error_reporting(E_ALL ^ E_NOTICE);
ini_set('display_errors', 'Off');
//error_reporting(E_ALL);
date_default_timezone_set('Europe/Moscow');
header('Cache-Control: no-cache, no-store, must-revalidate');
@ -13,9 +12,6 @@ header('Expires: 0');
require_once 'mysql_override.php';
// Для всех доработок, пока нет автозагрузки классов.
require_once 'class/Insallah/Config.php';
// Попробуем в автозагрузку.
// Никогда не заработает с такими названиями классов и файлов!
// "На потом."
@ -24,8 +20,8 @@ spl_autoload_register(function ($className) {
# 2 without
$fileName = [
__DIR__ . '/class/' . str_replace('\\', '/', $className . '.php'),
__DIR__ . '/class/' . $className . '.php'
];
__DIR__ . '/class/' . $className . '.php',
];
foreach ($fileName as $file) {
if (file_exists($file)) {
require_once $file;

View File

@ -1,12 +1,12 @@
<?php
//error_reporting(E_ALL);
const GAME = true; // Для совместимости с этой "защитой".
const GAME_VERSION = 'alpha-7.4';
// Новая автозагрузка.
// ВНИМАНИЕ! Не введено в эксплуатацию!
require_once 'mysql_override.php';
require_once 'class/Insallah/Config.php';
spl_autoload_register(function (string $className) {
$rootdir = $_SERVER['DOCUMENT_ROOT'] . '/_incl_data';
@ -14,7 +14,8 @@ spl_autoload_register(function (string $className) {
# 2 without
$fileName = [
$rootdir . '/class/' . str_replace('\\', DIRECTORY_SEPARATOR, $className . '.php'),
$rootdir . '/class/' . $className . '.php'
$rootdir . '/class/' . $className . '.php',
$rootdir . '/vendor/' . $className . '.php',
];
foreach ($fileName as $file) {
if (file_exists($file)) {

View File

@ -1,126 +1,108 @@
<?php
namespace Insallah;
use Core\Db;
use User;
use Helper\Math;
use Helper\Table;
use User\ItemsModel;
class Achievements
{
private User $user;
private $info;
private array $info;
private array $data = [
'zb' => [
'questname' => 'Ежедн.Задания',
'quest' => 'Выполнить задания бабки.',
'check' => ['Заданий', 5, 25, 50, 100, 250],
'prize' => ['Жетон <br>успеха <br>', 5, 20, 40, 60, 100],
'startlink' => 11
'startlink' => 11,
],
'vx' => [
'questname' => 'Хаотические бои',
'quest' => 'Победить в хаотических боях.',
'check' => ['Побед', 50, 300, 400, 500, 1000],
'prize' => ['екр.', 25, 50, 75, 100, 200],
'startlink' => 21
'startlink' => 21,
],
'snt' => [
'questname' => 'Сундук трупожора',
'quest' => 'Открыть сундук трупожора.',
'check' => ['Открытий', 5, 25, 50, 100, 250],
'prize' => ['екр.', 10, 25, 50, 75, 200],
'startlink' => 31
'startlink' => 31,
],
'rp' => [
'questname' => 'Руны 8 лвл.',
'quest' => 'Получить руну при плавке плохих заготовок. [S]',
'check' => ['Рун', 5, 10, 25, 50, 100],
'prize' => ['Плохие <br> заготовки <br>', 5, 7, 10, 12, 15],
'startlink' => 41
'startlink' => 41,
],
'rn' => [
'questname' => 'Руны 9 лвл.',
'quest' => 'Получить руну при плавке нормальных заготовок. [M]',
'check' => ['Рун', 5, 10, 15, 25, 50],
'prize' => ['Нормальные <br> заготовки <br>', 5, 7, 9, 12, 15],
'startlink' => 51
'startlink' => 51,
],
'rb' => [
'questname' => 'Руны 10 лвл.',
'quest' => 'Получить руну при плавке идеальных заготовок. [L]',
'check' => ['Рун', 2, 5, 8, 11, 15],
'prize' => ['Идеальные <br> заготовки <br>', 2, 4, 6, 10, 15],
'startlink' => 61
'startlink' => 61,
],
'pg' => [
'questname' => 'Героич. Сражения',
'quest' => 'Поучаствовать в героическом сражении.',
'check' => ['Участий', 100, 200, 400, 600, 1000],
'prize' => ['Жетон <br>успеха <br>', 10, 20, 40, 60, 80],
'startlink' => 71
'startlink' => 71,
],
'bv' => [
'questname' => 'Продажи Бабушке',
'quest' => 'Продать бабушке найденные вещи в пещере.',
'check' => ['Продаж', 5, 25, 50, 100, 250],
'prize' => ['кр.', 500, 1000, 2000, 4000, 5000],
'startlink' => 81
'startlink' => 81,
],
'kw' => [
'questname' => 'Клан Поединки',
'quest' => 'Победить в клановой войне.',
'check' => ['Побед', 5, 10, 15, 20, 25],
'prize' => ['Свиток <br> кланового<br> опыта ', 1, 2, 5, 10, 15],
'startlink' => 91
'startlink' => 91,
],
'pa' => [ # not implemented!
'questname' => 'Покровительство',
'quest' => 'Получить покровительство Ангела.',
'check' => ['Получено', 5, 25, 50, 100, 250],
'prize' => null,
'startlink' => null
'startlink' => null,
],
'bs' => [
'questname' => 'Башня смерти',
'quest' => 'Победы в башне смерти.',
'check' => ['Побед', 1, 5, 10, 50, 500],
'prize' => ['екр.', 1, 5, 10, 50, 200],
'startlink' => 101
'startlink' => 101,
],
'trn' => [ # not implemented!
'questname' => 'Турниры',
'quest' => 'Поучавствовать в турнирах.',
'check' => ['Побед', 25, 50, 100, 200, 500],
'prize' => ['екр.', 25, 25, 25, 25, 50],
'startlink' => 111
'startlink' => 111,
],
];
public function __construct(User $user)
{
$this->user = $user;
$this->info = Db::getRow('select * from users_achiv where id = ?', [$user->info['id']]);
$this->info = Db::getRow('select * from users_achiv where id = ?', [$user->info['id']]) ?: [];
}
//fixme: сюда иногда приходит (NULL, NULL).
private function prizeName(?int $int, ?string $string): string
{
return in_array($string, ['екр.', 'кр.']) ? $int . ' ' . $string : $string . ' ' . $int;
}
private function drawSunduk($nagr, $whatInside, $tier): string
{
return vsprintf(
'<img onclick="%s" onmouseover="%s" onmouseout="%s" onmousedown="%s" class="cp" src="%s" alt="Сундук">',
[
"location.href='\main.php?titul&nagr=$nagr'",
"top.hi(this, '<b>Сундук $tier ранга<hr>Содержит:<hr> $whatInside</b>', event, 2, 0, 1, 1, 'max-width:307px')",
"top.hic();",
"top.hic();",
"//img.new-combats.tech/i/titul/nagr$tier.gif"
]
);
}
public function getList(): string
{
@ -161,8 +143,8 @@ class Achievements
$this->prizeName($value['prize'][2], $value['prize'][0]),
$this->prizeName($value['prize'][3], $value['prize'][0]),
$this->prizeName($value['prize'][4], $value['prize'][0]),
$this->prizeName($value['prize'][5], $value['prize'][0])
]
$this->prizeName($value['prize'][5], $value['prize'][0]),
],
], 'prizelist', true);
# If has new tier, AND only first 5 tiers AND prize is set.
if (
@ -183,7 +165,7 @@ class Achievements
return $string;
}
private function calculateCurrent($check = null)
private function calculateCurrent($check = null): void
{
$this->info['bs'] = $this->user->info['win_bs'];
foreach ($this->info as $k => $v) {
@ -205,26 +187,46 @@ class Achievements
$this->info["klasP$k"] = Math::get100Percentage($this->data[$k]['check'][1], $this->info[$k]);
for ($i = 1; $i <= 5; $i++) {
if ($this->info[$k] >= $this->data[$k]['check'][$i]) {
$this->info["klas$k"] = $i;
if ($i === 5) {
# На 5 ранге должно отдавать максимум.
$this->info["klasP$k"] = 100;
} else {
$this->info["klasP$k"] = Math::get100Percentage(
$this->data[$k]['check'][$i + 1] - $this->data[$k]['check'][$i],
$this->info[$k] - $this->data[$k]['check'][$i]
);
}
if ($this->info[$k] < $this->data[$k]['check'][$i]) {
continue;
}
$this->info["klas$k"] = $i;
if ($i === 5) {
# На 5 ранге должно отдавать максимум.
$this->info["klasP$k"] = 100;
} else {
$this->info["klasP$k"] = Math::get100Percentage(
$this->data[$k]['check'][$i + 1] - $this->data[$k]['check'][$i],
$this->info[$k] - $this->data[$k]['check'][$i]
);
}
}
}
}
private function prizeName(?int $int, ?string $string): string
{
return in_array($string, ['екр.', 'кр.']) ? $int . ' ' . $string : $string . ' ' . $int;
}
private function drawSunduk($nagr, $whatInside, $tier): string
{
return vsprintf(
'<img onclick="%s" onmouseover="%s" onmouseout="%s" onmousedown="%s" class="cp" src="%s" alt="Сундук">',
[
"location.href='\main.php?titul&nagr=$nagr'",
"top.hi(this, '<b>Сундук $tier ранга<hr>Содержит:<hr> $whatInside</b>', event, 2, 0, 1, 1, 'max-width:307px')",
"top.hic();",
"top.hic();",
"//img.new-combats.tech/i/titul/nagr$tier.gif",
]
);
}
public function getInfo(?int $uid = null)
{
if (!is_null($uid)) {
$this->info = \Core\Db::getRow('select * from users_achiv where id = ?', [$uid]);
$this->info = Db::getRow('select * from users_achiv where id = ?', [$uid]) ?: [];
}
$this->calculateCurrent();
return $this->info;
@ -236,11 +238,6 @@ class Achievements
return $this->info;
}
private function addOne($name)
{
\Core\Db::sql("update users_achiv set $name = $name + 1 where id = ?", [$this->user->info['id']]);
}
public function updateTier($name)
{
if (in_array($name, array_keys($this->data))) {
@ -248,6 +245,11 @@ class Achievements
}
}
private function addOne($name)
{
Db::sql("update users_achiv set $name = $name + 1 where id = ?", [$this->user->info['id']]);
}
public function updateCounter($name)
{
if (in_array($name, array_keys($this->data))) {
@ -271,7 +273,7 @@ class Achievements
public function givePrizeItems($itemId, $aType)
{
for ($i = 1; $i <= $this->data[$aType]['prize'][$this->info[$aType . '_n'] + 1]; $i++) {
$this->user->addItem($itemId, $this->user->info['id']);
ItemsModel::addItem($itemId, $this->user->info['id']);
}
}
@ -279,4 +281,4 @@ class Achievements
{
return array_keys($this->data);
}
}
}

View File

@ -0,0 +1,135 @@
<?php
namespace Admin;
use Core\Db;
readonly class Monster
{
public array $info;
public function __construct(int $monsterid)
{
$this->info = Db::getRow('select * from aaa_monsters where uid = ?', [$monsterid]);
if ($_SERVER['REQUEST_METHOD'] === OAUTH_HTTP_METHOD_POST) {
$this->save();
}
}
private function save(): void
{
$params['uid'] = $this->info['uid'];
$params['start_room'] = (int)$_POST['bot_sroom'];
$params['start_day'] = (int)$_POST['bot_sday'];
$params['start_dd'] = (int)$_POST['bot_sdd'];
$params['start_mm'] = (int)$_POST['bot_smm'];
$params['start_hh'] = (int)$_POST['bot_shh'];
$params['start_min'] = (int)$_POST['bot_smin'];
$params['back_day'] = (int)$_POST['bot_bday'];
$params['back_dd'] = (int)$_POST['bot_bdd'];
$params['back_mm'] = (int)$_POST['bot_bmm'];
$params['back_hh'] = (int)$_POST['bot_bhh'];
$params['back_min'] = (int)$_POST['bot_bmin'];
$params['start_text'] = $_POST['bot_stext'];
$params['back_text'] = $_POST['bot_btext'];
$params['win_text'] = $_POST['bot_wintext'];
$params['lose_text'] = $_POST['bot_losetext'];
$params['nich_text'] = $_POST['bot_nichtext'];
$params['win_back'] = $_POST['bot_winback'];
$params['time_restart'] = $_POST['bot_trs'];
$params['win_itm'] = $_POST['bot_winitm'];
$params['win_money1'] = $_POST['bot_winmoney1'];
$params['win_money2'] = $_POST['bot_winmoney2'];
$params['win_exp'] = $_POST['bot_winexp'];
$params['win_eff'] = $_POST['bot_wineff'];
$params['win_ico'] = $_POST['bot_winico'];
$params['lose_itm'] = $_POST['bot_loseitm'];
$params['lose_money'] = $_POST['bot_losemoney1'];
$params['lose_money2'] = $_POST['bot_losemoney2'];
$params['lose_exp'] = $_POST['bot_loseexp'];
$params['lose_eff'] = $_POST['bot_loseeff'];
$params['lose_ico'] = $_POST['bot_loseico'];
if (!isset(
$params['uid'],
$params['start_room'],
$params['start_day'],
$params['back_day'],
$params['start_dd'],
$params['start_mm'],
$params['start_hh'],
$params['start_min'],
$params['back_min'],
$params['back_dd'],
$params['back_mm'],
$params['back_hh'],
$params['start_text'],
$params['back_text'],
$params['win_text'],
$params['lose_text'],
$params['nich_text'],
$params['win_money1'],
$params['win_money2'],
$params['lose_money'],
$params['lose_money2'],
$params['win_exp'],
$params['lose_exp'],
$params['win_itm'],
$params['lose_itm'],
$params['win_eff'],
$params['lose_eff'],
$params['win_ico'],
$params['lose_ico'],
$params['win_back'],
$params['time_restart']
)) {
return;
}
Db::sql('replace into aaa_monsters
(uid, start_room, start_day, back_day, start_dd, start_mm, start_hh, start_min,
back_min, back_dd, back_mm, back_hh, start_text, back_text, win_text, lose_text,
nich_text, win_money1, win_money2, lose_money, lose_money2, win_exp, lose_exp,
win_itm, lose_itm, win_eff, lose_eff, win_ico, lose_ico, win_back, time_restart)
values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)', [
$params['uid'],
$params['start_room'],
$params['start_day'],
$params['back_day'],
$params['start_dd'],
$params['start_mm'],
$params['start_hh'],
$params['start_min'],
$params['back_min'],
$params['back_dd'],
$params['back_mm'],
$params['back_hh'],
$params['start_text'],
$params['back_text'],
$params['win_text'],
$params['lose_text'],
$params['nich_text'],
$params['win_money1'],
$params['win_money2'],
$params['lose_money'],
$params['lose_money2'],
$params['win_exp'],
$params['lose_exp'],
$params['win_itm'],
$params['lose_itm'],
$params['win_eff'],
$params['lose_eff'],
$params['win_ico'],
$params['lose_ico'],
$params['win_back'],
$params['time_restart'],
]);
echo '<b style="color: red">Новые данные были успешно сохранены!</b>';
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
<?php
use Core\ConversionHelper;
use Helper\Conversion;
class BotPriemLogic
{
@ -102,242 +102,13 @@ class BotPriemLogic
return true;
}
private static function usePriem($id)
{
BotLogic::inuser_go_btl(BotLogic::$bot, '&usepriem=' . $id);
}
//Ставка на опережение
private static function priem220($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Разгадать тактику
private static function priem217($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Обреченность
private static function priem204($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Выжить
private static function priem232($i)
{
if (self::hp() <= 30 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Жажда крови
private static function priem188($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Шок удар
private static function priem235($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Хлебнуть крови
private static function priem240($i)
{
if (self::hp() <= 70) {
self::usePriem($i);
}
}
//Силовое поле
private static function priem175($i)
{
self::usePriem($i);
}
//Прикрыться
private static function priem1($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Вломить
private static function priem2($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Собрать зубы
private static function priem3($i)
{
if (self::hp() <= 70 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Воля к победе
private static function priem6($i)
{
if (self::hp() <= 40 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Танец ветра
private static function priem8($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Танец лезвий
private static function priem48($i)
{
if (rand(0, 100) < 70) {
self::usePriem($i);
}
}
//Дикая удача
private static function priem9($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Слепая удача
private static function priem47($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Предвиденье
private static function priem10($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Второе дыхание
private static function priem49($i)
{
if (rand(0, 100) < 80 && self::hp() <= 60) {
self::usePriem($i);
}
}
//Рывок
private static function priem223($i)
{
if (self::hp() <= 50 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Удачный удар
private static function priem11($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Стойкость
private static function priem13($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Ярость
private static function priem14($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Сильный удар
private static function priem4($i)
{
if (rand(0, 100) < 60) {
self::usePriem($i);
}
}
//Утереть пот
private static function priem5($i)
{
if (self::hp() <= 95) {
self::usePriem($i);
}
}
//Агрессивная защита
private static function priem211($i)
{
if (rand(0, 100) < 80) {
self::usePriem($i);
}
}
//Полная защита
private static function priem45($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Активная защита
private static function priem7($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
private static function hp(): float
{
return round((BotLogic::$st['hpNow'] / BotLogic::$st['hpAll'] * 100), 2);
}
//Тест на возможность использования
private static function testpriem($pl): int
{
global $u;
$notr = 0;
$tr = ConversionHelper::dataStringToArray($pl['tr']);
$d2 = ConversionHelper::dataStringToArray($pl['date2']);
$tr = Conversion::dataStringToArray($pl['tr']);
$d2 = Conversion::dataStringToArray($pl['date2']);
$x = 1;
while ($x <= 7) {
@ -393,4 +164,260 @@ class BotPriemLogic
return $notr;
}
//Ставка на опережение
private static function priem1($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Разгадать тактику
private static function usePriem($id)
{
BotLogic::inuser_go_btl(BotLogic::$bot, '&usepriem=' . $id);
}
//Обреченность
private static function priem2($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Выжить
private static function priem3($i)
{
if (self::hp() <= 70 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Жажда крови
private static function hp(): float
{
return round((BotLogic::$st['hpNow'] / BotLogic::$st['hpAll'] * 100), 2);
}
//Шок удар
private static function priem4($i)
{
if (rand(0, 100) < 60) {
self::usePriem($i);
}
}
//Хлебнуть крови
private static function priem5($i)
{
if (self::hp() <= 95) {
self::usePriem($i);
}
}
//Силовое поле
private static function priem6($i)
{
if (self::hp() <= 40 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Прикрыться
private static function priem7($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Вломить
private static function priem8($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Собрать зубы
private static function priem9($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Воля к победе
private static function priem10($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Танец ветра
private static function priem11($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Танец лезвий
private static function priem13($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Дикая удача
private static function priem14($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Слепая удача
private static function priem45($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Предвиденье
private static function priem47($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Второе дыхание
private static function priem48($i)
{
if (rand(0, 100) < 70) {
self::usePriem($i);
}
}
//Рывок
private static function priem49($i)
{
if (rand(0, 100) < 80 && self::hp() <= 60) {
self::usePriem($i);
}
}
//Удачный удар
private static function priem188($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Стойкость
private static function priem204($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Ярость
private static function priem211($i)
{
if (rand(0, 100) < 80) {
self::usePriem($i);
}
}
//Сильный удар
private static function priem217($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Утереть пот
private static function priem220($i)
{
if (rand(0, 100) < 30) {
self::usePriem($i);
}
}
//Агрессивная защита
private static function priem223($i)
{
if (self::hp() <= 50 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Полная защита
private static function priem232($i)
{
if (self::hp() <= 30 && rand(0, 100) < 50) {
self::usePriem($i);
}
}
//Активная защита
private static function priem235($i)
{
if (rand(0, 100) < 50) {
self::usePriem($i);
}
}
private static function priem240($i)
{
if (self::hp() <= 70) {
self::usePriem($i);
}
}
//Тест на возможность использования
private static function priem175($i)
{
self::usePriem($i);
}
}

View File

@ -0,0 +1,81 @@
<?php
namespace Captcha;
class Captcha
{
private int $width;
private int $height;
private string $sum;
public function width(int $width): Captcha
{
$this->width = max($width, 1);
return $this;
}
public function height(int $height): Captcha
{
$this->height = max($height, 1);
return $this;
}
public function newImage()
{
if ($this->width < 1 || $this->height < 1) {
return;
}
$img = imagecreatetruecolor($this->width, $this->height) or die('Cannot create image'); // создаем картинку
imagefill($img, 0, 0, 0x616161); // заполняем фон картинки
$x = -20;
$i = 1;
$sum = "";
$colorRGB = rand(180, 200); //цвет текста
while ($i++ <= 5000) {
imageSetPixel($img, rand(0, 105), rand(0, 24), 0x515151);
}
//рисуем 2 линии
imageLine($img, rand(0, 10), rand(0, 50), rand(95, 105), rand(0, 26), 0x909090);
imageLine($img, rand(0, 10), rand(0, 50), rand(95, 105), rand(0, 26), 0x909090);
//рамка
imageRectangle($img, 0, 0, 105, 24, 0x343434);
$fonts = [
'fonts/FRSCRIPT.ttf',
'fonts/CHILLER.ttf',
'fonts/Bradley Hand ITC.ttf',
'fonts/de_Manu_2_Regular.ttf',
'fonts/Edgar_da_cool_Regular.ttf',
'fonts/Hurryup_Hurryup.ttf',
'fonts/Fh_Script_Regular.ttf',
'fonts/Gabo4_Gabo4.ttf',
'fonts/JAMI_Regular.ttf',
'fonts/Justy1_Regular.ttf',
];
$font = '../' . $fonts[rand(0, sizeof($fonts) - 1)];
$i = 1;
while ($i++ <= 4) { // выводим одну цифру за один проход цикла
imagettftext($img, 15, 0, $x = $x + 25, 20, imagecolorallocate($img, $colorRGB, $colorRGB, $colorRGB), $font, $rnd = mt_rand(0, 9)); // выводим текст поверх картинки
$sum = $sum . $rnd; // Собираем в одну строку все символы на картинке
}
ob_start();
imagepng($img); // выводим готовую картинку в формате PNG
$imgData = ob_get_clean();
imagedestroy($img); // освобождаем память, выделенную для картинки
echo '<img src="data:image/png;base64,' . base64_encode($imgData) . '" alt="captcha">';
$this->sum = $sum;
}
/**
* @return string
*/
public function getSum(): string
{
return $this->sum;
}
}

File diff suppressed because one or more lines are too long

View File

@ -0,0 +1,24 @@
<?php
namespace Clan;
use Core\Db;
class ClanInfo
{
public static function isJoinable(string $name): bool
{
return Db::getValue('select count(name) from clan where name = ? and status = 1', [$name]) > 0;
}
public static function getNameById(int $id): string
{
$clan = self::getById($id);
return !empty($clan['name']) ? $clan['name'] : '';
}
public static function getById(int $id): array
{
return Db::getRow('select * from clan where id = ? and status = 1', [$id]) ?: [];
}
}

View File

@ -2,8 +2,9 @@
namespace Clan;
use Core\ConversionHelper;
use Core\Db;
use Delo;
use Helper\Conversion;
use User;
use User\ItemsModel;
@ -11,51 +12,27 @@ class ItemStorage
{
private string $error = '';
private function isGoodForStorage(array $item, $userClanId): bool
{
if (empty($item['inslot']) || !empty($item['gift'])) {
$this->error = 'Ïðåäìåò íå íàéäåí.';
}
$idata = ConversionHelper::dataStringToArray($item['data']);
if (
!empty($idata['frompisher']) ||
!empty($idata['sudba']) ||
!empty($idata['icos']) ||
!empty($idata['fromlaba'])
) {
$this->error = 'Ïðåäìåò íå ïîäõîäèò.';
}
if (!empty($idata['toclan']) && explode('#', $idata['toclan'])[0] == $userClanId) {
$this->error = 'Ïðåäìåò óæå ïðèíàäëåæèò êëàíó.';
}
return empty($this->error);
}
public function put(int $itemId, int $clanId): string
{
$user = User::start()->info;
$item = ItemsModel::getOwnedItemById($itemId, $user['id']);
$clanName = Db::getValue('select name from clan where id = ?', [$clanId]) ?? '';
if (empty($clanName)) {
return 'Êëàí íå íàéäåí.';
return 'Клан не найден.';
}
if (!$this->isGoodForStorage($item, $user['clan'])) {
return $this->error;
}
$col = User::start()->itemsX(($itemId));
$idata = ConversionHelper::dataStringToArray($item['data']);
$idata = Conversion::dataStringToArray($item['data']);
if (!isset($idata['toclan'])) {
$idata['toclan'] = $user['clan'] . '#' . $user['id'];
$item['data'] = ConversionHelper::arrayToDataString($idata);
User::start()->addDelo(
$item['data'] = Conversion::arrayToDataString($idata);
Delo::add(
2,
$user['id'],
'&quot;System.transfer.MONEY&quot;: Ïðåäìåò &quot;' . $item['name'] . '&quot; (#id : "' . $itemId . '") (x' . $col . ') áûë ïîæåðòâîâàí êëàíó &quot;' . $clanName . '&quot; (' . $clanId . ').',
time(),
$user['city'],
'System.transfer.clan',
0,
0
$user['id'],
'&quot;System.transfer.MONEY&quot;: Предмет &quot;' . $item['name'] . '&quot; (#id : "' . $itemId . '") (x' . $col . ') был пожертвован клану &quot;' . $clanName . '&quot; (' . $clanId . ').',
);
$sendType = 4;
} else {
@ -63,16 +40,35 @@ class ItemStorage
}
Db::sql(
'insert into clan_operations (clan, time, type, text, val, uid) values (?,unix_timestamp(),?,?,?,?)',
[$clanId, $sendType, $user['login'], $item['name'] . ("x$col Èä: [$itemId]"), $user['id']]
[$clanId, $sendType, $user['login'], $item['name'] . ("x$col Ид: [$itemId]"), $user['id']]
);
Db::sql(
'update items_users set lastUPD = unix_timestamp(), uid = ?, data = ? where id = ?',
['-21' . $user['clan'], $item['data'], $itemId]
);
return 'Âû ïåðåäàëè ïðåäìåò &quot;' . $item['name'] . '&quot; êëàíó.';
return 'Вы передали предмет &quot;' . $item['name'] . '&quot; клану.';
}
private function isGoodForStorage(array $item, $userClanId): bool
{
if (empty($item['inslot']) || !empty($item['gift'])) {
$this->error = 'Предмет не найден.';
}
$idata = Conversion::dataStringToArray($item['data']);
if (
!empty($idata['frompisher']) ||
!empty($idata['sudba']) ||
!empty($idata['icos']) ||
!empty($idata['fromlaba'])
) {
$this->error = 'Предмет не подходит.';
}
if (!empty($idata['toclan']) && explode('#', $idata['toclan'])[0] == $userClanId) {
$this->error = 'Предмет уже принадлежит клану.';
}
return empty($this->error);
}
public function ungive_itm_cl($id, $user, $cl): string
{
@ -86,27 +82,25 @@ class ItemStorage
mysql_query('SELECT `id`,`bot`,`clone` FROM `stats` WHERE `id` = "' . $itm_['uid'] . '" LIMIT 1')
);
if ($user_itm['bot'] > 0 || $user_itm['clone'] > 0 || !isset($user_itm['id'])) {
$r = '<font color="#FF0000"><strong>Âû íå ìîæåòå èçüÿòü äàííûé ïðåäìåò, îí íå ïðèíàäëåæèò êëàíó</strong></font><br />';
$r = '<font color="#FF0000"><strong>Вы не можете изьять данный предмет, он не принадлежит клану</strong></font><br />';
} elseif (isset($itm_['id'])) {
if ($itm_['inOdet'] != 0) {
$o = ', `inOdet` = 0';
} else {
$o = '';
}
$r = '<font color="#FF0000"><strong>Âû óñïåøíî èçúÿëè ïðåäìåò &quot;' . $itm_['name'] . '&quot;</strong></font><br />';
$col = $this->itemsX(((int)$id));
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time(
) . '", "6", "' . $user['login'] . '", "' . $itm_['name'] . ' (x' . $col . ') Èä : [' . $id . '] | Ó ïåðñîíàæà : [' . $itm_['uid'] . ']", "' . $user['id'] . '")'
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time(
) . '", `uid` = "-21' . $res['id'] . '" ' . $o . ' WHERE `id` = "' . $id . '" LIMIT 1'
);
if ($itm_['inOdet'] != 0) {
$o = ', `inOdet` = 0';
} else {
$o = '';
}
$r = '<font color="#FF0000"><strong>Вы успешно изъяли предмет &quot;' . $itm_['name'] . '&quot;</strong></font><br />';
$col = $this->itemsX(((int)$id));
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "6", "' . $user['login'] . '", "' . $itm_['name'] . ' (x' . $col . ') Ид : [' . $id . '] | У персонажа : [' . $itm_['uid'] . ']", "' . $user['id'] . '")'
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "-21' . $res['id'] . '" ' . $o . ' WHERE `id` = "' . $id . '" LIMIT 1'
);
} else {
$r = '<font color="#FF0000"><strong>Ïðåäìåò íå íàéäåí.</strong></font><br />';
$r = '<font color="#FF0000"><strong>Предмет не найден.</strong></font><br />';
}
return $r;
}
@ -120,25 +114,23 @@ class ItemStorage
);
$res = mysql_fetch_array(mysql_query('SELECT * FROM `clan` WHERE `id` = "' . $cl . '" LIMIT 1'));
if (isset($itm_['id'])) {
$po = ConversionHelper::dataStringToArray($itm_['data']);
$po = Conversion::dataStringToArray($itm_['data']);
if (isset($po['toclan'])) {
$cls = explode('#', $po['toclan']);
$cls = $cls[1];
}
$col = $this->itemsX(((int)$id));
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time(
) . '", "5", "' . $user['login'] . '", "' . $itm_['name'] . ' (x' . $col . ') Èä : [' . $id . '] Õîçÿèí : [' . $cls . ']", "' . $user['id'] . '")'
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time(
) . '", `uid` = "' . $user['id'] . '" WHERE `id` = "' . $id . '" LIMIT 1'
);
$r = '<font color="#FF0000"><strong>Âû óñïåøíî âçÿëè ïðåäìåò &quot;' . $itm_['name'] . '&quot; èç õðàíèëèùà</strong></font><br />';
$col = $this->itemsX(((int)$id));
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "5", "' . $user['login'] . '", "' . $itm_['name'] . ' (x' . $col . ') Ид : [' . $id . '] Хозяин : [' . $cls . ']", "' . $user['id'] . '")'
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "' . $user['id'] . '" WHERE `id` = "' . $id . '" LIMIT 1'
);
$r = '<font color="#FF0000"><strong>Вы успешно взяли предмет &quot;' . $itm_['name'] . '&quot; из хранилища</strong></font><br />';
} else {
$r = '<font color="#FF0000"><strong>Ïðåäìåò íå íàéäåí.</strong></font><br />' . $id;
$r = '<font color="#FF0000"><strong>Предмет не найден.</strong></font><br />' . $id;
}
return $r;
}
@ -149,7 +141,7 @@ class ItemStorage
'SELECT * FROM `items_users` WHERE (`uid` = "-21' . $user['clan'] . '" OR `data` LIKE "%toclan=' . $user['clan'] . '#%")'
);
while ($pl = mysql_fetch_array($itms)) {
$po = ConversionHelper::dataStringToArray($pl['data']);
$po = Conversion::dataStringToArray($pl['data']);
if (isset($po['toclan'])) {
$cls = explode('#', $po['toclan']);
$cls = $cls[1];
@ -161,18 +153,16 @@ class ItemStorage
}
}
unset($po['toclan']);
$pl['data'] = ConversionHelper::arrayToDataString($po);
$pl['data'] = Conversion::arrayToDataString($po);
$col = $this->itemsX(((int)$pl['id']));
$it_n = mysql_fetch_array(
mysql_query('SELECT `name` FROM `items_main` WHERE `id` = "' . $pl['item_id'] . '"')
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time(
) . '", `uid` = "' . $user['id'] . '", `data` = "' . $pl['data'] . '" WHERE `id` = "' . $pl['id'] . '"'
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "' . $user['id'] . '", `data` = "' . $pl['data'] . '" WHERE `id` = "' . $pl['id'] . '"'
);
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time(
) . '", "' . $type . '", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Èä : [' . $pl['id'] . ']", "' . $user['id'] . '")'
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "' . $type . '", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
);
} elseif ($pl['uid'] == $user['id']) {
$col = $this->itemsX(((int)$pl['id']));
@ -180,14 +170,12 @@ class ItemStorage
mysql_query('SELECT `name` FROM `items_main` WHERE `id` = "' . $pl['item_id'] . '"')
);
mysql_query(
'UPDATE `items_users` SET `lastUPD` = "' . time(
) . '", `uid` = "-21' . $user['clan'] . '" WHERE `id` = "' . $pl['id'] . '"'
'UPDATE `items_users` SET `lastUPD` = "' . time() . '", `uid` = "-21' . $user['clan'] . '" WHERE `id` = "' . $pl['id'] . '"'
);
mysql_query(
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time(
) . '", "9", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Èä : [' . $pl['id'] . ']", "' . $user['id'] . '")'
'INSERT INTO `clan_operations` (`clan`, `time`, `type`, `text`, `val`, `uid`) VALUES ("' . $res['id'] . '", "' . time() . '", "9", "' . $user['login'] . '", "' . $it_n['name'] . ' (x' . $col . ') Ид : [' . $pl['id'] . ']", "' . $user['id'] . '")'
);
}
}
}
}
}

View File

@ -0,0 +1,136 @@
<?php
namespace Clan;
use Core\Config;
use Core\Db;
use Uploader;
class Register
{
const REGISTER_COST_EKR = 50;
private string $name;
private int $align = 0;
private Uploader $logo;
private int $newClanId = 0;
public function __construct()
{
if (!isset($_POST['newclanname'], $_POST['newclanalign'], $_FILES['newclanlogo'])) {
return;
}
$this->setName($_POST['newclanname']);
$this->setLogo();
$this->setAlign(intval($_POST['newclanalign']));
$this->new();
}
private function setName(string $name)
{
$this->name = $name;
}
private function setLogo()
{
$this->logo = new Uploader('newclanlogo');
$this->logo->setMaxFileSize(.03);
$this->logo->setDimensions(24, 15);
$this->logo->setExtentions(['gif', 'png']);
}
private function setAlign(int $align)
{
if (!in_array($align, [0, 1, 3, 7])) {
$align = 0;
}
$this->align = $align;
}
public function new()
{
if (!$this->hasGoodName()) {
return;
}
$imageId = $this->logo->saveToDb();
if (!$imageId) {
echo $this->logo::$error;
return;
}
Db::sql('insert into clan (name, align, logo) values (?,?,?)', [$this->name, $this->align, $imageId]);
$this->newClanId = Db::lastInsertId();
}
private function hasGoodName(): bool
{
return Db::getValue('select count(id) from clan where name = ?', [$this->name]) === 0;
}
public static function approve(int $clanId)
{
Db::sql('update clan set status = 1, time_reg = unix_timestamp() where id = ?', [$clanId]);
}
public static function reject(int $clanId)
{
Db::sql('delete from clan where id = ?', [$clanId]);
}
public static function printForm(): string
{
$img = Config::img() . '/i/align';
return <<<REGISTERFORM
<style>
div.regclangrid [type=radio] {
position: absolute;
opacity: 0;
width: 0;
height: 0;
}
/* IMAGE STYLES */
div.regclangrid [type=radio] + img {
cursor: pointer;
}
/* CHECKED STYLES */
div.regclangrid [type=radio]:checked + img {
outline: 1px solid brown;
padding: 2px;
}
div.regclangrid {
display: grid;
grid-template-columns: 100px auto;
}
</style>
<form method="POST" enctype="multipart/form-data">
<div class="regclangrid">
<div><label for="clanname">Название:</label></div>
<div><input name="newclanname" id="clanname"></div>
<div><label for="clanlogo">Логотип:</label></div>
<div><input type="file" name="newclanlogo" accept="image/*" id="newclanlogo"> размер: 24×15, формат: png или gif, до 30Кб</div>
<div>Склонность:</div>
<div>
<label><input type="radio" name="newclanalign" value="0" checked><img src="$img/align0.gif" alt="none"></label>
<label><input type="radio" name="newclanalign" value="1"><img src="$img/align1.gif" alt="light"></label>
<label><input type="radio" name="newclanalign" value="3"><img src="$img/align3.gif" alt="dark"></label>
<label><input type="radio" name="newclanalign" value="7"><img src="$img/align7.gif" alt="neutral"></label>
</div>
<div></div>
<div><button type="submit">Подать заявку</button></div>
</div>
</form>
REGISTERFORM;
}
/**
* @return int
*/
public function getNewClanId(): int
{
return $this->newClanId;
}
}

View File

@ -1,77 +1,36 @@
<?php
use Core\Db;
use Helper\Conversion;
class ComissionShop
{
public function commisionShop($sid, $preview = "full")
public function commisionShop($preview = 'full')
{
global $c, $code, $sid;
switch ((int)$_GET['otdel']) {
case 1:
$typeOtdel = 18;
break;
case 2:
$typeOtdel = 19;
break;
case 3:
$typeOtdel = 20;
break;
case 4:
$typeOtdel = 21;
break;
case 5:
$typeOtdel = 22;
break;
case 6:
$typeOtdel = 15;
break;
case 7:
$typeOtdel = 12;
break;
case 8:
$typeOtdel = 4;
break;
case 9:
$typeOtdel = 5;
break;
case 10:
$typeOtdel = 6;
break;
case 11:
$typeOtdel = 1;
break;
case 12:
$typeOtdel = 3;
break;
case 13:
$typeOtdel = 8;
break;
case 14:
$typeOtdel = 14;
break;
case 15:
$typeOtdel = 13;
break;
case 16:
$typeOtdel = 9;
break;
case 17:
$typeOtdel = 10;
break;
case 18:
$typeOtdel = 11;
break;
case 19:
$typeOtdel = 29;
break;
case 20:
$typeOtdel = 30;
break;
case 1050:
$typeOtdel = 1050;
break;
default :
$typeOtdel = 18;
}
global $code;
$typeOtdel = match ((int)$_GET['otdel']) {
2 => 19,
3 => 20,
4 => 21,
5 => 22,
6 => 15,
7 => 12,
8 => 4,
9 => 5,
10 => 6,
11 => 1,
12 => 3,
13 => 8,
14 => 14,
15 => 13,
16 => 9,
17 => 10,
18 => 11,
19 => 29,
20 => 30,
1050 => 1050,
default => 18,
};
if ($typeOtdel != 1050) {
if ($preview == "full") {
$cl = mysql_query(
@ -158,9 +117,9 @@ ORDER BY `1price`ASC , inGroupCount DESC'
)
);
if ($steck[0] > 1 && $preview == "preview") {
$po = \Core\ConversionHelper::dataStringToArray($d['data']);
$po = Helper\Conversion::dataStringToArray($d['data']);
} else {
$po = \Core\ConversionHelper::dataStringToArray($pl['data']);
$po = Helper\Conversion::dataStringToArray($pl['data']);
}
if (($pl['type'] >= 18 && $pl['type'] <= 24) || $pl['type'] == 26 || $pl['type'] == 27) {
//Зоны блока +
@ -452,7 +411,7 @@ ORDER BY `1price`ASC , inGroupCount DESC'
//действие комплекта
$i1c = 0;
$i2c = 0;
$i1e = \Core\ConversionHelper::dataStringToArray($plc['data']);
$i1e = Helper\Conversion::dataStringToArray($plc['data']);
while ($i1c < count($this->items['add'])) {
if (isset($i1e[$this->items['add'][$i1c]])) {
$i3c = $i1e[$this->items['add'][$i1c]];
@ -488,7 +447,7 @@ ORDER BY `1price`ASC , inGroupCount DESC'
//действие комплекта
$i1c = 0;
$i2c = 0;
$i1e = \Core\ConversionHelper::dataStringToArray($plc['data']);
$i1e = Helper\Conversion::dataStringToArray($plc['data']);
while ($i1c < count($this->items['add'])) {
if (isset($i1e[$this->items['add'][$i1c]])) {
$i3c = $i1e[$this->items['add'][$i1c]];
@ -572,4 +531,96 @@ ORDER BY `1price`ASC , inGroupCount DESC'
echo '<tr style="background-color:#' . $cr . ';"><td style="padding:7px;" align="center" valign="top">Прилавок магазина пуст</td></tr>';
}
}
public function buyItem(int $iid, User $u): string
{
$irow = Db::getRow('select items_users.id, uid, 1price, inGroup, inShop, data, item_id, login, items_main.name, price1
from items_users
left join users on users.id = uid
left join items_main on items_main.id = item_id
where items_users.id = ? and inShop = 30', [$iid]);
$price = $irow['1price'];
if (!isset($irow['id']) || !isset($iid) || $irow['inShop'] != 30) {
$r = 'Предмет не найден на прилавке';
} else {
if ($price > $u->info['money']) {
$r = 'У вас недостаточно денег (не хватает ' . ($price - $u->info['money']) . ' кр.)';
} else {
$u->addKr(-$price);
$u->addKr($price, $irow['uid']);
$col = $u->itemsX($iid);
if ($col > 1) {
Db::sql('update items_users set uid = ?, inGroup = inGroup + 1000, 1price = ?, lastUPD = unix_timestamp(), inShop = 0
where inShop = 30 and inOdet = 0 and item_id = ? and uid = ? and inGroup = ? limit ?',
[$u->info['id'], $irow['price1'], $irow['item_id'], $irow['uid'], $irow['inGroup'], $col]);
$irow['name'] .= "(x$col)";
} else {
Db::sql('update items_users set uid = ?, 1price = ?, lastUPD = unix_timestamp(), inShop = 0
where id = ? and uid = ? and inOdet = 0',
[$iid, $irow['uid']]);
}
Delo::add(1, 'comShop', $u->info['id'], "Купил предмет «{$irow['name']}» у игрока {$irow['login']} за $price кр.", $price);
Delo::add(1, 'comShop', $irow['uid'], "Продал предмет «{$irow['name']}» игроку {$irow['login']} за $price кр.");
$r = "Вы купили предмет «{$irow['name']}» у игрока {$irow['login']} за $price кр.<br>Предмет успешно добавлен в инвентарь.";
}
}
return '<div>' . $r . '</div>';
}
public function rent($action, int $iid, int $price, User $u)
{
if ($action == "Сдать в магазин" && $price > 0) {
$ChImtem = mysql_fetch_array(
mysql_query(
'SELECT `id`, `item_id`, `data`, `inGroup`, `uid` FROM `items_users` WHERE `id` = ' . $iid . ' LIMIT 1'
)
);
$ChSudba = Conversion::dataStringToArray($ChImtem['data']);
if (!isset($ChSudba['sudba']) && $ChSudba['sudba'] == 0 && $ChSudba['sudba'] != 1 && !isset($ChSudba['toclan'])) {
if (isset($ChImtem['inGroup']) && $ChImtem['inGroup'] > 0) {
$col = $u->itemsX($ChImtem['id']);
if ($col > 1) {
mysql_query(
'UPDATE `items_users` SET `inShop` = 30, `1price` = ' . $price . ' WHERE `item_id`="' . $ChImtem['item_id'] . '" AND `uid`="' . $ChImtem['uid'] . '" AND `inGroup` = "' . $ChImtem['inGroup'] . '" LIMIT ' . $col . ''
);
} else {
mysql_query(
'UPDATE `items_users` SET `inShop` = 30, `1price` = ' . $price . ' WHERE `uid` = "' . $u->info['id'] . '" AND `id` = "' . $iid . '" AND `inOdet` = "0" AND `delete` = "0" '
);
}
} else {
mysql_query(
'UPDATE `items_users` set `inShop` = 30, `1price` = ' . $price . ' where `uid` = "' . $u->info['id'] . '" AND `id` = "' . $iid . '" AND `inOdet` = "0" AND `delete` = "0" '
);
}
}
} elseif ($action == "Забрать") {
$i = mysql_fetch_array(
mysql_query(
'SELECT `im`.`price1`,
`iu`.* FROM `items_users` AS `iu` LEFT JOIN `items_main` AS `im` ON (`im`.`id` = `iu`.`item_id`) WHERE `iu`.`id` = "' . $iid . '" AND `iu`.`inShop` = "30" AND `iu`.`delete` = "0" LIMIT 1'
)
);
if (isset($i['inGroup']) and $i['inGroup'] > 0) {
$col = $u->itemsX($i['id']);
if ($col > 1) {
mysql_query(
'UPDATE `items_users` SET `inShop` = 0, `1price` = ' . $i['price1'] . ' WHERE `item_id`="' . $i['item_id'] . '" AND `inShop` = "30" AND `uid`="' . $i['uid'] . '" AND `inGroup` = "' . $i['inGroup'] . '" LIMIT ' . $col . ''
);
} else {
mysql_query(
'UPDATE `items_users` SET `inShop` = 0, `1price` = ' . $i['price1'] . ' WHERE `uid` = "' . $u->info['id'] . '" AND `id` = "' . $iid . '" AND `inOdet` = "0" AND `delete` = "0" '
);
}
} else {
mysql_query(
'UPDATE `items_users` SET `inShop` = 0, `1price` = "' . $i['price1'] . '" WHERE `id` = "' . $iid . '" and `inShop` = "30" LIMIT 1'
);
}
}
}
}

View File

@ -1,17 +0,0 @@
<?php
namespace Core;
class ComparsionHelper
{
public static function minimax($value, $minimum, $maximum)
{
if ($value < $minimum) {
$value = $minimum;
}
if ($value > $maximum) {
$value = $maximum;
}
return $value;
}
}

View File

@ -4,19 +4,18 @@ namespace Core;
class Config
{
const EKR_RUB_PRICE = 30;
const KR_TO_EKR_EXCHANGE = 500;
const EKR_TO_KR_EXCHANGE = 200;
private static self $instance;
private static string $hostname = 'new-combats.tech';
private static string $gamename = 'Бойцовский Клуб';
private function __construct()
{
//singleton
}
private static function subdomain(string $name): string
{
return DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . $name . '.' . self::$hostname;
}
/** Самый распространённый субдомен
* //img.{siteName}.
* @return string
@ -26,6 +25,11 @@ class Config
return self::subdomain('img');
}
private static function subdomain(string $name): string
{
return DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . $name . '.' . self::$hostname;
}
public static function get(?string $key = null)
{
$c['ver'] = '1.8.3.7';
@ -48,7 +52,7 @@ class Config
$c['https'] = DIRECTORY_SEPARATOR . DIRECTORY_SEPARATOR . self::$hostname;
$c['img2'] = self::subdomain('img');
$c['lib'] = self::subdomain('lib');
$c['exit'] = '<script>top.location.href="' . $c['https'] . '";</script>';
$c['exit'] = "<script>window.location.replace('{$c['https']}');</script>";
$c['support'] = 'support@' . $c['host'];
@ -75,9 +79,8 @@ class Config
$c['expstop'] = 2999999; //9; //Опыт на котором останавливаемся 11 149999999
$c['expstopu'] = 2999999; //Опыт на котором останавливаемся
$c['noobgade'] = false; //нуб квест (пещера)
$c['bonusonline'] = true; //бонус за онлайн
$c['level_ransfer'] = 8; //С какого уровня разрешены передачи
$c['znahar'] = true; //бесплатный знахарь
$c['nolevel'] = false; //лимитирование уровней
$c['noitembuy'] = false; //Не требует ресурсы для покупки
$c['effz'] = 0; //Скольким секундам равен заряд

View File

@ -1,26 +0,0 @@
<?php
namespace Core;
class ConversionHelper
{
/** Ïðåâðàùàåò ñòðîêó data ('a=1|b=2|c=3') èç ÁÄ â ìàññèâ [a=>1, b=>2, c=>3].
* @param string $dataString
* @return array
*/
public static function dataStringToArray(string $dataString): array
{
$arr = json_decode(str_replace(['=', '|'], ['":', ',"'], '{"' . $dataString . '}'), true);
return $arr ?: [];
}
/** Ïðåâðàùàåò ìàññèâ [a=>1, b=>2, c=>3] â ñòðîêó data ('a=1|b=2|c=3') äëÿ ÁÄ.
* @param array $dataArray
* @return string
*/
public static function arrayToDataString(array $dataArray): string
{
$str = json_encode($dataArray);
return $str ? str_replace(['":', ',"', '{"', '}'], ['=', '|'], $str) : '';
}
}

View File

@ -2,7 +2,6 @@
namespace Core;
use Exception;
use PDO;
use PDOException;
use PDOStatement;
@ -15,22 +14,71 @@ class Db
/**
* DB constructor.
* @throws Exception
* @throws PDOException
*/
public function __construct()
{
try {
self::$db = Database::pdoinit();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
throw new PDOException($e->getMessage());
}
}
/**
* @param string $query
* @return int
*/
public static function exec(string $query): int
{
self::init();
return self::$db->exec($query);
}
private static function init(): void
{
self::$instance ??= new self();
}
/**
* @param ?string $name [optional] Name of the sequence object from which the ID should be returned.
* @return string
*/
public static function lastInsertId(?string $name = null): string
{
self::init();
return self::$db->lastInsertId($name);
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getRows(string $query, array $args = []): array
{
return self::run($query, $args)->fetchAll();
}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public static function run(string $query, array $args = []): PDOStatement
{
try {
if (!$args) {
return self::query($query);
}
$stmt = self::prepare($query);
$stmt->execute($args);
return $stmt;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
/**
* @param string $stmt
* @return PDOStatement
@ -51,64 +99,6 @@ class Db
return self::$db->prepare($stmt);
}
/**
* @param string $query
* @return int
*/
static public function exec(string $query): int
{
self::init();
return self::$db->exec($query);
}
/**
* @return string
*/
static public function lastInsertId(): string
{
self::init();
return self::$db->lastInsertId();
}
/**
* @param string $query
* @param array $args
* @return PDOStatement
*/
public static function run(string $query, array $args = []): PDOStatement
{
try {
if (!$args) {
return self::query($query);
}
$stmt = self::prepare($query);
$stmt->execute($args);
return $stmt;
} catch (PDOException $e) {
throw new PDOException($e->getMessage());
}
}
/**
* @param string $query
* @param array $args
* @return mixed
*/
public static function getRow(string $query, array $args = [])
{
return self::run($query, $args)->fetch();
}
/**
* @param string $query
* @param array $args
* @return array
*/
public static function getRows(string $query, array $args = []): array
{
return self::run($query, $args)->fetchAll();
}
/**
* @param string $query
* @param array $args
@ -123,6 +113,16 @@ class Db
return $result;
}
/**
* @param string $query
* @param array $args
* @return mixed
*/
public static function getRow(string $query, array $args = [])
{
return self::run($query, $args)->fetch();
}
/**
* @param string $query
* @param array $args
@ -141,4 +141,4 @@ class Db
{
self::run($query, $args);
}
}
}

View File

@ -1,38 +0,0 @@
<?php
namespace Core;
use PHPMailer;
class Mail
{
public static function send($to, $message, $subject = 'Бойцовский клуб')
{
require dirname(__DIR__) . '/mail/class.phpmailer.php';
$mail = new PHPMailer;
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.mail.yahoo.com'; // Specify main and backup server
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'newcombats@yahoo.com'; // SMTP username
$mail->Password = 'uqcdbnsoagxcyysh';
$mail->SMTPSecure = 'tls'; // Enable encryption, 'ssl' also accepted
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->From = 'newcombats@yahoo.com';
$mail->FromName = 'Бойцовский Клуб';
$mail->AddAddress($to); // Add a recipient
$mail->IsHTML(true); // Set email format to HTML
$mail->Subject = $subject;
$mail->Body = '<div>' . $message . '</div>';
$mail->AltBody = $message;
if (!$mail->Send()) {
return 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo;
}
return 1;
}
}

View File

@ -0,0 +1,18 @@
<?php
namespace Core;
class View
{
public static function render(string $view, array $arguments = [])
{
extract($arguments, EXTR_SKIP);
$file = $_SERVER['DOCUMENT_ROOT'] . "/_incl_data/Views/$view";
if (is_readable($file)) {
require $file;
} else {
trigger_error("File $file not found!", E_USER_ERROR);
}
}
}

View File

@ -0,0 +1,26 @@
<?php
namespace DTO;
class BattleSpell
{
public string $name;
public string $elemental;
public int $damage;
public string $color;
public string $colorCrit;
public string $colorMiss;
public function __construct(string $elemental)
{
if (!in_array($elemental, ['fire', 'water', 'air', 'earth', 'light', 'dark'])) {
$this->elemental = 'raw';
}
if ($elemental === 'fire') {
$this->elemental = $elemental;
$this->color = '#a00';
$this->colorCrit = '#f00';
$this->colorMiss = '#909090';
}
}
}

View File

@ -2,7 +2,7 @@
namespace DTO;
use Core\ConversionHelper;
use Helper\Conversion;
use ItemModel;
class KnowledgeTempleItem
@ -13,6 +13,7 @@ class KnowledgeTempleItem
public int $level;
private int $rowId;
/**
* @param array $item
*/
@ -23,10 +24,10 @@ class KnowledgeTempleItem
$this->type = intval($item['type']);
$this->name = $item['name'];
// Îáùèé + êîíêðåòíûé.
// Общий + конкретный.
$itemData = array_merge(
ConversionHelper::dataStringToArray(ItemModel::getItemData($this->id)),
ConversionHelper::dataStringToArray($item['data']),
Conversion::dataStringToArray(ItemModel::getItemData($this->id)),
Conversion::dataStringToArray($item['data']),
);
$this->level = intval($itemData['tr_lvl']);
}
@ -35,4 +36,5 @@ class KnowledgeTempleItem
{
return !empty($this->rowId);
}
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace DTO;
class Present
{
/** Логин отправителя
* @var string
*/
public string $sender;
/** Логин получателя
* @var string
*/
public string $receiver;
/** id подарка
* @var int
*/
public int $itemId;
/** Заголовок поздравления.
* Обычно отображается в инфе персонажа в тултипе.
* @var string
*/
public string $textTitle = '';
/** Текст поздравления
* Отображается только получателю подарка в инвентаре.
* @var string
*/
public string $text = '';
/** Флаг анонимности. Если true, в поле "отправитель" будет "невидимка".
* @var bool
*/
public bool $anonymousSender = false;
/** Флаг кланового подарка. Если true, в поле "отправитель" будет имя клана в котором состоит игрок.
* @var bool
*/
public bool $clanSender = false;
}

46
_incl_data/class/Delo.php Normal file
View File

@ -0,0 +1,46 @@
<?php
use Core\Db;
use User\UserIp;
class Delo
{
/**
* Запись в личное дело персонажа.
* @param int $type цифровой тип лога (??)
* @param string $from отправитель записи
* @param int $uid кому пишется
* @param string $text текст
* @param float $moneyOut количество денег снятых с игрока
* @param float $moneyIn количество денег полученных игроком
* @return void
*/
public static function add(int $type, string $from, int $uid, string $text, float $moneyOut = 0, float $moneyIn = 0): void
{
$sql = 'insert into users_delo (uid, time, text, login, `delete`, no_right, ip, moneyOut, moneyIn, type) values (?,unix_timestamp(),?,?,0,?,?,?,?,?)';
Db::sql($sql, [
$uid, $text, $from, '', UserIp::get(), $moneyOut, $moneyIn, $type,
]);
}
public static function printPublicModerationStatus(int $userid): void
{
$status = Db::getValue('select text from users_delo where uid = ? and hb != 0 order by id desc limit 1', [$userid]);
if (!$status) {
return;
}
echo <<<HTML
<div style="padding-left: 5px; margin: 5px 0;">
Сообщение от модераторов:<br>
<span style="color: red; background-color: bisque; font-weight: bold;">$status</span>
</div>
HTML;
}
public static function getAllByUserId(int $userid): array
{
return Db::getRows('select time, text from users_delo where uid = ? and type = 0 order by id desc', [$userid]);
}
}

View File

@ -1,5 +1,8 @@
<?php
use Helper\Conversion;
use User\ItemsModel;
class Dialog
{
private array $info;
@ -208,7 +211,7 @@ class Dialog
//Выдаем предмет для квеста
$itmb = mysql_fetch_array(mysql_query('SELECT * FROM `items_main` WHERE `id` = "' . $act1[8] . '" LIMIT 1'));
if (isset($itmb['id'])) {
\User\ItemsModel::addItem($act1[8], $u->info['id'], '|nodelete=1');
ItemsModel::addItem($act1[8], $u->info['id'], '|nodelete=1');
$txt .= '<br><b><font color=red>Вы получили предмет &quot;' . $itmb['name'] . '&quot;</font></b>';
}
}
@ -229,16 +232,16 @@ class Dialog
$txt .= ' за ' . $act1[2] . ' екр.';
}
if ($act1[3] > 0) {
$txt .= ' на срок ' . $u->timeOut($act1[3]) . '';
$act1dt .= '|srok=' . $act1[3] . '';
$txt .= ' на срок ' . Conversion::secondsToTimeout($act1[3]);
$act1dt .= '|srok=' . $act1[3];
}
$txt .= '</font></b>';
\User\ItemsModel::addItem($itmb['id'], $u->info['id'], $act1dt);
ItemsModel::addItem($itmb['id'], $u->info['id'], $act1dt);
$pg = $act1[4];
}
} else {
$txt .= '<br><b><font color=red>Неудалось приобрести предмет...</font></b>';
$txt .= '<br><b style="color: red">Неудалось приобрести предмет...</b>';
$pg = 1;
}
} elseif ($act1[0] == 'quest') {
@ -263,7 +266,7 @@ class Dialog
}
$ic2 = 1;
while ($ic2 <= $act3[2]) {
\User\ItemsModel::addItem($itmqs['id'], $u->info['id'], '|quest_item=1', ['del' => $act3[3]]);
ItemsModel::addItem($itmqs['id'], $u->info['id'], '|quest_item=1', ['del' => $act3[3]]);
$ic2++;
}
}
@ -393,7 +396,7 @@ class Dialog
if ($upd) {
if ($itik > 0) {
//Выдаем предметы
\User\ItemsModel::addItem($itik, $u->info['id'], '|nosale=1|srok=' . (7 * 86400) . '', null, 1);
ItemsModel::addItem($itik, $u->info['id'], '|nosale=1|srok=' . (7 * 86400) . '', null, 1);
$itm_nm = mysql_fetch_array(mysql_query('SELECT `name` FROM `items_main` WHERE `id` = "' . $itik . '" LIMIT 1'));
$txt = 'Вы получили предмет &quot;' . $itm_nm['name'] . '&quot;';
} else {
@ -413,7 +416,7 @@ class Dialog
}
$arts_1 = $arts_1[rand(0, count($arts_1) - 1)];
if ($arts_1 > 0) {
\User\ItemsModel::addItem($arts_1, $u->info['id'], '|sroknext=1|nosale=1|sleep_moroz=1|srok=' . (86400 / 2) . '', null, 100);
ItemsModel::addItem($arts_1, $u->info['id'], '|sroknext=1|nosale=1|sleep_moroz=1|srok=' . (86400 / 2) . '', null, 100);
}
$itm_nm = mysql_fetch_array(mysql_query('SELECT `name` FROM `items_main` WHERE `id` = "' . $arts_1 . '" LIMIT 1'));
@ -433,7 +436,7 @@ class Dialog
}
$arts_1 = $arts_1[rand(0, count($arts_1) - 1)];
if ($arts_1 > 0) {
\User\ItemsModel::addItem($arts_1, $u->info['id'], '|sroknext=1|nosale=1|sleep_moroz=1|srok=' . (86400 / 2) . '', null, 100);
ItemsModel::addItem($arts_1, $u->info['id'], '|sroknext=1|nosale=1|sleep_moroz=1|srok=' . (86400 / 2) . '', null, 100);
}
$itm_nm = mysql_fetch_array(mysql_query('SELECT `name` FROM `items_main` WHERE `id` = "' . $arts_1 . '" LIMIT 1'));
@ -523,7 +526,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
$e++;
}
$txt .= $cn[$i][$j]['n'] . ' x' . ($t[0] * $this->objLevel($cn[$i][$j], $u->info['level'])) . ' = ' . $cn[$i]['add'][1] . ' x' . $t[0] . '<br>';
@ -569,7 +572,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
$e++;
}
$txt .= $cn[$i][$j]['n'] . ' x' . ($t[0] * $this->objLevel($cn[$i][$j], $u->info['level'])) . ' = ' . $cn[$i]['add'][1] . ' x' . $t[0] . '<br>';
@ -615,7 +618,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i]['add'][0], $u->info['id'], $data);
$e++;
}
$txt .= $cn[$i][$j]['n'] . ' x' . ($t[0] * $this->objLevel($cn[$i][$j], $u->info['level'])) . ' = ' . $cn[$i]['add'][1] . ' x' . $t[0] . '<br>';
@ -647,7 +650,7 @@ class Dialog
if (isset($keypr1['id'], $keypr2['id'])) {
mysql_query('DELETE FROM `items_users` WHERE `id` = "' . $keypr1['id'] . '" OR `id` = "' . $keypr2['id'] . '" LIMIT 2');
$data = '|frompisher=' . $d->info['id2'];
\User\ItemsModel::addItem(2555, $u->info['id'], $data);
ItemsModel::addItem(2555, $u->info['id'], $data);
$txt = 'Вы успешно получили &quot;Пирамидальный ключ&quot;';
}
@ -690,7 +693,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
$e++;
}
mysql_query('DELETE FROM `items_users` WHERE `id` = "' . $keypr['id'] . '" LIMIT 1');
@ -746,7 +749,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
$e++;
}
mysql_query('DELETE FROM `items_users` WHERE `id` = "' . $keypr['id'] . '" LIMIT 1');
@ -802,7 +805,7 @@ class Dialog
$data = '|frompisher=' . $d->info['id2'];
$e = 1;
while ($e <= $t[0]) {
\User\ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
ItemsModel::addItem($cn[$i][$j]['add'][0], $u->info['id'], $data);
$e++;
}
$txt .= $cn[$i][$j]['n'] . ' x' . ($t[0] * $this->objLevel($cn[$i][$j], $u->info['level'])) . ' = ' . $cn[$i][$j]['add'][1] . ' x' . $t[0] . '<br>';
@ -957,7 +960,7 @@ class Dialog
$qsw = 0;
while ($qsw < $item['colvo']) {
$txt .= '<br/>Вы получили предмет';
\User\ItemsModel::addItem($item['item_id'], $u->info['id']);
ItemsModel::addItem($item['item_id'], $u->info['id']);
$qsw++;
}
}
@ -983,7 +986,7 @@ class Dialog
if ($this->info['tr_dn'] != $d->info['id2']) {
$go = 0;
} elseif ($this->info['x'] != 0 || $this->info['y'] != 0) {
if ($d->testLike($u->info['x'], $u->info['y'], $this->info['x'], $this->info['y']) != 1) {
if (!$d->cellIsGoodforAction($u->info['x'], $u->info['y'], $this->info['x'], $this->info['y'])) {
$go = 0;
}
//если бот погиб
@ -1021,8 +1024,7 @@ class Dialog
}
$this->title = $this->info['text'];
$this->youInfo = $u->getInfoPers($u->info['id'], 1);
$this->youInfo = $this->youInfo[0];
$this->youInfo = $u->getInfoPers($u->info['id'], 1)[0];
$this->botInfo = $this->infoBot($this->info['bot_id']);
//Диалог
$qpl = mysql_fetch_array(mysql_query('SELECT * FROM `dungeon_dlg` WHERE `type` = "1" AND `qid` = "0" AND `id_dg` = "' . $this->info['id'] . '" AND `page` = "' . ((int)$pg) . '" LIMIT 1'));
@ -1215,7 +1217,7 @@ class Dialog
$val = 4799;
}
}
\User\ItemsModel::addItem($val, $u->info['id'], $data_itm);
ItemsModel::addItem($val, $u->info['id'], $data_itm);
$i1++;
}
} elseif ($var == 'up') {

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,35 @@
<?php
namespace Enum;
enum ShopId: int
{
case MAIN = 1;
case BEREZKA = 2;
case LUKA = 5; // пещера тысячи проклятий
case FLOWER = 6;
case BOOKS = 7;
case ANIMALS = 8; // магазин новичка
case TAVERN = 9; // наковальня
case IZLOM = 10;
case BLOOD_ALTAR = 11; //алтарь крови
case TEMPLE = 14;
case MUSHROOMS = 17; // общий рыцарский
case REFERALS = 27;
case RULF_HRUNT = 33; // бездна
case SHOP_KAT = 44; // магазин рульфа хрунта, а ты что такое?
case LABORATORY = 45;
case NEWBIE = 106; // пещера мглы
case KNIGHTS_MAIN = 400; //магазин рефералов
case SHOP_PRIZ = 404; // каморка Луки
case SHOP_2 = 609; // магазин грибоеда??
case ANVIL = 700; // катакомбы
case ARTEFACTS = 777; //магазин самоцветов
case DUNGEON_BEZDNA = 801; // храм?!
case DUNGEON_PTP = 802; // излом?!
case DUNGEON_CATACOMBS = 803; //лаборатория?!?!
case DUNGEON_MISTY = 804;
case CRYSTALS = 1050;
}

View File

@ -0,0 +1,10 @@
<?php
namespace Enum;
enum StatFilterCellName: string
{
case Bonus = 'is_bonus';
case Requirement = 'is_requirement';
case Percentage = 'is_percentage';
}

View File

@ -1,21 +1,17 @@
<?php
use Core\ArraySorter;
use Core\ComparsionHelper;
use Core\Config;
use Core\Db;
use FightRequest\FRHelper;
use Helper\ArraySorter;
use Helper\Comparsion;
use Tournament\Tournament;
use Tournament\TournamentModel;
use User\Effects;
class FightRequest
{
private bool $backTest = false; // Для проверок хаотических поединков.
private static bool $bcktst;
private User $u;
public string $error = '';
public const BATTLE_RAZDEL_GROUP = 4;
public const BATTLE_RAZDEL_GROUP = 4; // Для проверок хаотических поединков.
public const BATTLE_RAZDEL_CHAOTIC = 5;
public const BATTLE_RAZDEL_CURRENT = 6;
public const BATTLE_RAZDEL_ENDED = 7;
@ -23,6 +19,10 @@ class FightRequest
private const BATTLE_TYPE_MELEE = 1;
private const BATTLE_TYPE_NO_EKR_ITEMS = 51;
private const CHAOTIC_TYPE_PRIZED = 33;
private static bool $bcktst;
public string $error = '';
private bool $backTest = false;
private User $u;
/**
* Заявки на бой.
@ -58,22 +58,22 @@ class FightRequest
return Db::getValue('select count(*) from stats where zv = ?', [$frId]);
}
/** Считаем количество людей в конкретной заявке во второй команде.
* @param int $frId id заявки
* @return int
/** Проверяем заявки
* @return void
*/
private function countUsersInTeam2(int $frId): int
private function test()
{
return Db::getValue('select count(*) from stats where zv = ? and team = 2', [$frId]);
}
private function testTravm()
{
$tr = Db::getValue(
'select v1 from eff_users where id_eff = 4 and `delete` = 0 and uid = ? order by v1 desc limit 1',
[$this->u->info['id']]
);
return $tr ? $tr - 1 : 0;
if ($this->u->info['zv'] > 0) {
$z = Db::getValue(
'select count(*) from zayvki where id = ? and (cancel > 0 or btl_id >0 or time < unix_timestamp() - 3600)',
[$this->u->info['zv']]
);
if ($z > 0) {
$this->u->info['zv'] = 0;
Db::sql('update stats set zv = 0 where id = ?', [$this->u->info['id']]);
}
}
$this->testGroupAndChaotic();
}
private function testGroupAndChaotic()
@ -83,22 +83,23 @@ class FightRequest
'select * from zayvki where btl_id = 0 and cancel = 0 and start = 0 and razdel in (4,5) order by id desc limit 22'
);
foreach ($sp as $pl) {
$uz = Db::getRow(
'select users.id, * from users left join stats on users.id = stats.id where zv = ?',
$uz = Db::getRows(
'select * from users left join stats on users.id = stats.id where zv = ?',
[$pl['id']]
);
$i = [];
$toChat = '';
$toWhere = '';
foreach ($uz as $t) {
${'tm' . $t['team']} ??= [];
$i[$t['team']] ??= 0;
${'tm' . $t['team']}[$i[$t['team']]] = $t;
$toChat .= '' . $t['login'] . ',';
$toWhere .= 'OR `id` = "' . $t['id'] . '" ';
$i[$t['team']]++;
if (is_iterable($uz)) {
foreach ($uz as $t) {
${'tm' . $t['team']} ??= [];
$i[$t['team']] ??= 0;
${'tm' . $t['team']}[$i[$t['team']]] = $t;
$toChat .= '' . $t['login'] . ',';
$toWhere .= 'OR `id` = "' . $t['id'] . '" ';
$i[$t['team']]++;
}
}
if ($pl['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
$cols = $this->countUsersAll($pl['id']);
if ($cols >= $pl['maxplayers']) {
@ -123,24 +124,6 @@ class FightRequest
}
}
/** Проверяем заявки
* @return void
*/
private function test()
{
if ($this->u->info['zv'] > 0) {
$z = Db::getValue(
'select count(*) from zayvki where id = ? and (cancel > 0 or btl_id >0 or time < unix_timestamp() - 3600)',
[$this->u->info['zv']]
);
if ($z > 0) {
$this->u->info['zv'] = 0;
Db::sql('update stats set zv = 0 where id = ?', [$this->u->info['id']]);
}
}
$this->testGroupAndChaotic();
}
private function testGroup($groups, $zayavka, $toChat, $toWhere)
{
if ($zayavka['razdel'] != 4) {
@ -162,6 +145,266 @@ class FightRequest
}
}
private function cancelGroup($zv, $uids, $debug = null)
{
Db::sql('update stats set zv = default where zv = ?', [$zv['id']]);
Db::sql('update zayvki set cancel = unix_timestamp() where id = ?', [$zv['id']]);
if (empty($uids)) {
return;
}
$text = ' Не удалось начать поединок по причине: Группа не набрана!';
if ($zv['priz'] > 0) {
$pg = $this->cancelPrizedChaotic($zv);
if (!empty($pg[0])) {
$uids = $pg[0];
}
$text .= $pg[1];
}
$chat = new Chat();
$chat->sendsys($text . $debug, $uids);
}
private function cancelPrizedChaotic(array $zv): array
{
$stmt = Db::getRows('select id from stats where zv = ?', [$zv['id']]);
foreach ($stmt as $user) {
if ($zv['type'] === self::CHAOTIC_TYPE_PRIZED) {
$stmt2 = Db::getValue('select id from users where inUser = ?', [$user['id']]);
if (!empty($stmt2)) {
Db::sql('update users set inUser = 0 where id = ?', [$stmt2]);
Db::sql('delete from users where id = ?', [$user['id']]);
Db::sql('delete from stats where id = ?', [$user['id']]);
Db::sql('delete from items_users where uid = ?', [$user['id']]);
Db::sql('delete from eff_users where uid = ?', [$user['id']]);
// \Core\ConversionHelper::dataStringToArray(4754, $user['id']);
}
} else {
// \Core\ConversionHelper::dataStringToArray(4754, $user['id']); реликвии ангела
}
}
return [
$stmt2 ?? 0,
' Вы получаете Призовой Жетон (х1)',
];
}
public function startBattle($id, $vars = null)
{
// что это?
$z = Db::getRow(
'select * from zayvki where id = ? and start = 0 and cancel = 0 and (time > unix_timestamp() - 60*60*2 or razdel > 3)',
[$id]
);
if (!isset($z['id'])) {
return;
}
$vars = explode('|-|', $vars);
if ($z['razdel'] == self::BATTLE_RAZDEL_GROUP || $z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
if ($z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
$sp = Db::getRows(
'select id, team, upLevel, btl_cof, exp from stats where zv = ? order by btl_cof desc', [$z['id']]
);
// Разбивка на команды раньше зависела от равной суммы btl_cof в командах, но как это должно было
// работать никто не знал. Теперь просто пул игроков мешается и бьётся пополам. Ins.
$pld2 = [];
$team1IdsArr = [];
$team2IdsArr = [];
foreach ($sp as $pl) {
$pld2[] = $pl;
}
shuffle($pld2);
$pieces = array_chunk($pld2, ceil(count($pld2) / 2));
foreach ($pieces[0] as $team1) {
$team1IdsArr[] = $team1['id'];
}
foreach ($pieces[1] as $team2) {
$team2IdsArr[] = $team2['id'];
}
$team1Ids = implode($team1IdsArr);
$team2Ids = implode($team2IdsArr);
Db::sql('update stats set team = 1 where id in (?)', [$team1Ids]);
Db::sql('update stats set team = 2 where id in (?)', [$team2Ids]);
}
$args = [
$z['otmorozok'],
$z['priz'],
$z['smert'],
$z['noart'],
$z['noeff'],
$z['noatack'],
$z['arand'],
$z['kingfight'],
$z['nobot'],
$z['fastfight'],
$z['razdel'],
$z['city'],
$z['timeout'],
$z['type'],
$z['invise'],
$z['travmChance'] ?? 0,
$z['exp'],
];
$q = 'insert into battle (
otmorozok,
priz,
smert,
noart,
noeff,
noatack,
arand,
kingfight,
nobot,
fastfight,
razdel,
city,
time_start,
timeout,
type,
invis,
travmChance,
addExp
) values (?,?,?,?,?,?,?,?,?,?,?,?,unix_timestamp(),?,?,?,?,?)';
//ТУТ старт боя
Db::sql($q, $args);
unset($q, $args);
$btl_id = Db::lastInsertId();
if ($btl_id) {
if ($z['type'] == self::BATTLE_TYPE_MELEE) {
Db::sql(
'update items_users set inOdet = 0 where uid in (select id from stats where zv = ?)', [$z['id']]
);
} elseif ($z['type'] == self::BATTLE_TYPE_NO_EKR_ITEMS) {
Db::sql(
'update items_users set inOdet = 0 where uid in (select id from stats where zv = ?) and 2price > 0',
[$z['id']]
);
}
//обновляем данные о поединке
Db::sql('update stats set zv = 0 where zv = ?', [$z['id']]);
$q = 'update users set battle = ' . $btl_id . ' where ' . $vars[1];
Db::sql($q);
unset($q);
//обновляем заявку, что бой начался
Db::sql('update zayvki set start = unix_timestamp(), btl_id = ? where id = ?', [$btl_id, $z['id']]);
$this->u->info['battle'] = $btl_id;
//Отправляем сообщение в чат всем бойцам
$this->sendSysChatSound($vars[0], -1);
}
} elseif ($z['razdel'] >= 1 && $z['razdel'] <= 3) {
//начало PvP
if ($this->u->info['team'] != 1 || $this->u->info['zv'] != $z['id']) {
$this->error = 'Вы не можете начать поединок.';
} else {
$enemyId = Db::getValue('select id from stats where zv = ? and team = 2 limit 1', [$z['id']]);
if (!$enemyId) {
$this->error = 'Вы не можете начать поединок, вашу заявку никто не принял.';
} else {
$enemy = Db::getRow('select login, money from users where id = ?', [$enemyId]);
//создаем поединок
if (
$enemy['money'] < $z['money'] ||
$this->u->info['money'] < $z['money']
) {
$z['money'] = 0.00;
}
$args = [
$z['otmorozok'],
$z['smert'],
$z['noart'],
$z['noeff'],
$z['noatack'],
$z['arand'],
$z['kingfight'],
$z['nobot'],
$z['fastfight'],
$this->u->info['city'],
$z['timeout'],
$z['type'],
$z['travmChance'],
$z['money'],
];
$q = 'insert into battle (
otmorozok,
smert,
noart,
noeff,
noatack,
arand,
kingfight,
nobot,
fastfight,
city,
time_start,
timeout,
type,
travmChance,
money
) values (?,?,?,?,?,?,?,?,?,?,unix_timestamp(),?,?,?,?)';
Db::sql($q, $args);
$btl_id = Db::lastInsertId();
unset($q, $args);
if (!$btl_id) {
$this->error = 'Ошибка создания битвы.';
} else {
//обновляем данные о поединке
Db::sql('update stats set zv = 0 where zv = ?', [$z['id']]);
Db::sql(
'update users set battle = ? where id = ? or id = ?',
[$btl_id, $this->u->info['id'], $enemyId]
);
//Если бой кулачный, то снимаем вещи
if ($z['type'] == self::BATTLE_TYPE_MELEE) {
Db::sql(
'update items_users set inOdet = 0 where uid in (?,?) ',
[$this->u->info['id'], $enemyId]
);
}
//обновляем заявку, что бой начался
Db::sql(
'update zayvki set start = unix_timestamp(), btl_id = ? where id = ?', [$btl_id, $z['id']]
);
$this->u->info['battle'] = $btl_id;
//Отправляем сообщение в чат всем бойцам
$this->sendSysChatSound($enemy['login']);
die('<script>location="main.php?battle_id=' . $btl_id . '";</script>');
}
}
}
}
}
/**
* Звуковой пинг в чат?
* @return void
* @todo убрать колхоз с условиями когда станет ясно как оно работает.
*/
private function sendSysChatSound(string $to = '', int $room = 0)
{
$cmsg = new ChatMessage();
if (empty($to)) {
$cmsg->setTo($this->u->info['login']);
} else {
$cmsg->setTo($to);
}
if (empty($room)) {
$cmsg->setRoom($this->u->info['room']);
} else {
$cmsg->setRoom($room);
}
$cmsg->setCity($this->u->info['city']);
$cmsg->setType(11);
$cmsg->setSound(117);
(new Chat())->sendMsg($cmsg);
}
private function testCronChaotic($zayavka, $toChat, $toWhere)
{
$chat = new Chat();
@ -225,8 +468,6 @@ class FightRequest
'id' => $botInfo['id'],
'login' => $botInfo['login'],
'level' => $botInfo['level'],
'city' => $botInfo['city'],
'cityreg' => $botInfo['city'],
'name' => $botInfo['login'],
'sex' => $botInfo['sex'],
'hobby' => '',
@ -261,6 +502,17 @@ class FightRequest
}
}
public function testCronZv()
{
$this->testCronGroupAndChaotic();
if ($this->backTest || self::$bcktst) {
self::$bcktst = false;
$this->testCronZv();
}
}
/** Проверяем хаотичные и групповые бои [в этом городе ?] */
private function testCronGroupAndChaotic(): void
{
@ -299,65 +551,6 @@ class FightRequest
}
}
public function testCronZv()
{
$this->testCronGroupAndChaotic();
if ($this->backTest || self::$bcktst) {
self::$bcktst = false;
$this->testCronZv();
}
}
private function cancelGroup($zv, $uids, $debug = null)
{
Db::sql('update stats set zv = default where zv = ?', [$zv['id']]);
Db::sql('update zayvki set cancel = unix_timestamp() where id = ?', [$zv['id']]);
if (empty($uids)) {
return;
}
$text = ' Не удалось начать поединок по причине: Группа не набрана!';
if ($zv['priz'] > 0) {
$pg = $this->cancelPrizedChaotic($zv);
if (!empty($pg[0])) {
$uids = $pg[0];
}
$text .= $pg[1];
}
$chat = new Chat();
$chat->sendsys($text . $debug, $uids);
}
private function cancelPrizedChaotic(array $zv): array
{
$stmt = Db::getRows('select id from stats where zv = ?', [$zv['id']]);
foreach ($stmt as $user) {
if ($zv['type'] === self::CHAOTIC_TYPE_PRIZED) {
$stmt2 = Db::getValue('select id from users where inUser = ?', [$user['id']]);
if (!empty($stmt2)) {
Db::sql('update users set inUser = 0 where id = ?', [$stmt2]);
Db::sql('delete from users where id = ?', [$user['id']]);
Db::sql('delete from stats where id = ?', [$user['id']]);
Db::sql('delete from items_users where uid = ?', [$user['id']]);
Db::sql('delete from eff_users where uid = ?', [$user['id']]);
\Core\ConversionHelper::dataStringToArray(4754, $user['id']);
}
} else {
\Core\ConversionHelper::dataStringToArray(4754, $user['id']);
}
}
return [
$stmt2 ?? 0,
' Вы получаете Призовой Жетон (х1)',
];
}
private function addGroupRequest()
{
}
public function addGroupOrChaoticRequest(int $r)
{
if (!in_array($r, [self::BATTLE_RAZDEL_GROUP, self::BATTLE_RAZDEL_CHAOTIC])) {
@ -502,8 +695,8 @@ class FightRequest
$nz['time_start'] = 600;
}
$nz['tm1max'] = ComparsionHelper::minimax((int)$_POST['nlogin1'], 1, 99);
$nz['tm2max'] = ComparsionHelper::minimax((int)$_POST['nlogin2'], 1, 99);
$nz['tm1max'] = Comparsion::minimax((int)$_POST['nlogin1'], 1, 99);
$nz['tm2max'] = Comparsion::minimax((int)$_POST['nlogin2'], 1, 99);
//Генерируем уровни союзника
$levels = FRHelper::getTeammatesLevel($_POST['levellogin1'], $this->u->info['level']);
@ -582,221 +775,13 @@ class FightRequest
}
}
/**
* Звуковой пинг в чат?
* @return void
* @todo убрать колхоз с условиями когда станет ясно как оно работает.
*/
private function sendSysChatSound(string $to = '', int $room = 0)
private function testTravm()
{
$cmsg = new ChatMessage();
if (empty($to)) {
$cmsg->setTo($this->u->info['login']);
} else {
$cmsg->setTo($to);
}
if (empty($room)) {
$cmsg->setRoom($this->u->info['room']);
} else {
$cmsg->setRoom($room);
}
$cmsg->setCity($this->u->info['city']);
$cmsg->setType(11);
$cmsg->setSound(117);
(new Chat())->sendMsg($cmsg);
}
public function startBattle($id, $vars = null)
{
// что это?
$z = Db::getRow(
'select * from zayvki where id = ? and start = 0 and cancel = 0 and (time > unix_timestamp() - 60*60*2 or razdel > 3)',
[$id]
$tr = Db::getValue(
'select v1 from eff_users where id_eff = 4 and `delete` = 0 and uid = ? order by v1 desc limit 1',
[$this->u->info['id']]
);
if (!isset($z['id'])) {
return;
}
$vars = explode('|-|', $vars);
if ($z['razdel'] == self::BATTLE_RAZDEL_GROUP || $z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
if ($z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
$sp = Db::getRows(
'select id, team, upLevel, btl_cof, exp from stats where zv = ? order by btl_cof desc', [$z['id']]
);
// Разбивка на команды раньше зависела от равной суммы btl_cof в командах, но как это должно было
// работать никто не знал. Теперь просто пул игроков мешается и бьётся пополам. Ins.
$pld2 = [];
$team1IdsArr = [];
$team2IdsArr = [];
foreach ($sp as $pl) {
$pld2[] = $pl;
}
shuffle($pld2);
$pieces = array_chunk($pld2, ceil(count($pld2) / 2));
foreach ($pieces[0] as $team1) {
$team1IdsArr[] = $team1['id'];
}
foreach ($pieces[1] as $team2) {
$team2IdsArr[] = $team2['id'];
}
$team1Ids = implode($team1IdsArr);
$team2Ids = implode($team2IdsArr);
Db::sql('update stats set team = 1 where id in (?)', [$team1Ids]);
Db::sql('update stats set team = 2 where id in (?)', [$team2Ids]);
}
$args = [
$z['otmorozok'],
$z['priz'],
$z['smert'],
$z['noart'],
$z['noeff'],
$z['noatack'],
$z['arand'],
$z['kingfight'],
$z['nobot'],
$z['fastfight'],
$z['razdel'],
$z['city'],
$z['timeout'],
$z['type'],
$z['invise'],
$z['travmChance'],
$z['exp'],
];
$q = 'insert into battle (
otmorozok,
priz,
smert,
noart,
noeff,
noatack,
arand,
kingfight,
nobot,
fastfight,
razdel,
city,
time_start,
timeout,
type,
invis,
travmChance,
addExp
) values (?,?,?,?,?,?,?,?,?,?,?,?,unix_timestamp(),?,?,?,?,?)';
//ТУТ старт боя
Db::sql($q, $args);
unset($q, $args);
$btl_id = Db::lastInsertId();
if ($btl_id) {
if ($z['type'] == self::BATTLE_TYPE_MELEE) {
Db::sql(
'update items_users set inOdet = 0 where uid in (select id from stats where zv = ?)', [$z['id']]
);
} elseif ($z['type'] == self::BATTLE_TYPE_NO_EKR_ITEMS) {
Db::sql(
'update items_users set inOdet = 0 where uid in (select id from stats where zv = ?) and 2price > 0',
[$z['id']]
);
}
//обновляем данные о поединке
Db::sql('update stats set zv = 0 where zv = ?', [$z['id']]);
$q = 'update users set battle = ' . $btl_id . ' where ' . $vars[1];
Db::sql($q);
unset($q);
//обновляем заявку, что бой начался
Db::sql('update zayvki set start = unix_timestamp(), btl_id = ? where id = ?', [$btl_id, $z['id']]);
$this->u->info['battle'] = $btl_id;
//Отправляем сообщение в чат всем бойцам
$this->sendSysChatSound($vars[0], -1);
}
} elseif ($z['razdel'] >= 1 && $z['razdel'] <= 3) {
//начало PvP
if ($this->u->info['team'] != 1 || $this->u->info['zv'] != $z['id']) {
$this->error = 'Вы не можете начать поединок.';
} else {
$enemyId = Db::getValue('select id from stats where zv = ? and team = 2 limit 1', [$z['id']]);
if (!$enemyId) {
$this->error = 'Вы не можете начать поединок, вашу заявку никто не принял.';
} else {
$enemy = Db::getRow('select login, money from users where id = ?', [$enemyId]);
//создаем поединок
if (
$enemy['money'] < $z['money'] ||
$this->u->info['money'] < $z['money']
) {
$z['money'] = 0.00;
}
$args = [
$z['otmorozok'],
$z['smert'],
$z['noart'],
$z['noeff'],
$z['noatack'],
$z['arand'],
$z['kingfight'],
$z['nobot'],
$z['fastfight'],
$this->u->info['city'],
$z['timeout'],
$z['type'],
$z['travmChance'],
$z['money'],
];
$q = 'insert into battle (
otmorozok,
smert,
noart,
noeff,
noatack,
arand,
kingfight,
nobot,
fastfight,
city,
time_start,
timeout,
type,
travmChance,
money
) values (?,?,?,?,?,?,?,?,?,?,unix_timestamp(),?,?,?,?)';
Db::sql($q, $args);
$btl_id = Db::lastInsertId();
unset($q, $args);
if (!$btl_id) {
$this->error = 'Ошибка создания битвы.';
} else {
//обновляем данные о поединке
Db::sql('update stats set zv = 0 where zv = ?', [$z['id']]);
Db::sql(
'update users set battle = ? where id = ? or id = ?',
[$btl_id, $this->u->info['id'], $enemyId]
);
//Если бой кулачный, то снимаем вещи
if ($z['type'] == self::BATTLE_TYPE_MELEE) {
Db::sql(
'update items_users set inOdet = 0 where uid in (?,?) ',
[$this->u->info['id'], $enemyId]
);
}
//обновляем заявку, что бой начался
Db::sql(
'update zayvki set start = unix_timestamp(), btl_id = ? where id = ?', [$btl_id, $z['id']]
);
$this->u->info['battle'] = $btl_id;
//Отправляем сообщение в чат всем бойцам
$this->sendSysChatSound($enemy['login']);
die('<script>location="main.php?battle_id=' . $btl_id . '";</script>');
}
}
}
}
return $tr ? $tr - 1 : 0;
}
public function getCurrentStatus(array $zi, int $r)
@ -822,6 +807,16 @@ class FightRequest
echo '<br>Ваш бой начнется через ' . $tm_start . ' мин.';
}
/** Дописывает значение после точки, если такового нет. 1 -> 1.0, 1.1 -> 1.1
* @param string $str
* @return string
*/
public function rzv(string $str): string
{
$symbols = explode('.', $str);
return isset($symbols[1]) ? $symbols[0] . '.' . $symbols[1] : $symbols[0] . '.0';
}
public function getEndedBattlesList(string $slogin, int $dt)
{
$code = PassGen::intCode();
@ -936,7 +931,7 @@ class FightRequest
$teams = ArraySorter::groupBy($cb, 'team');
foreach ($teams as $teamId => $team) {
foreach ($team as $key => $player) {
$players .= $this->u->microLogin($player['id']);
$players .= $this->u->getLogin($player['id']);
if ($key !== array_key_last($team)) {
$players .= ', ';
} else {
@ -999,16 +994,6 @@ class FightRequest
/** Конец турниров от Insallah. */
}
/** Дописывает значение после точки, если такового нет. 1 -> 1.0, 1.1 -> 1.1
* @param string $str
* @return string
*/
public function rzv(string $str): string
{
$symbols = explode('.', $str);
return isset($symbols[1]) ? $symbols[0] . '.' . $symbols[1] : $symbols[0] . '.0';
}
public function seeZv(array $zi, int $r)
{
$code = PassGen::intCode();
@ -1053,7 +1038,7 @@ class FightRequest
$uids = Db::getColumn('select id from stats where zv = ?', [$pl['id']]);
$cols = count($uids);
foreach ($uids as $uid) {
$tm .= $this->u->microLogin($uid) . ', ';
$tm .= $this->u->getLogin($uid) . ', ';
}
$tm = rtrim($tm, ', ');
@ -1064,7 +1049,7 @@ class FightRequest
$unvs = '';
if ($pl['invise'] == 1) {
$userslist = $this->u->isModerator() ? $tm : '';
$tm = '<span style="color:maroon">' . $this->u->microLogin($pl['creator']) . '</span>' .
$tm = '<span style="color:maroon">' . $this->u->getLogin($pl['creator']) . '</span>' .
$userslist . ' - <i>невидимый</i>';
$unvs = ' Участников: ' . $cols . ' чел. ';
$n1tv .= ' <img src="' . Config::img() . '/i/fighttypehidden0.gif" title="Невидимый">';
@ -1158,9 +1143,9 @@ class FightRequest
$tmc = [];
$users = Db::getRows('select team, id from stats where zv = ?', [$pl['id']]);
foreach ($users as $user) {
${'tm' . $user['team']} .= $this->u->microLogin($user['id']) . ', ';
${'tm' . $user['team']} .= $this->u->getLogin($user['id']) . ', ';
$tmc[$user['team']]++;
$teams[$user['team']][] = $this->u->microLogin($user['id']);
$teams[$user['team']][] = $this->u->getLogin($user['id']);
}
foreach ($teams as $id => $members) {
@ -1210,14 +1195,17 @@ class FightRequest
HTML;
if ($r === self::BATTLE_RAZDEL_CHAOTIC) {
if (!$this->u->info['no_zv_key']): ?>
if (!$this->u->info['no_zv_key']):
$security = new Captcha\Captcha();
?>
<div style="float:left;">
<form method="post" style="margin:0px;padding:0px;"
action="/main.php?zayvka=1&r=<?= $r ?>&rnd=<?= $code ?>"><br>
<img src="/show_reg_img/security2.php?id='<?= time() ?>" width="70" height="20">
<form method="post" style="margin:0px;padding:0px;" action="/main.php?zayvka=1&r=<?= $r ?>&rnd=<?= $code ?>"><br>
<?php $security->width(70)->height(20)->newImage();
$_SESSION['code'] = $security->getSum(); ?>
Код подтверждения: <input style="width:40px;" type="text" name="code21">
<input class="btn" type="submit" value="Принять вызов"><br><?= $zvb ?>
<img src="/show_reg_img/security2.php?id=<?= time() ?>" width="70" height="20">
<?php $security->width(70)->height(20)->newImage();
$_SESSION['code'] = $security->getSum(); ?>
Код подтверждения: <input style="width:40px;" type="text" name="code22">
<input class="btn" style="margin-top:1px;" type="submit" value="Принять вызов">
</form>
@ -1252,6 +1240,41 @@ class FightRequest
return $this->u->info['id'];
}
/** Считаем количество людей в конкретной заявке во второй команде.
* @param int $frId id заявки
* @return int
*/
private function countUsersInTeam2(int $frId): int
{
return Db::getValue('select count(*) from stats where zv = ? and team = 2', [$frId]);
}
public function go(int $id)
{
global $zi;
if (empty($id) || !empty($this->u->info['battle'])) {
return;
}
if (isset($zi['id'])) {
$this->error = 'Вы не можете принять бой. Сначала отзовите свою заявку.';
return;
}
$z = Db::getRow(
'select * from zayvki where id = ? and start = 0 and cancel = 0 and time > unix_timestamp() - 60*60*2',
[$id]
);
if (!isset($z['id'])) {
$this->error = 'Заявка на бой не найдена.';
return;
}
if ($z['razdel'] == self::BATTLE_RAZDEL_GROUP) {
$this->joinGroup($z);
} elseif ($z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
$this->joinChaotic($z);
}
}
/** Принять групповую заявку.
* @param array $z заявка
* @return void
@ -1591,7 +1614,7 @@ class FightRequest
$items = $classItems[$sellclass];
foreach ($items as $slot => $itemId) {
$re = \Core\ConversionHelper::dataStringToArray($itemId, $uidb);
$re = Helper\Conversion::dataStringToArray($itemId, $uidb);
$stmt1->execute([$slot, $re]);
$stmt2->execute([$itemId, $re]);
}
@ -1608,29 +1631,8 @@ class FightRequest
echo '<script>location="/main.php";</script>';
}
public function go(int $id)
private function addGroupRequest()
{
global $zi;
if (empty($id) || !empty($this->u->info['battle'])) {
return;
}
if (isset($zi['id'])) {
$this->error = 'Вы не можете принять бой. Сначала отзовите свою заявку.';
return;
}
$z = Db::getRow(
'select * from zayvki where id = ? and start = 0 and cancel = 0 and time > unix_timestamp() - 60*60*2',
[$id]
);
if (!isset($z['id'])) {
$this->error = 'Заявка на бой не найдена.';
return;
}
if ($z['razdel'] == self::BATTLE_RAZDEL_GROUP) {
$this->joinGroup($z);
} elseif ($z['razdel'] == self::BATTLE_RAZDEL_CHAOTIC) {
$this->joinChaotic($z);
}
}
}

View File

@ -32,7 +32,7 @@ class Filter
if ($add > 0) {
$on = mysql_fetch_array(mysql_query('SELECT * FROM `online` WHERE `uid` = "' . $uid . '" LIMIT 1'));
if (isset($on['id'])) {
if (isset($on['uid'])) {
$mt = 0;
$lst = time();
if (date('d', $on['lastUp']) != date('d', $lst)) {
@ -42,7 +42,7 @@ class Filter
}
$add = $on['time_all'] + $add;
mysql_query(
'UPDATE `online` SET `mainTime` = "' . $mt . '",`time_today` = "' . $on['time_today'] . '",`lastUp` = "' . $lst . '",`time_all` = "' . $add . '" WHERE `id` = "' . $on['id'] . '" LIMIT 1'
'UPDATE `online` SET `mainTime` = "' . $mt . '",`time_today` = "' . $on['time_today'] . '",`lastUp` = "' . $lst . '",`time_all` = "' . $add . '" WHERE `uid` = "' . $on['uid'] . '" LIMIT 1'
);
}
}

View File

@ -1,6 +1,6 @@
<?php
namespace Core;
namespace Helper;
class ArraySorter
{
/**

View File

@ -0,0 +1,23 @@
<?php
namespace Helper;
class Comparsion
{
/** Íå äà¸ò çíà÷åíèþ âûéòè çà ïðåäåëû.
* @param $value
* @param $minimum
* @param $maximum
* @return mixed
*/
public static function minimax($value, $minimum, $maximum): mixed
{
if ($value < $minimum) {
$value = $minimum;
}
if ($value > $maximum) {
$value = $maximum;
}
return $value;
}
}

View File

@ -0,0 +1,69 @@
<?php
namespace Helper;
use DateTime;
class Conversion
{
/** Превращает строку data ('a=1|b=2|c=3') из БД в массив [a=>1, b=>2, c=>3].
* @param string|null $dataString
* @return array
*/
public static function dataStringToArray(?string $dataString): array
{
if (empty($dataString)) {
return [];
}
$dataString = str_replace('||', '|', $dataString); // любители забивать руками параметры и задваивать разделители.
if (mb_substr($dataString, -1) === '|') {
$dataString = rtrim($dataString, '|');
}
$arr = json_decode(str_replace(['=', '|'], ['":', ',"'], '{"' . $dataString . '}'), true);
return $arr ?: [];
}
/** Превращает массив [a=>1, b=>2, c=>3] в строку data ('a=1|b=2|c=3') для БД.
* @param array $dataArray
* @return string
*/
public static function arrayToDataString(array $dataArray): string
{
$str = json_encode($dataArray);
return $str ? str_replace(['":', ',"', '{"', '}'], ['=', '|'], $str) : '';
}
/** Превращает количество секунд в человекопонятное Х мес. Х дн. Х ч. Х мин. Х сек.,
* используемое обычно для отображения игровых таймаутов.
* @param int|string $seconds
* @return string
*/
public static function secondsToTimeout(int|string $seconds): string
{
$seconds = (int)$seconds;
$time = new DateTime();
$time->setTimestamp($seconds);
$sec = intval($time->format('s'));
$min = intval($time->format('i'));
$hr = intval($time->format('G'));
$day = intval($time->format('j'));
$month = intval($time->format('n'));
$timeout = '';
if ($month > 1) {
$timeout .= $month . ' мес. ';
}
if ($day > 1) {
$timeout .= $day . ' дн. ';
}
if ($hr) {
$timeout .= $hr . ' ч. ';
}
if ($sec && !$min) {
$timeout .= $sec . ' сек. ';
} elseif ($min) {
$timeout .= $min . ' мин. ';
}
return $timeout;
}
}

View File

@ -0,0 +1,36 @@
<?php
namespace Helper;
use PHPMailer\PHPMailer\Exception;
use PHPMailer\PHPMailer\PHPMailer;
class Mail
{
public static function send($to, $message, $subject = 'Бойцовский клуб'): int
{
$mail = new PHPMailer;
try {
$mail->IsSMTP();
$mail->Host = 'smtp.mail.yahoo.com';
$mail->SMTPAuth = true;
$mail->Username = 'newcombats@yahoo.com';
$mail->Password = 'uqcdbnsoagxcyysh';
$mail->SMTPSecure = PHPMailer::ENCRYPTION_STARTTLS;
$mail->Port = 587;
$mail->CharSet = 'UTF-8';
$mail->setFrom('newcombats@yahoo.com', 'Бойцовский Клуб');
$mail->addAddress($to); // Add a recipient
$mail->IsHTML();
$mail->Subject = $subject;
$mail->Body = '<div>' . $message . '</div>';
$mail->AltBody = $message;
$mail->send();
return 1;
} catch (Exception $e) {
return 0;
}
}
}

View File

@ -0,0 +1,43 @@
<?php
namespace Helper;
/** All raw mathematics in one place. */
class Math
{
/**
* @param float|int $total
* @param int|null $number
* @return float
*/
public static function getPercentage($total, ?int $number): float
{
if (is_null($number)) {
return 0;
}
return $total > 0 ? round(($number * 100) / $total, 2) : 0;
}
public static function get100Percentage($total, ?int $number)
{
if (is_null($number)) {
return 0;
}
return min(self::getPercentage($total, $number), 100);
}
/** Number-20% and Number+20% */
public static function get20PercentRange($number): array
{
return [
'min' => $number * ((100 - 20) / 100),
'max' => $number * ((100 + 20) / 100),
];
}
public static function addPercent($num, $percent)
{
return $num + (($percent / 100) * $num);
}
}

View File

@ -0,0 +1,21 @@
<?php
namespace Helper;
class Table
{
public static function get($rows, $class = '', $fill = false): string
{
$c = '';
$maxRows = sizeof(max($rows));
foreach ($rows as $row) {
if ($fill && sizeof($row) < $maxRows) {
$row = array_merge($row, array_fill(0, $maxRows - sizeof($row), ''));
}
$c .= '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
return (!empty($class) ? "<table class='$class'>" : '<table>') . $c . '</table>' . PHP_EOL;
}
}

View File

@ -0,0 +1,27 @@
<?php
use Core\Db;
class Images
{
public static function getSrc(int $id): string
{
$i = Db::getRow('select mime_type, img from images where id = ?', [$id]);
return 'data:' . $i['mime_type'] . ';base64,' . base64_encode($i['img']);
}
public static function getSrcByName(string $name): string
{
$i = Db::getRow('select mime_type, img from images where id = (select logo from clan where name = ?)', [$name]);
return 'data:' . $i['mime_type'] . ';base64,' . base64_encode($i['img']);
}
public static function getJson(int $id)
{
$stmt = Db::getRow('select mime_type, img from images where id = ?', [$id]);
if (!$stmt) {
$stmt = [];
}
return json_encode($stmt);
}
}

View File

@ -0,0 +1,145 @@
<?php
namespace Inf;
use Core\Config;
use Core\Db;
class Awards
{
private const KNIGHT = [
1 => 'Рыцарь первого круга',
2 => 'Рыцарь второго круга',
3 => 'Рыцарь третьего круга',
];
private const SCHOLAR = [
1 => 'Посвящённый первого круга',
2 => 'Посвящённый второго круга',
3 => 'Посвящённый третьего круга',
];
private const IZLOM = [
1 => 'Аттестованный боец',
2 => 'Опытный боец',
3 => 'Ветеран',
4 => 'Генерал',
];
private const DUNGEON_NAME = [
'repdreamscity' => 'Водосток',
'repizlom' => 'Излом Хаоса',
'rep1' => 'Храм Знаний',
];
private array $awards = [];
public function __construct(int $userid)
{
$reputations = Db::getRow('select * from rep where id = ?', [$userid]) ?: [];
$customAwards = Db::getRows('select text, img from users_ico where uid = ? and (endTime = 0 or endTime > unix_timestamp())', [$userid]);
foreach ($customAwards as $award) {
$this->awards[] = ['', $award['text'], $award['img']];
}
if (!empty($reputations)) {
$this->addDungeonAwards($reputations);
}
}
private function addDungeonAwards(mixed $reputations): void
{
match (true) {
$reputations['repdreamscity'] > 9999 => $this->awards[] = [self::DUNGEON_NAME['repdreamscity'], self::KNIGHT[3], 'i/ico/ric_kanal3.gif'],
$reputations['repdreamscity'] > 4999 => $this->awards[] = [self::DUNGEON_NAME['repdreamscity'], self::KNIGHT[2], 'i/ico/ric_kanal2.gif'],
$reputations['repdreamscity'] > 999 => $this->awards[] = [self::DUNGEON_NAME['repdreamscity'], self::KNIGHT[1], 'i/ico/ric_kanal1.gif'],
default => '',
};
match (true) {
$reputations['rep1'] > 9999 => $this->awards[] = [self::DUNGEON_NAME['rep1'], self::SCHOLAR[3], 'znrune_3.gif'],
$reputations['rep1'] > 999 => $this->awards[] = [self::DUNGEON_NAME['rep1'], self::SCHOLAR[2], 'znrune_2.gif'],
$reputations['rep1'] > 99 => $this->awards[] = [self::DUNGEON_NAME['rep1'], self::SCHOLAR[1], 'znrune_1.gif'],
default => '',
};
match (true) {
$reputations['repizlom'] > 24999 => $this->awards[] = [self::DUNGEON_NAME['repizlom'], self::IZLOM[4], 'iz_zn_ver10_4.gif'],
$reputations['repizlom'] > 9999 => $this->awards[] = [self::DUNGEON_NAME['repizlom'], self::IZLOM[3], 'iz_zn_ver10_3.gif'],
$reputations['repizlom'] > 999 => $this->awards[] = [self::DUNGEON_NAME['repizlom'], self::IZLOM[2], 'iz_zn_ver10_2.gif'],
$reputations['repizlom'] > 99 => $this->awards[] = [self::DUNGEON_NAME['repizlom'], self::IZLOM[1], 'iz_zn_ver10_1.gif'],
default => '',
};
match (true) {
$reputations['repcapitalcity'] > 24999 => $this->awards[] = ['Capital city', self::KNIGHT[2], 'zn1_2.gif'],
$reputations['repcapitalcity'] > 9999 => $this->awards[] = ['Capital city', self::KNIGHT[1], 'zn1_1.gif'],
default => '',
};
match (true) {
$reputations['repangelscity'] > 24999 => $this->awards[] = ['Angels city', self::KNIGHT[2], 'zn2_2.gif'],
$reputations['repangelscity'] > 9999 => $this->awards[] = ['Angels city', self::KNIGHT[1], 'zn2_1.gif'],
default => '',
};
match (true) {
$reputations['repdemonscity'] > 24999 => $this->awards[] = ['Demons city', self::KNIGHT[2], 'zn3_2.gif'],
$reputations['repdemonscity'] > 9999 => $this->awards[] = ['Demons city', self::KNIGHT[1], 'zn3_1.gif'],
default => '',
};
match (true) {
$reputations['repdevilscity'] > 24999 => $this->awards[] = ['Devils city', self::KNIGHT[2], 'zn4_2.gif'],
$reputations['repdevilscity'] > 9999 => $this->awards[] = ['Devils city', self::KNIGHT[1], 'zn4_1.gif'],
default => '',
};
match (true) {
$reputations['repsuncity'] > 24999 => $this->awards[] = ['Sun city', self::KNIGHT[2], 'zn5_2.gif'],
$reputations['repsuncity'] > 9999 => $this->awards[] = ['Sun city', self::KNIGHT[1], 'zn5_1.gif'],
default => '',
};
match (true) {
$reputations['repsandcity'] > 24999 => $this->awards[] = ['Sand city', self::KNIGHT[2], 'zn7_2.gif'],
$reputations['repsandcity'] > 9999 => $this->awards[] = ['Sand city', self::KNIGHT[1], 'zn7_1.gif'],
default => '',
};
match (true) {
$reputations['repemeraldscity'] > 24999 => $this->awards[] = ['Emeralds city', self::KNIGHT[2], 'zn6_2.gif'],
$reputations['repemeraldscity'] > 9999 => $this->awards[] = ['Emeralds city', self::KNIGHT[1], 'zn6_1.gif'],
default => '',
};
match (true) {
$reputations['repmooncity'] > 24999 => $this->awards[] = ['Moon city', self::KNIGHT[2], 'zn9_2.gif'],
$reputations['repmooncity'] > 9999 => $this->awards[] = ['Moon city', self::KNIGHT[1], 'zn9_1.gif'],
default => '',
};
match (true) {
$reputations['repabandonedplain'] > 9999 => $this->awards[] = ['Гора Легиона', self::KNIGHT[2], '1_gora.gif'],
$reputations['repabandonedplain'] > 999 => $this->awards[] = ['Гора Легиона', self::KNIGHT[1], '2_gora.gif'],
default => '',
};
}
public function addCustom(string $name, string $description, string $image): void
{
$this->awards[] = [$name, $description, $image];
}
public function print(): void
{
foreach ($this->awards as $award) {
$img = Config::img() . DIRECTORY_SEPARATOR . $award[2];
if (!empty($award[0])) {
$award[1] = "<b>$award[0]</b><br>$award[1]";
}
echo <<<HTML
<img src="$img" alt="" onmouseover="top.hi(this,'$award[1]',event,0,0,1,0);" onmouseout="top.hic();" onmousedown="top.hic();" style="cursor: pointer;">
HTML;
}
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace Inf;
use Core\Db;
use DateTimeImmutable;
class LastNames
{
private array $lastnames = [];
/** История имён
* @param int $userid
*/
public function __construct(int $userid)
{
$names = Db::getRows('select * from lastnames where uid = ? order by time desc', [$userid]);
$dt = new DateTimeImmutable();
foreach ($names as $name) {
$dt->setTimestamp($name['time']);
$this->lastnames[] = "«{$name['login']}» до " . $dt->format('d.m.Y H:i');
}
}
public function print(): void
{
echo $this->get();
}
private function get(): string
{
if (empty($this->lastnames)) {
return '';
}
return 'История имен:<br>' . implode('<br>', $this->lastnames);
}
}

View File

@ -0,0 +1,38 @@
<?php
namespace Inf;
use Core\Config;
use Helper\Conversion;
class Status
{
private array $statuses;
public function add(bool $condition, string $text, int|string|null $timeout = 0, ?string $img = ''): void
{
if (!$condition) {
return;
}
if (!empty($timeout)) {
$text .= ' ещё ' . Conversion::secondsToTimeout($timeout - time());
}
$text = "<span style='vertical-align:middle;'>$text</span>";
if (!empty($img)) {
$text = '<span><img src="' . Config::img() . DIRECTORY_SEPARATOR . $img . '" alt="' . $text . '" style="vertical-align:middle;"></span> ' . $text;
}
$this->statuses[] = "<div>$text</div>"; // обёртка для центрирования картинки с текстом
}
public function print(): void
{
if (empty($this->statuses)) {
return;
}
echo '<br><div style="font-size: smaller;">' . implode('<br>', $this->statuses) . '</div>';
}
}

View File

@ -0,0 +1,39 @@
<?php
namespace Inf;
use Core\Db;
class Twinks
{
private array $twinks = [];
/** Мульты персонажа
* @param int $userid
* @param int $twinkid
*/
public function __construct(int $userid, int $twinkid)
{
$twinks = Db::getRows('select login, level, twink from users_twink where uid = ? and twink != 0', [$userid]);
foreach ($twinks as $twink) {
$str = $twink['login'] . ' [' . $twink['level'] . ']';
if ($twinkid === $twink['twink']) {
$str = '<b style="color:#ff9900;">' . $str . '</b>';
}
$this->twinks[] = $str;
}
}
public function print(): void
{
echo $this->get();
}
private function get(): string
{
if (empty($this->twinks)) {
return '';
}
return 'Другие образы: ' . implode(', ', $this->twinks) . '<br>';
}
}

View File

@ -0,0 +1,68 @@
<?php
namespace Inf;
use Core\Config;
class Zodiac
{
private const ZODIAC = [
1 => 'Овен',
2 => 'Телец',
3 => 'Близнецы',
4 => 'Рак',
5 => 'Лев',
6 => 'Дева',
7 => 'Весы',
8 => 'Скорпион',
9 => 'Стрелец',
10 => 'Козерог',
11 => 'Водолей',
12 => 'Рыбы',
];
private int $day = 0;
private int $month = 0;
public function __construct(string $date)
{
[$d, $m, $y] = explode('.', $date);
if (!checkdate($d, $m, $y)) {
return;
}
$this->day = (int)$d;
$this->month = (int)$m;
}
public function getImageLink(): string
{
if (empty($this->getName())) {
return '#';
}
$id = array_flip(self::ZODIAC);
return Config::img() . '/i/zodiac/' . $id[$this->getName()] . '.gif';
}
public function getName(): string
{
if (empty($this->day) || empty($this->month)) {
return '';
}
$z = [
1 => self::ZODIAC[10],
self::ZODIAC[11],
self::ZODIAC[12],
self::ZODIAC[1],
self::ZODIAC[2],
self::ZODIAC[3],
self::ZODIAC[4],
self::ZODIAC[5],
self::ZODIAC[6],
self::ZODIAC[7],
self::ZODIAC[8],
self::ZODIAC[9],
self::ZODIAC[10],
];
$lastDay = [1 => 19, 18, 20, 20, 21, 21, 22, 22, 21, 22, 21, 20, 19];
return $this->day > $lastDay[$this->month] ? $z[$this->month + 1] : $z[$this->month];
}
}

View File

@ -1,16 +0,0 @@
<?php
//use Insallah\Tournament;
//require_once 'Core/Db.php';
require_once 'Core/Math.php';
require_once 'Core/Table.php';
require_once 'Runes/Runes.php';
//require_once 'Tournament/Tournament.php';
//require_once 'Tournament/TournamentModel.php';
require_once 'Achievements.php';
//Вместо крона для турнира.
//if (Tournament::IS_ENABLED) {
// (new Tournament())->startAllBattles();
//}

View File

@ -1,165 +0,0 @@
<?php
namespace Insallah;
//use Core\Database;
use Exception;
//use http\Message;
use PDO;
use PDOException;
use PDOStatement;
class DbOld
{
/**
* Настройки подключения
* Лучше выносить в конфиг
* self::DB_HOST -> Config::DB_HOST
*/
const DB_HOST = '127.0.0.1'; // localhost
const DB_USER = 'newcom1_abk';
const DB_PASSWORD = '4nWYsIM[c?}P';
const DB_NAME = 'newcom1_abk';
const CHARSET = 'utf8mb4';
const DB_PREFIX = '';
/**
* @var PDO
*/
static private $db;
/**
* @var null
*/
protected static $instance = null;
/**
* DB constructor.
* @throws Exception
*/
public function __construct()
{
if (self::$instance === null) {
try {
self::$db = new PDO(
'mysql:host=' . self::DB_HOST . ';dbname=' . self::DB_PREFIX . self::DB_NAME,
self::DB_USER,
self::DB_PASSWORD,
[
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES " . self::CHARSET,
]
);
// self::$db = Database::pdoinit();
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
return self::$instance;
}
/**
* @param $stmt
* @return PDOStatement
*/
public static function query($stmt)
{
return self::$db->query($stmt);
}
/**
* @param $stmt
* @return PDOStatement
*/
public static function prepare($stmt)
{
return self::$db->prepare($stmt);
}
/**
* @param $query
* @return int
*/
static public function exec($query)
{
return self::$db->exec($query);
}
/**
* @return string
*/
static public function lastInsertId()
{
return self::$db->lastInsertId();
}
/**
* @param $query
* @param array $args
* @return PDOStatement
* @throws Exception
*/
public static function run($query, $args = [])
{
try {
if (!$args) {
return self::query($query);
}
$stmt = self::prepare($query);
$stmt->execute($args);
return $stmt;
} catch (PDOException $e) {
throw new Exception($e->getMessage());
}
}
/**
* @param $query
* @param array $args
* @return mixed
*/
public static function getRow($query, $args = [])
{
return self::run($query, $args)->fetch();
}
/**
* @param $query
* @param array $args
* @return array
*/
public static function getRows($query, $args = [])
{
return self::run($query, $args)->fetchAll();
}
/**
* @param $query
* @param array $args
* @return mixed
*/
public static function getValue($query, $args = [])
{
$result = self::getRow($query, $args);
if (!empty($result)) {
$result = array_shift($result);
}
return $result;
}
/**
* @param $query
* @param array $args
* @return array
*/
public static function getColumn($query, $args = [])
{
return self::run($query, $args)->fetchAll(PDO::FETCH_COLUMN);
}
public static function sql($query, $args = [])
{
self::run($query, $args);
}
}

View File

@ -1,43 +0,0 @@
<?php
namespace Insallah;
/** All raw mathematics in one place. */
class Math
{
/**
* @param float|int $total
* @param int|null $number
* @return float
*/
public static function getPercentage($total, ?int $number): float
{
if (is_null($number)) {
return 0;
}
return $total > 0 ? round(($number * 100) / $total, 2) : 0;
}
public static function get100Percentage($total, ?int $number)
{
if (is_null($number)) {
return 0;
}
return min(self::getPercentage($total, $number), 100);
}
/** Number-20% and Number+20% */
public static function get20PercentRange($number): array
{
return [
'min' => $number * ((100 - 20) / 100),
'max' => $number * ((100 + 20) / 100),
];
}
public static function addPercent($num, $percent)
{
return $num + (($percent / 100) * $num);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace Insallah;
class Table
{
public static function get($rows, $class = '', $fill = false)
{
$c = '';
$max_rows = sizeof(max($rows));
foreach ($rows as $row) {
if ($fill && sizeof($row) < $max_rows) {
$row = array_merge($row, array_fill(0, $max_rows - sizeof($row), ''));
}
$c .= '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
return (!empty($class) ? "<table class='$class'>" : '<table>') . $c . '</table>' . PHP_EOL;
}
}

View File

@ -1,37 +0,0 @@
<?php
namespace Insallah;
/** All raw mathematics in one place. */
class Math
{
/**
* @param float|int $total
* @param int|null $number
* @return float
*/
public static function getPercentage($total, int $number): float
{
return $total > 0 ? round(($number * 100) / $total, 2) : 0;
}
public static function get100Percentage($total, int $number)
{
return min(self::getPercentage($total, $number), 100);
}
/** Number-20% and Number+20% */
public static function get20PercentRange($number): array
{
return [
'min' => $number * ((100 - 20) / 100),
'max' => $number * ((100 + 20) / 100),
];
}
public static function addPercent($num, $percent)
{
return $num + (($percent / 100) * $num);
}
}

View File

@ -1,22 +0,0 @@
<?php
namespace Insallah;
class Table
{
public static function get($rows, $class = '', $fill = false)
{
$c = '';
$max_rows = sizeof(max($rows));
foreach ($rows as $row) {
if ($fill && sizeof($row) < $max_rows) {
$row = array_merge($row, array_fill(0, $max_rows - sizeof($row), ''));
}
$c .= '<tr><td>' . implode('</td><td>', $row) . '</td></tr>';
}
return (!empty($class) ? "<table class='$class'>" : '<table>') . $c . '</table>' . PHP_EOL;
}
}

View File

@ -19,7 +19,7 @@ class Config
const STEP_EKR = 151;
const DELAY_EFFECT_ID = 486;
const CUSTOM_BATTLE_ID = 25000;
const PRIZE_ITEM_ID = 4754;
const PRIZE_ITEM_ID = 0;
const RETURN_ROOM = 9;
const MINIMUM_USER_LEVEL = 8;

View File

@ -0,0 +1,67 @@
<?php
namespace Item\Data;
use Model\Constant\Stat;
class Bonuses
{
private Stat $stat;
private array $result = [];
public function __construct(array $data)
{
$this->stat = new Stat();
foreach ($data as $bonusName => $value) {
if (!$this->stat->getBonusNames()[$bonusName]) {
$this->result[$bonusName] = $value; //fixme на период отладки для отлова забытых
//continue;
}
$this->result[$this->stat->getBonusNames()[$bonusName]] = $value;
}
$this->armor($data);
}
private function armor(array $data): void
{
$min = 0;
$max = 0;
$type = [
1 => 'головы',
2 => 'корпуса',
3 => 'пояса',
4 => 'ног',
];
foreach ($type as $k => $v) {
if (!empty($data['mib' . $k])) {
$min = $data['mib' . $k];
$max = $data['mib' . $k];
}
if (!empty($data['mab' . $k])) {
if (empty($data['mib' . $k])) {
$min = $data['mab' . $k];
}
$max = $data['mab' . $k];
}
if (empty($min) && empty($max)) {
return;
}
$this->result['Броня ' . $v] = $min . ' - ' . $max;
}
}
public function get(): array
{
return $this->result;
}
public function addZonb(): void
{
if (isset($this->result[$this->stat->getBonusNames()['zonb']])) {
$this->result[$this->stat->getBonusNames()['zonb']]++;
} else {
$this->result[$this->stat->getBonusNames()['zonb']] = 1;
}
}
}

View File

@ -0,0 +1,41 @@
<?php
namespace Item\Data;
class Properties
{
public static array $names = [
'damage' => 'Урон',
];
private array $result = [];
public function __construct(array $data)
{
$this->damage($data);
}
private function damage(array $data): void
{
$min = 0;
$max = 0;
if (!empty($data['yron_min'])) {
$min = $data['yron_min'];
$max = $data['yron_min'];
}
if (!empty($data['yron_max'])) {
if (empty($data['yron_min'])) {
$min = $data['yron_max'];
}
$max = $data['yron_max'];
}
if (empty($min) && empty($max)) {
return;
}
$this->result[self::$names['damage']] = $min . ' - ' . $max;
}
public function get(): array
{
return $this->result;
}
}

View File

@ -0,0 +1,72 @@
<?php
namespace Item\Data;
use Model\Constant\Stat;
class Requirements
{
private static array $sex = [
0 => 'Мужской',
1 => 'Женский',
];
private static array $align = [
1 => 'Свет',
2 => 'Хаос',
3 => 'Тьма',
7 => 'Нейстралитет',
9 => 'Дитя подземелья',
];
private int $alignValue = 0;
private array $result = [];
private Stat $stat;
public function __construct(array $data)
{
$this->stat = new Stat();
foreach ($data as $requirementName => $value) {
if (!$this->stat->getRequirementNames()[$requirementName]) {
$this->result[$requirementName] = $value; //fixme на период отладки для отлова забытых
//continue;
}
if ($requirementName === 'sex') {
if (self::$sex[$value]) {
$value = self::$sex[$value];
} else {
continue;
}
}
if ($requirementName === 'align') {
if (self::$align[$value]) {
$this->alignValue = $value;
$this->result[$requirementName]['sysvalue'] = $value;
$value = self::$align[$value];
} else {
continue;
}
}
//$this->result[$this->stat->getRequirementNames()[$requirementName]] = $value;
$this->result[$requirementName] = [
'name' => $this->stat->getRequirementNames()[$requirementName],
'value' => $value,
];
}
}
public function get(): array
{
return $this->result;
}
/** Число для отрисовки иконки.
* @return int
*/
public function getAlign(): int
{
return $this->alignValue;
}
}

View File

@ -0,0 +1,51 @@
<?php
namespace Item;
use Core\Db;
use Helper\Conversion;
class DataModel
{
private array $data = [];
public function __construct(int $itemId)
{
$datastring = Db::getValue('select data from items_main_data where items_id = ?', [$itemId]);
if (empty($datastring)) {
return;
}
$this->data = Conversion::dataStringToArray($datastring);
}
public function getAll(): array
{
return $this->data;
}
public function getRequirements(): array
{
return $this->getPrefixed('tr_');
}
private function getPrefixed(string $prefix): array
{
$result = [];
foreach ($this->data as $k => $v) {
if (str_starts_with($k, $prefix)) {
$result[str_replace($prefix, '', $k)] = $v;
}
}
return $result;
}
public function getBonuses(): array
{
return $this->getPrefixed('add_');
}
public function getProperties(): array
{
return $this->getPrefixed('sv_');
}
}

View File

@ -4,6 +4,7 @@ namespace Location;
use Chat;
use ChatMessage;
use Delo;
use User;
class DeathTower
@ -12,7 +13,7 @@ class DeathTower
{
$user = User::start();
if ($bu) {
/* в этом бою проверяем юзеров */
/* <EFBFBD> <20><><EFBFBD><EFBFBD> <20><><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> */
$i = 0;
while ($i < count($bu[$i])) {
if ($bu[$i]['lose'] > 0 || $bu[$i]['nich']) {
@ -22,7 +23,7 @@ class DeathTower
mysql_query(
'UPDATE `bs_turnirs` SET `users_finish` = `users_finish` + 1 WHERE `id` = "' . $id['id'] . '" LIMIT 1'
);
/* удаляем юзера */
/* <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD> */
if ($bu['inBot'] == 0) {
$pls1 = mysql_fetch_array(
mysql_query(
@ -33,7 +34,7 @@ class DeathTower
mysql_query('DELETE FROM `users` WHERE `id` = "' . $bu[$i]['id'] . '" LIMIT 1');
mysql_query('DELETE FROM `stats` WHERE `id` = "' . $bu[$i]['id'] . '" LIMIT 1');
//выкидываем предметы на землю
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> <20><><EFBFBD><EFBFBD><EFBFBD>
$spi = mysql_query(
'SELECT `id`,`item_id` FROM `items_users` WHERE `uid` = "' . $bu[$i]['id'] . '" LIMIT 500'
);
@ -88,9 +89,9 @@ class DeathTower
$chat = new Chat();
$cmsg = new ChatMessage();
/* завершаем БС */
/* <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><> */
if (isset($win['id']) && $win['lose'] == 0 && $win['nich'] == 0 && $win['id'] > 0) {
//есть победитель
//<EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
$bsep = 0;
if ($winr['level'] < 6) {
$bsep = 2500;
@ -103,7 +104,7 @@ class DeathTower
} else {
$bsep = 50000;
}
/* Выдаем приз */
/* <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD> */
$mn = (round($id['money'] / 100 * 85));
mysql_query(
'UPDATE `users` SET `money` = `money` + "' . $mn . '" WHERE `id` = "' . $winr['id'] . '" LIMIT 1'
@ -111,10 +112,10 @@ class DeathTower
mysql_query(
'UPDATE `stats` SET `exp` = `exp` + "' . $bsep . '" WHERE `id` = "' . $winr['id'] . '" LIMIT 1'
);
/* чат */
/* <EFBFBD><EFBFBD><EFBFBD> */
$cmsg->setTo($winr['login']);
$cmsg->setText(
"Поздравляем! Вы победили в турнире &quot;Башня Смерти&quot;! Получено опыта: $bsep, деньги: $mn кр."
"<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>! <20><> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> &quot;<3B><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&quot;! <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD>: $bsep, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: $mn <20><>."
);
$cmsg->setType(6);
$chat->sendMsg($cmsg);
@ -122,21 +123,23 @@ class DeathTower
$cmsg->setTo('');
$cmsg->setIsAlert(true);
$cmsg->setText(
"Завершился турнир &quot;Башня Смерти&quot;, победитель турнира: <strong>{$winr['login']}</strong>! Поздравляем!"
"<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> &quot;<3B><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>&quot;, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: <strong>{$winr['login']}</strong>! <EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>!"
);
$cmsg->setType(5);
$chat->sendMsg($cmsg);
$user->addDelo(
1, $uid,
'&quot;<span style="color: #C65F00; ">WinTournament.' . $user->info['city'] . '</span>&quot; (Башня Смерти): Получено &quot;<strong>' . $mn . '</strong> кр.&quot;',
time(), $user->info['city'], 'WinTournament.' . $user->info['city'], 0, 0
Delo::add(
1,
'WinTournament.' . $user->info['city'],
$uid,
'&quot;<span style="color: #C65F00; ">WinTournament.' . $user->info['city'] . '</span>&quot; (<28><><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>): <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> &quot;<strong>' . $mn . '</strong> <20><>.&quot;',
);
} else {
/* чат */
/* <EFBFBD><EFBFBD><EFBFBD> */
$cmsg->setIsAlert(true);
$cmsg->setType(5);
$cmsg->setText('Завершился турнир «Башня Смерти», победитель турнира: отсутствует.');
$cmsg->setText('<EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD> <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>: <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>.');
}
$sp = mysql_query(

View File

@ -0,0 +1,564 @@
<?php
namespace Location;
use Core\Config;
use Core\Db;
use Delo;
use Enum\ShopId;
use Helper\Conversion;
use Item\Data\Bonuses;
use Item\Data\Properties;
use Item\Data\Requirements;
use Item\DataModel;
use Model\Constant\ShopOtdel;
use User;
class Shop
{
public ShopOtdel $shopOtdel;
private ShopId $shopId;
private array $wares;
private int $otdel;
private int $itemId;
private $buyer;
public function __construct(ShopId $shopId, int $otdel = 1)
{
$this->shopOtdel = new ShopOtdel();
$this->otdel = $otdel;
$this->itemId = intval($_GET['itmid']);
$this->shopId = $shopId;
$this->wares = Db::getRows('select * from
items_shop
left join items_main on items_shop.item_id = items_main.id
where sid = ? and r = ? and kolvo > 0 order by pos', [$shopId->value, $otdel]);
$this->buyer = new class {
public function getId(): int
{
return User::start()->info['id'];
}
public function getCredits(): float
{
return User::start()->info['money'];
}
public function getEuroCredits(): float
{
return User::start()->info['money2'];
}
public function getVoinstvennost(): int
{
return (int)User::start()->rep['rep3'] - (int)User::start()->rep['rep3_buy'];
}
public function getNextAct()
{
return User::start()->info['nextAct']; // что ты такое?!
}
public function isAdmin(): bool
{
return User::start()->isAdmin();
}
public function hasEnough(string $parameter, int $value): bool
{
return User::start()->stats[$parameter] >= $value;
}
public function hasExactly(string $parameter, int $value): bool
{
return User::start()->stats[$parameter] === $value;
}
public function hasEnoughCredits(int $itemprice): bool
{
return $this->getCredits() >= $itemprice;
}
public function hasEnoughEuroCredits(int $itemprice): bool
{
return $this->getEuroCredits() >= $itemprice;
}
public function hasEnoughVoinstvennost(int $itemprice): bool
{
return $this->getVoinstvennost() >= $itemprice;
}
};
if ($this->buyer->isAdmin()) {
if (isset($_GET['itmup'])) {
$this->itemUp();
} elseif (isset($_GET['itmdown'])) {
$this->itemDown();
}
}
if ($_SERVER["REQUEST_METHOD"] === "GET") {
if ($_GET['itmup']) {
$this->itemUp();
}
}
}
private function itemUp(): void
{
$this->changeItemPositionByInt(-1);
}
private function changeItemPositionByInt(int $modificator): void
{
Db::sql('update items_shop set pos = pos + ? where sid = ? and r = ? and item_id = ? and kolvo > 0',
[$modificator, $this->shopId->value, $this->otdel, $this->itemId]);
}
private function itemDown(): void
{
$this->changeItemPositionByInt(1);
}
public function printWares(): void
{
foreach ($this->wares as $pl) {
$data = new DataModel($pl['item_id']);
$itemRequirements = new Requirements($data->getRequirements());
$itemBonuses = new Bonuses($data->getBonuses());
$itemProperties = new Properties($data->getProperties());
$itemData = $data->getAll();
$pl['price_1'] = $this->calculateMinimalPrice($pl['price1'], $pl['price_1'], $pl['tr_items']);
$pl['price_2'] = $this->calculateMinimalPrice($pl['price2'], $pl['price_2'], $pl['tr_items']);
if (($pl['type'] >= 18 && $pl['type'] <= 24) || $pl['type'] == 26 || $pl['type'] == 27) {
$itemBonuses->addZonb();
}
$is2 = $this->name($pl['name'], $pl['renameadd'], $pl['item_id']);
if ($pl['massa'] > 0) {
$is2 .= '(Масса: ' . round($pl['massa'], 2) . ')';
}
$is2 .= $this->icons($itemRequirements->getAlign(), $itemData['art'], $itemData['sudba']);
$is2 .= $this->price($pl['price_1'], $pl['price_2'], $pl['price_4']);
if ($pl['kolvo'] < 50) {
$is2 .= ' &nbsp; &nbsp; <small style="color: crimson;">(остаток на складе: <strong>' . $pl['kolvo'] . '</strong>)</small>';
}
$is2 .= $this->needItems($pl['tr_items']);
//долговечность
if ($pl['iznos'] > 0) {
$pl['iznosMAXi'] = $pl['iznos'];
}
if ($pl['iznosMAXi'] > 0 && $pl['iznosMAXi'] < 1000) {
$is2 .= 'Долговечность: 0/' . $pl['iznosMAXi'] . '<br>';
}
if ($itemData['battleUseZd'] > 0) {
$is2 .= 'Задержка использования: ' . Conversion::secondsToTimeout($itemData['battleUseZd']) . '<br>';
}
$is2 = rtrim($is2, '<br>');
//Срок годности предмета
if ($itemData['srok'] > 0) {
$pl['srok'] = $itemData['srok'];
}
if ($pl['srok'] > 0) {
$is2 .= '<br>Срок годности: ' . Conversion::secondsToTimeout($pl['srok']);
}
if ($pl['magic_chance'] > 0) {
$is2 .= '<br>Вероятность срабатывания: ' . min([$pl['magic_chance'], 100]) . '%';
}
//Продолжительность действия магии:
if ((int)$pl['magic_inci'] > 0) {
$magicDuration = Db::getValue('select actiontime from eff_main where id2 = ?', [(int)$pl['magic_inci']]);
if ($magicDuration > 0) {
$is2 .= '<br>Продолжительность действия: ' . Conversion::secondsToTimeout($magicDuration);
}
}
if ($itemRequirements->get()) {
$is2 .= '<br><strong>Требуется минимальное:</strong>';
$is2 .= '<ul style="margin: 0; padding: 0 30px;">';
foreach ($itemRequirements->get() as $dataName => $dataInfo) {
if ($dataName === 'align' || $dataName === 'sex') {
$value = $dataName === 'align' ? intval($dataInfo['sysvalue']) : intval($dataInfo['value']);
$is2 .= $this->buyer->hasExactly($dataName, $value) ? '<li>' : '<li style="color: crimson; list-style-type: \'× \';">';
} else {
$is2 .= $this->buyer->hasEnough($dataName, intval($dataInfo['value'])) ? '<li>' : '<li style="color: crimson; list-style-type: \'× \';">';
}
$name = empty($dataInfo['name']) ? $dataName : $dataInfo['name'];
$is2 .= $name . ': ' . $dataInfo['value'];
//$is2 .= $dataName . ': ' . $dataInfo;
$is2 .= '</li>';
}
$is2 .= '</ul>';
}
if ($itemBonuses->get()) {
$is2 .= '<br><strong>Действует на:</strong>';
$is2 .= '<ul style="margin: 0; padding: 0 30px;">';
foreach ($itemBonuses->get() as $name => $value) {
if ($name === 'Броня') {
$is2 .= '<li>' . $name . ': ' . $value . '</li>';
continue;
}
$color = $value > 0 ? 'darkgreen' : 'darkred';
$is2 .= '<li style="color: ' . $color . '">' . $name . ': ' . ($value > 0 ? '+' . $value : $value) . '</li>';
}
$is2 .= '</ul>';
}
$is2 .= '<br><strong>Свойства предмета:</strong>';
foreach ($itemProperties->get() as $name => $value) {
$is2 .= '<br>' . $name . ': ' . $value;
}
if ($pl['2too'] === 1) {
$is2 .= '<br>Второе оружие';
}
if ($pl['2h'] === 1) {
$is2 .= '<br>Двуручное оружие';
}
if (!empty($itemData['imposed'])) {
if (empty($itemData['imposed_name'])) {
$itemData['imposed_name'] = 'Неизвестное зачарование';
}
$itemData['imposed_name'] = str_replace('Чары ', '', $itemData['imposed_name']);
$is2 .= '<br><span style="color: maroon;">Зачарование:</span> ' . $itemData['imposed_name'];
}
if (!empty($itemData['free_stats']) && $itemData['free_stats'] > 0) {
$is2 .= '<br> +' . $itemData['free_stats'] . ' дополнительных характеристик';
}
//Встроенная магия
if (!empty($pl['magic_inci']) || !empty($pl['magic_inc'])) {
if (empty($pl['magic_inc'])) {
$pl['magic_inc'] = $pl['magic_inci'];
}
$magic = Db::getRow('select id2, mname, minfo, img from eff_main where type1 = 12345 and id2 = ?', [$pl['magic_inc']]);
if ($magic['id2']) {
$is2 .= '<br><div>Встроено заклятие <img alt="' . $magic['mname'] . '" src="' . Config::img() . '/i/eff/' . $magic['img'] . '"> ' . $magic['minfo'] . '</div>';
}
}
$is2 .= $this->getcomplect($itemData['complect']);
if ($pl['max_text'] - $pl['use_text'] > 0) {
$is2 .= '<div>Количество символов: ' . ($pl['max_text'] - $pl['use_text']) . '</div>';
}
$is2 .= '<small>';
if (!empty($itemData['gravi'])) {
$is2 .= '<br><span style="font-size: x-large; font-family: consolas, monospace; background-color: darkseagreen; color: ghostwhite; padding: 0 5px;">' . $itemData['gravi'] . '</span>';
}
if (!empty($itemData['info'])) {
$pl['info'] .= '<br>' . $itemData['info'];
}
if (!empty($pl['info'])) {
$is2 .= '<div style="border: 2px dashed whitesmoke; background-color: silver;">' . $pl['info'] . '</div>';
}
if (isset($itemData['noremont'])) {
$is2 .= '<div style="color:brown;">Предмет не подлежит ремонту</div>';
}
if (isset($itemData['nosale'])) {
$is2 .= '<div style="color:brown;">Предмет нельзя продать</div>';
}
if (isset($itemData['nomodif'])) {
$is2 .= '<div style="color:brown;">Предмет нельзя улучшать</div>';
}
if (isset($itemData['nodelete'])) {
$is2 .= '<div style="color:brown;">Предмет нельзя выбросить</div>';
}
if (isset($itemData['sleep_moroz']) && $itemData['sleep_moroz'] > 0) {
$is2 .= '<div style="color:brown;">Предмет не портится во время сна</div>';
}
$is2 .= '</small>';
$is1 = $this->imageAndControls($pl['id'], $pl['type'], $pl['img'], $pl['name'], $pl['price_1'], $pl['price_2']);
echo <<<HTML
<div style="padding: 7px; text-align: center; vertical-align: middle;" class="left">$is1</div>
<div style="padding: 7px;" class="right">{$this->adminOptions($pl['id'], $pl['pos'])} $is2</div>
HTML;
}
if (empty($this->wares)) {
echo '<div style="grid-column: 1 / 3; padding: 7px; margin: auto">Прилавок магазина пуст.</div>';
}
}
private function calculateMinimalPrice($basePrice, $shopPrice, $needItems)
{
if ($shopPrice < 0.01 && !$needItems) {
$shopPrice = $basePrice;
}
if ($shopPrice < 0) {
$shopPrice = 0;
}
return $shopPrice;
}
private function name(string $name, ?string $defaultName, int $itemid): string
{
$styleSuffix = '';
if ($this->shopId === ShopId::SHOP_2) {
$styleSuffix = 'WL';
}
if (!empty($defaultName)) {
$name .= ' (Предмет: ' . $defaultName . ')';
}
if (!empty($styleSuffix)) {
$name = '<span class="icos_' . $styleSuffix . '">' . $name . ' <small>&nbsp;' . $styleSuffix . '&nbsp;</small></span>';
}
return '<a id="sit_' . $itemid . '" href="/item/' . $itemid . '" target="_blank">' . $name . '</a> &nbsp; &nbsp;';
}
private function icons(?int $align, ?int $artefact, ?int $destiny): string
{
$str = '&nbsp;&nbsp;';
if (!empty($align)) {
$str .= '<img src="' . Config::img() . '/i/align/align' . $align . '.gif" alt="Требуется склонность">';
}
if (!empty($artefact)) {
$str .= '<img src="' . Config::img() . '/i/artefact.gif" alt="Артефакт">';
}
$str .= $this->destiny($destiny);
return $str;
}
private function destiny($d): string
{
if (empty($d)) {
return '';
}
if ($d == 0) {
$str = 'первым, кто наденет его';
} elseif ($d == 1) {
$str = 'первым, кто возьмёт его';
} else {
$str = $d;
}
return '<img
title="Этот предмет будет связан общей судьбой с ' . $str . '. Никто другой не сможет его использовать."
src="' . Config::img() . '/i/destiny0.gif"
alt="Общая судьба">';
}
private function price(int $credits, int $eurocredits, int $voinstvennost): string
{
$result = 'Цена: ';
if ($this->shopId === ShopId::SHOP_2) {
$result .= $this->printColoredValue($this->buyer->getVoinstvennost() >= $voinstvennost, $voinstvennost);
$result .= ' Воинственности ';
} elseif ($this->shopId === ShopId::BEREZKA || $this->shopId === ShopId::ARTEFACTS) {
$result .= '<span style="color: cornflowerblue;">';
$result .= $this->printColoredValue($this->buyer->getEuroCredits() >= $eurocredits, $eurocredits);
$result .= ' екр.</span> ';
} else {
$result .= $this->printColoredValue($this->buyer->getCredits() >= $credits, $credits);
$result .= ' кр.';
}
return '<br><strong>' . $result . '</strong> ';
}
/**
* Если в первом параметре передаётся false, строка во втором параметре красится в красный цвет.
* @param bool $check
* @param $value
* @return string
*/
private function printColoredValue(bool $check, $value): string
{
$color = $check ? 'inherit' : 'red';
return sprintf('<span style="color:%s;">%s</span>', $color, $value);
}
private function needItems(string $items): string
{
if (!$items || Config::get('noitembuy')) {
return '';
}
$result = '';
$trn = true;
$itemsArray = explode(',', $items);
foreach ($itemsArray as $keyvalue) {
[$key, $value] = explode('=', $keyvalue);
if (!empty($key) && !empty($value)) {
$neededItemName = Db::getValue('select name from items_main where id = ?', [$key]);
if ($neededItemName) {
$neededItemsInInventoryCount = Db::getValue(
'select count(*) from items_users where item_id = ? and inShop = 0 and inOdet = 0 and `delete` in (0,1000) and uid = ?',
[$key, $this->buyer->getId()]);
if ($neededItemsInInventoryCount < (int)$value) {
$trn = false;
}
$result .= '[<strong>' . $neededItemName . '</strong>] x' . $value . ', ';
}
}
}
return $this->printColoredValue($trn, '<br>Требует предмет: ' . rtrim($result, ', ') . ' ') . '<br>';
}
private function getcomplect(?int $complect): string
{
if (!isset($complect)) {
return '';
}
$cname = 'Неизвестный Комплект';
$text = '';
$stmt = Db::getRows('select * from complects where com = ? order by x', [$complect]);
foreach ($stmt as $row) {
$cname = $row['name'];
$text .= '&nbsp;&nbsp;&bull; <span style="color: green;">' . $row['x'] . ' предметов</span>:<br>';
//действие комплекта
$complectBonuses = new Bonuses(Conversion::dataStringToArray($row['data']));
foreach ($complectBonuses->get() as $name => $value) {
$text .= '&nbsp;&nbsp;&nbsp;&nbsp;<span style="color: darkgreen;">';
if ($name === 'Броня') {
$text .= $name . ': ' . $value;
} else {
$text .= $name . ': ' . ($value > 0 ? '+' . $value : $value);
}
$text .= '</span><br>';
}
}
return "<br>Часть комплекта: <strong>$cname</strong><br><small>$text</small>";
}
private function imageAndControls(int $id, int $type, string $image, string $name, float $credits, float $eurocredits): string
{
if ($type == 71) {
$result = '<img src="' . Config::img() . '/i/items/' . $image . '" width="80" alt="' . $name . '"><br>';
} else {
$result = '<img src="' . Config::img() . '/i/items/' . $image . '" alt="' . $name . '"><br>';
}
if ($this->shopId == ShopId::SHOP_2) {
$js = <<<JS
<button onClick="top.buyShopNow($id,'?otdel=$this->otdel&buyVn=$id&sd4={$this->buyer->getNextAct()}','$name')">Купить</button>
JS;
} elseif (($this->shopId == ShopId::BEREZKA || $this->shopId == ShopId::ARTEFACTS) && $this->buyer->hasEnoughEuroCredits($eurocredits)) {
$js = <<<JS
<button onClick="top.buyShopNow($id,'?otdel=$this->otdel&buyEkr=$id&sd4={$this->buyer->getNextAct()}','$name',$eurocredits,'екр.')">Купить</button>
JS;
} elseif ($this->buyer->hasEnoughCredits($credits)) {
$js = <<<JS
<button onClick="top.buyShopNow($id,'?otdel=$this->otdel&buy=$id&sd4={$this->buyer->getNextAct()}','$name',$credits,'кр.')">Купить</button>
JS;
} else {
return '';
}
return $result . $js;
}
private function adminOptions(int $itemId, int $itemPosition): string
{
if (!$this->buyer->isAdmin()) {
return '';
}
$time = microtime();
return <<<HTML
<div style="float:right">
<a href="?otdel=$this->otdel&itmid=$itemId&itmup=1#itmdown$itemId"></a>
&nbsp; $itemPosition &nbsp;
<a href="?otdel=$this->otdel&itmid=$itemId&itmdown=1#itmdown$itemId"></a>
<button onclick="window.open('/item_edit_data.php?edit_item_data=$itemId','winEdi1','width=850,height=400,top=400,left=500,resizable=no,scrollbars=yes,status=no')">
Редактировать предмет
</button>
<button onclick="location.href='/main.php?timeWorld=$time&otdel=$this->otdel#itmShop$itemId'">Обновить</button>
</div><br>
HTML;
}
public function buy(int $itemid): string
{
$sql = 'select sid, items_shop.price_1, name from items_shop left join items_main on item_id = id where item_id = ? and sid = ?';
$item = Db::getRow($sql, [$itemid, $this->shopId->value]);
if (!$this->buyer->hasEnoughCredits($item['price_1'])) {
return 'Покупка не удалась.';
}
$newId = User\ItemsModel::addItem($itemid, $this->buyer->getId());
Db::sql('update items_users set `1price` = ? where id = ?', [$item['price_1'], $newId]);
User::start()->info['money'] -= $item['price_1'];
User::start()->addKr(-$item['price_1']);
Delo::add(1, "shopid:{$item['sid']}", $this->buyer->getId(), "Покупка «{$item['name']}» по цене {$item['price_1']}.", $item['price_1']);
return "Вы купили «{$item['name']}» по цене {$item['price_1']}.";
}
public function buyEkr(int $itemid): string
{
$sql = 'select sid, items_shop.price_2, name from items_shop left join items_main on item_id = id where item_id = ? and sid = ?';
$item = Db::getRow($sql, [$itemid, $this->shopId->value]);
if (!$this->buyer->hasEnoughEuroCredits($item['price_2'])) {
return 'Покупка не удалась.';
}
$newId = User\ItemsModel::addItem($itemid, $this->buyer->getId());
Db::sql('update items_users set `2price` = ? where id = ?', [$item['price_2'], $newId]);
User::start()->info['money2'] -= $item['price_2'];
User::start()->addEkr(-$item['price_2']);
Delo::add(1, "shopid:{$item['sid']}", $this->buyer->getId(), "Покупка «{$item['name']}» по цене {$item['price_2']}.", $item['price_2']);
return "Вы купили «{$item['name']}» по цене {$item['price_2']}.";
}
public function buyVn(int $itemid): string
{
$sql = 'select sid, items_shop.price_4, name from items_shop left join items_main on item_id = id where item_id = ? and sid = ?';
$item = Db::getRow($sql, [$itemid, $this->shopId->value]);
if (!$this->buyer->hasEnoughVoinstvennost($item['price_4'])) {
return 'Покупка не удалась.';
}
$newId = User\ItemsModel::addItem($itemid, $this->buyer->getId());
Db::sql('update items_users set `4price` = ? where id = ?', [$item['price_4'], $newId]);
User::start()->rep['rep3'] -= $item['price_4'];
User::start()->addVoinstvennost(-$item['price_4']);
Delo::add(1, "shopid:{$item['sid']}", $this->buyer->getId(), "Покупка «{$item['name']}» по цене {$item['price_4']}.", $item['price_4']);
return "Вы купили «{$item['name']}» по цене {$item['price_4']}.";
}
public function getUsedOtdels(): array
{
$result = [];
foreach (Db::getColumn('select r from items_shop where sid = ? group by r', [$this->shopId->value]) as $v) {
$result[$v] = $this->shopOtdel->getName($v);
}
return $result;
}
public function getUserWallet(): string
{
$result = '';
if ($this->shopId === ShopId::MAIN) {
$result = $this->buyer->getCredits() . ' кр.';
} elseif (in_array($this->shopId, [ShopId::BEREZKA, ShopId::ARTEFACTS])) {
$result = $this->buyer->getEuroCredits() . ' екр.';
} elseif ($this->shopId === ShopId::SHOP_2) {
$result = $this->buyer->getVoinstvennost() . ' воинственности.';
}
return $result;
}
}

View File

@ -0,0 +1,191 @@
<?php
use Core\Config;
use Core\Db;
class LocationResponse
{
private const MSG = [
'your-position' => 'Ваше местоположение',
'move-bk' => 'Проход через <b>Бойцовский клуб</b>',
'move-zalu4' => 'Проход через <b>Зал паладинов</b>',
'move-map_halls' => 'Проход через <b>Залы</b>',
'move-to-sek4' => 'Проход через <b>Рыцарский</b> или <b>Торговый</b> зал',
'move-sek5' => 'Проход через <b>Торговый зал</b>',
'move-sek6' => 'Проход через <b>Рыцарский зал</b>',
];
private static function thisInfRm($id): array
{
$rm = Db::getRow('select id, name from room where code = ?', [$id]);
if (isset($rm['id'])) {
$rown = Db::getValue('select count(*) from users where online > unix_timestamp() - 120 and room = ?', [$rm['id']]);
return [$id, $rm['name'], $rown];
}
return ['false', 'Здание было разрушено', 0];
}
public static function init(
int $tmGo,
int $tmGol,
$roomFile,
$roomName,
): string {
$r = match ($roomFile) {
'bk' => [
'status' => 'success',
'location' => [
'bg' => 'navig',
'left' => '241',
'top' => '128',
],
'goto' => [
['id' => 'map_bk', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_klub1', 'params' => self::thisInfRm('1.180.0.15')],
['id' => 'map_klub2', 'params' => self::thisInfRm('1.180.0.225')],
['id' => 'map_klub3', 'params' => self::thisInfRm('1.180.0.2')],
['id' => 'map_klub4', 'params' => self::thisInfRm('1.180.0.4')],
['id' => 'map_klub5', 'params' => self::thisInfRm('1.180.0.5')],
['id' => 'map_klub6', 'params' => self::thisInfRm('1.180.0.16')],
['id' => 'map_klub7', 'params' => self::thisInfRm('1.180.0.9')],
],
'buttons' => [
['Возврат', 'main.php?homeworld=true'],
['Карта клуба', 'main.php?clubmap=true'],
['Форум', "window.open('" . Config::get('forum') . "', 'forum', 'location=yes,menubar=yes,status=yes,resizable=yes,toolbar=yes,scrollbars=yes,scrollbars=yes')"],
['Подсказка', "window.open('/encicl/help/top1.html', 'help', 'height=300,width=500,location=no,menubar=no,status=no,toolbar=no,scrollbars=yes')"],
],
],
'zv1' => [
'status' => 'success',
'location' => [
'bg' => 'navig',
'left' => '154',
'top' => '148',
],
'goto' => [
['id' => 'map_bk', 'params' => self::thisInfRm('1.180.0.3')],
['id' => 'map_klub1', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub2', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub3', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub4', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_klub5', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub6', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub7', 'params' => [false, self::MSG['move-bk']]],
],
],
'zv2' => [
'status' => 'success',
'location' => [
'bg' => 'navig',
'left' => '395',
'top' => '142',
],
'goto' => [
['id' => 'map_bk', 'params' => self::thisInfRm('1.180.0.3')],
['id' => 'map_klub1', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub2', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub3', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_klub4', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub5', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub6', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub7', 'params' => [false, self::MSG['move-bk']]],
],
],
'zv3' => [
'status' => 'success',
'location' => [
'bg' => 'navig',
'left' => '337',
'top' => '79',
],
'goto' => [
['id' => 'map_bk', 'params' => self::thisInfRm('1.180.0.3')],
['id' => 'map_klub1', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub2', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub3', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub4', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub5', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_klub6', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub7', 'params' => [false, self::MSG['move-bk']]],
],
],
'zv4' => [
'status' => 'success',
'location' => [
'bg' => 'navig',
'left' => '139',
'top' => '79',
],
'goto' => [
['id' => 'map_bk', 'params' => self::thisInfRm('1.180.0.3')],
['id' => 'map_klub1', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub2', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub3', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub4', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub5', 'params' => [false, self::MSG['move-bk']]],
['id' => 'map_klub6', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_klub7', 'params' => [false, self::MSG['move-bk']]],
],
],
'zalu' => [
'status' => 'success',
'location' => [
'bg' => 'navig1',
'left' => '337',
'top' => '117',
],
'goto' => [
['id' => 'map_halls', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_zalu3', 'params' => [false, self::MSG['move-zalu4']]],
['id' => 'map_zalu4', 'params' => self::thisInfRm('1.180.0.16')],
['id' => 'map_zalu6', 'params' => [false, self::MSG['move-zalu4']]],
['id' => 'map_zalu7', 'params' => self::thisInfRm('1.180.0.3')],
],
],
'zalu_pal' => [
'status' => 'success',
'location' => [
'bg' => 'navig1',
'left' => '163',
'top' => '28',
],
'goto' => [
['id' => 'map_halls', 'params' => self::thisInfRm('1.180.0.15')],
['id' => 'map_zalu3', 'params' => self::thisInfRm('1.180.0.xx')],
['id' => 'map_zalu4', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_zalu6', 'params' => self::thisInfRm('1.180.0.0')],
['id' => 'map_zalu7', 'params' => [false, self::MSG['move-map_halls']]],
],
],
'bk2' => [
'status' => 'success',
'location' => [
'bg' => 'navig3',
'left' => '162',
'top' => '125',
],
'goto' => [
['id' => 'map_2stair', 'params' => [false, self::MSG['your-position']]],
['id' => 'map_sec1', 'params' => self::thisInfRm('1.180.0.3')],
['id' => 'map_sec2', 'params' => self::thisInfRm('1.180.0.xx')],
['id' => 'map_sec3', 'params' => [false, self::MSG['move-sek5']]],
['id' => 'map_sec4', 'params' => [false, self::MSG['move-to-sek4']]],
['id' => 'map_sec5', 'params' => self::thisInfRm('1.180.0.221')],
['id' => 'map_sec6', 'params' => self::thisInfRm('1.180.0.224')],
['id' => 'map_sec7', 'params' => [false, self::MSG['move-sek6']]],
],
],
default => [],
};
if (!empty($r)) {
$r['location']['name'] = $roomName;
$r['location']['tgo'] = $tmGo * 10;
$r['location']['tgo1'] = $tmGol * 10;
}
$r = json_encode($r);
return $r ?: '';
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,24 @@
<?php
if (!defined('GAME')) {
die();
}
if (in_array($itm['magic_inci'], [396, 397, 398])) {
$eff = mysql_fetch_array(mysql_query('SELECT `id` FROM `eff_users` WHERE `uid` = "' . $u->info['id'] . '" AND `id_eff` = '. $itm['magic_inci'] .' LIMIT 1'));
if (isset($eff['id'])) {
mysql_query('UPDATE `eff_users` SET `delete` = "' . time() . '" WHERE `uid` = "' . $u->info['id'] . '" AND `delete` = "0" AND `id_eff` = "' . $itm['magic_inc'] . '"');
}
$this->add_eff($u->info['id'], $itm['magic_inc']);
Delo::add(
1,
'System.inventory',
$u->info['id'],
'&quot;<span style="color: maroon; ">System.inventory</span>&quot;: Персонаж использовал эликсир &quot;' . $itm['name'] . '&quot; (' . $u->info['id'] . ') [itm:' . $itm['id'] . '].',
);
$itm['iznosNOW']++;
mysql_query('UPDATE `items_users` SET `iznosNOW` = "' . $itm['iznosNOW'] . '" WHERE `id` = ' . $itm['id']);
$u->error = 'Вы успешно использовали эликсир &quot;' . $itm['name'] . '&quot;';
}

View File

@ -0,0 +1,331 @@
<?php
namespace Magic;
use Chat;
use ChatMessage;
use Core\Config;
use Core\Db;
use Helper\Math;
use Magic;
use User;
class Attack
{
private Magic $magic;
private int $pigAnimalBonus = 0;
public function __construct(Magic $magic)
{
$this->magic = $magic;
}
public function atackUser($uid1, $uid2, $tm, $btl, $addExp = 0, $type = 0)
{
global $u;
$attacker = User::getInfo($uid1);
$target = User::getInfo($uid2);
$battleTest = Db::getRow('select * from battle where id = ? and team_win = -1');
$good = 0;
$error = '';
if (
self::isMonster($target) &&
(
$target['level'] == 9 && $attacker['level'] > 9 ||
$target['level'] == 10 && ($attacker['level'] < 10 || $attacker['level'] > 11)
)
) {
$error = 'Нельзя нападать на монстра этого уровня!';
} elseif (self::isMonster($target) && User\Effects::hasAttackTimeLimit($attacker['id'])) {
$error = 'Нельзя нападать на монстра чаще одного раза в 3 часа!';
} elseif (User\Effects::isImmuneToAttack($target['id'])) {
$error = 'Персонаж имеет защиту от нападения!';
} elseif ($target['level'] == 8 && !self::isMonster($target) && self::canAttack8Level(
$attacker['id'], $target['id']
)) {
$error = 'На 8-е уровни нападать нельзя.';
} elseif ($attacker['level'] != $target['level'] && !self::isMonster($target)) {
$error = 'Нападать можно на персонажей только своего уровня!!!';
} elseif (isset($battleTest['id']) && $battleTest['noatack'] > 0) {
$error = 'Поединок защищен магией! Вы не можете вмешаться!';
} elseif ($target['level'] < 8) {
$error = 'Новички находятся под защитой Мироздателя...';
} elseif ($attacker['level'] < 8) {
$error = 'Тренируйтесь вам пока еще рано...';
} elseif ($target['admin'] == 1 && $attacker['admin'] == 0) {
$error = 'Уважайте хранителей...';
} elseif ($this->magic->testTravma($uid2, 3)) {
$error = 'Противник тяжело травмирован, нельзя напасть!';
} elseif ($this->magic->testTravma($uid1, 2)) {
$error = 'Вы травмированы, нельзя напасть!';
} elseif ($target['clan'] != 0 && ($target['clan'] == $attacker['clan']) && $attacker['admin'] == 0) {
$error = 'Чтите честь ваших сокланов.';
} elseif ($btl != 0 && $battleTest['smert'] == 1 && $type != 222) {
$error = 'Вы не можете вмешаться в этот кровавый поединок!';
} elseif ($btl == 0) {
$s01 = $u->getStats($uid1, 0);
if ($s01['hpNow'] < floor($s01['hpAll'] / 100 * 33)) {
$error = 'Нельзя напасть, у противника не восстановилось здоровье';
} else {
$addExp += $target['bbexp'];
//effect ненападения
if (self::isMonster($target)) {
User\Effects::giveAttackImmunity($attacker['id']);
}
//тут клан вар
//************
//нападаем на персонажа
//===Удаление защиты от нападения в результате нападения пользователем
User\Effects::removeByIds($attacker['id'], 479, 480, 481);
//=======
if ($type == 222) {
$battleId = self::battleInit($attacker, $target, 99, $addExp, true, 1);
} elseif (self::haveClanWar($attacker['clan'], $target['clan'])) {
$battleId = self::battleInit($attacker, $target, 250, $addExp, true);
} else {
$battleId = self::battleInit($attacker, $target, $type, $addExp);
}
if ($battleId > 0) {
//
$s01 = self::updateHpAndMp($s01);
$s02 = $u->getStats($uid2, 0);
$s02 = self::updateHpAndMp($s02);
Db::sql('update users set battle = ? where id in (?,?)', [$uid1, $uid2]);
$sql = 'update stats set lider = ?, tactic7 = ?, hpNow = ?, mpNow = ?, team = ? where id = ?';
Db::sql($sql, [
$battleId,
$s01['tactic7'],
$s01['hpNow'],
$s01['mpNow'],
1,
$uid1,
]);
Db::sql($sql, [
$battleId,
$s02['tactic7'],
$s02['hpNow'],
$s02['mpNow'],
2,
$uid2,
]);
unset($sql);
$good = $battleId;
}
}
} elseif (isset($battleTest['id']) && $battleTest['type'] == 500 && $target['team'] == 1) {
$error = 'Нельзя сражаться на стороне монстров!';
} elseif (isset($battleTest['id']) && $battleTest['type'] == 250 && $attacker['clan'] != $battleTest['clan1'] && $attacker['clan'] != $battleTest['clan2']) {
$error = 'Нельзя попасть в клановые бои - если вы неявляетесь представителем данных кланов!!!';
} elseif (isset($battleTest['id']) && $battleTest['invis'] > 0) {
$error = 'Нельзя вмешиваться в невидимый бой!';
} elseif ($battleTest['noatack'] > 0) {
$error = 'В этот поединок нельзя вмешиваться!';
} else {
//вмешиваемся в бой
//effect ненападения
if (self::isMonster($target)) {
User\Effects::giveAttackImmunity($attacker['id']);
}
Db::sql('update users set battle = ? where id = ?', [$btl, $uid1]);
$uid1st = $u->getStats($uid1);
$uid1u = User::getInfo($uid1);
if ($uid1u['level'] <= 7) {
$uid1st['tactic7'] = floor((10 + $uid1st['s7']) / $uid1st['hpAll'] * $uid1st['hpNow']);
} elseif ($uid1u['level'] == 8) {
$uid1st['tactic7'] = floor((20 + $uid1st['s7']) / $uid1st['hpAll'] * $uid1st['hpNow']);
} elseif ($uid1u['level'] == 9) {
$uid1st['tactic7'] = floor((30 + $uid1st['s7']) / $uid1st['hpAll'] * $uid1st['hpNow']);
} elseif ($uid1u['level'] >= 10) {
$uid1st['tactic7'] = floor((40 + $uid1st['s7']) / $uid1st['hpAll'] * $uid1st['hpNow']);
} else {
$uid1st['tactic7'] = floor((10 + $uid1st['s7']) / $uid1st['hpAll'] * $uid1st['hpNow']);
}
//Духовность, спасение
if ($uid1st['s7'] > 49) {
User\Effects::addSpasenie($uid1st['id']);
}
$btxt = '';
if ($uid1u['align'] > 0) {
$btxt = $btxt . '<img src=' . Config::img() . '/i/align/align' . $uid1u['align'] . '.gif >';
}
if ($uid1u['align2'] > 0) {
$btxt = $btxt . '<img src=' . Config::img() . '/i/align/align' . $uid1u['align2'] . '.gif >';
}
if ($uid1u['clan'] > 0) {
$btxt = $btxt . '<img src=' . Config::img() . '/i/clan/' . $uid1u['clan'] . '.gif >';
}
$btxt = $btxt . '<b>{u1}</b>[' . $uid1u['level'] . ']<a href=info/' . $uid1u['id'] . ' target=_blank ><img src=' . Config::img() . '/i/inf_capitalcity.gif alt=""></a>';
if ($uid1u['sex'] == 1) {
$btxt = $btxt . ' вмешалась в поединок.';
} else {
$btxt = $btxt . ' вмешался в поединок.';
}
$lastHOD = Db::getRow('select id, id_hod, type from battle_logs where battle = ? order by id_hod desc limit 1');
if (isset($lastHOD['id'])) {
$idHod = $lastHOD['id_hod'];
if ($lastHOD['type'] != 6) {
$idHod++;
}
Db::sql('insert into battle_logs (time, battle, id_hod, text, vars, zona1, zonb1, zona2, zonb2, type) values (unix_timestamp(),?,?,?,?,?,?,?,?,6)', [
$btl,
$idHod,
"{tm1} $btxt",
"login1={$uid1st['login']}||t1={$uid1st['team']}||login2={$uid1st['login']}||t2={$uid1st['team']}||time=" . time(),
"",
"",
"",
"",
]);
}
// Бафф Зверя animal_bonus ---------------------------------
$this->setAnimalBonus($attacker);
User::start()->info['hpNow'] += $this->pigAnimalBonus;
// Бафф Зверя animal_bonus ---------------------------------
$ltm = [1 => 2, 2 => 1];
Db::sql('update stats set hpNow = ?, hpAll = ?, team = ?, tactic7 = ? where id = ?', [$uid1st['hpNow'], $uid1st['mpNow'], $ltm[$tm], (int)$uid1st['tactic7'], $uid1]);
$good = $btl;
unset($uid1st);
}
$u->error = $error;
return $good;
}
private static function isMonster(array $target): bool
{
return $target['no_ip'] === 'trupojor';
}
private static function canAttack8Level($attacker, $target): bool
{
$aSum = User\ItemsModel::getDressedEkrTotalPrice($attacker);
$tRange = Math::get20PercentRange(User\ItemsModel::getDressedEkrTotalPrice($target));
return $aSum >= $tRange['min'] && $aSum <= $tRange['max'];
}
private static function battleInit(array $attacker, array $defender, int $type, float $addExp, bool $isClanWar = false, $smert = 0): int
{
$fighters = "{$attacker['login']},{$defender['login']}";
$clan1 = 0;
$clan2 = 0;
if ($isClanWar) {
$clan1 = $attacker['clan'];
$clan2 = $defender['clan'];
}
$sql = 'insert into battle (city, time_start, players, timeout, type, travmChance, typeBattle, addExp, clan1, clan2, smert) values (?,unix_timestamp(),?,60 * ?,?,50,9,?,?,?,?)';
$args = ['capitalcity', $fighters, mt_rand(1, 3), $type, $addExp, $clan1, $clan2, $smert];
Db::sql($sql, $args);
return (int)Db::lastInsertId();
}
private static function haveClanWar(int $clan1, int $clan2): bool
{
$listStr = "$clan1, $clan2";
return Db::getValue('select count(*) from clan_wars where clan1 in (?) and clan2 in (?) and clan1 != clan2', [$listStr, $listStr]) > 0;
}
/**
* Обновляем НР и МР игрокам.
* @param array $userStats
* @return array
*/
private static function updateHpAndMp(array $userStats): array
{
if ($userStats['level'] <= 7) {
$userStats['tactic7'] = floor(10 / $userStats['hpAll'] * $userStats['hpNow']);
} elseif ($userStats['level'] == 8) {
$userStats['tactic7'] = floor(20 / $userStats['hpAll'] * $userStats['hpNow']);
} elseif ($userStats['level'] == 9) {
$userStats['tactic7'] = floor(30 / $userStats['hpAll'] * $userStats['hpNow']);
} elseif ($userStats['level'] >= 10) {
$userStats['tactic7'] = floor(40 / $userStats['hpAll'] * $userStats['hpNow']);
}
return $userStats;
}
private function setAnimalBonus(array $owner)
{
if ($owner['animal'] < 1) {
return;
}
$animal = Db::getRow('select * from users_animal where uid = ? and id = ? and pet_in_cage = 0', [$owner['id'], $owner['animal']]);
if (!$animal) {
return;
}
if ($animal['eda'] < 1) {
$cmsg = new ChatMessage();
$cmsg->setRoom($owner['room']);
$cmsg->setTo($owner['login']);
$cmsg->setText('<strong>' . $animal['name'] . '</strong> нуждается в еде...');
$cmsg->setType(6);
(new Chat())->sendMsg($cmsg);
return;
}
$animalBonus = Db::getValue('select bonus from levels_animal where type = ? and level = ?', [$animal['type'], $animal['level']]);
$statusName = [
1 => ['cat', 'Кошачья Ловкость'],
2 => ['owl', 'Интуиция Совы'],
3 => ['wisp', 'Сила Стихий'],
4 => ['demon', 'Демоническая Сила'],
5 => ['dog', 'Друг'],
6 => ['pig', 'Полная Броня'],
7 => ['dragon', 'Инферно'],
];
User\Effects::removeByOverType($owner['id'], 100);
User\Effects::addCustom([
'v2' => 201,
'img2' => "summon_pet_{$statusName[$animal['type']][0]}.gif",
'id_eff' => 22,
'uid' => $owner['id'],
'name' => "{$statusName[$animal['type']][1]}[{$animal['level']}]",
'data' => $animalBonus,
'overType' => 100,
'timeUse' => 77,
'v1' => 'priem',
'user_use' => $owner['id'],
]);
if ($animal['type'] == 6) {
if ($animal['level'] == 1 || $animal['level'] == 2 || $animal['level'] == 3) {
$this->pigAnimalBonus = 50;
} elseif ($animal['level'] == 4) {
$this->pigAnimalBonus = 75;
} elseif ($animal['level'] == 5 || $animal['level'] == 6) {
$this->pigAnimalBonus = 125;
} elseif ($animal['level'] == 7 || $animal['level'] == 8) {
$this->pigAnimalBonus = 150;
} elseif ($animal['level'] == 9) {
$this->pigAnimalBonus = 200;
} elseif ($animal['level'] == 10) {
$this->pigAnimalBonus = 300;
}
Db::sql('update stats set hpNow = hpNow + ? where id = ?', [$this->pigAnimalBonus, $owner['id']]);
}
}
}

View File

@ -0,0 +1,44 @@
<?php
namespace Magic\Elemental;
use Battle;
use DTO\BattleSpell;
use Helper\Math;
class Fire
{
private static string $magicElement = 'fire';
private Battle $btl;
public function __construct(Battle $btl)
{
$this->btl = $btl;
}
/** Вспышка. Приёмы: 34(8), 67(9), 68 (10), 69(11)
* @param int $level
* @param int $fireTargetMultiplier
* @return BattleSpell
*/
public function flash(int $level, int $fireTargetMultiplier = 0): BattleSpell
{
$baseDamage = [
8 => [40, 40],
9 => [45, 45],
10 => [50, 50],
11 => [60, 60],
];
if (!is_numeric($fireTargetMultiplier)) {
$fireTargetMultiplier = 0;
}
$rawDamage = mt_rand($baseDamage[$level][0], $baseDamage[$level][1]);
$rawDamage = Math::addPercent($rawDamage, $fireTargetMultiplier);
$spell = new BattleSpell(self::$magicElement);
$spell->name = "Вспышка [$level]";
$spell->damage = $rawDamage;
return $spell;
}
}

View File

@ -0,0 +1,33 @@
<?php
if (!defined('GAME')) {
die();
}
if ($itm['magic_inci'] != 'addmoney') {
return;
}
if ($itm['2price'] > 0) {
$u->addEkr($itm['2price']);
} elseif ($itm['1price'] > 0) {
$u->addKr($itm['1price']);
} elseif ($itm['price2'] > 0) {
$u->addEkr($itm['price2']);
} elseif ($itm['price1'] > 0) {
$u->addKr($itm['price1']);
}
//
if ($itm['2price'] > 0) {
$u->error = 'Вы успешно обналичили чек на ' . $itm['2price'] . ' екр.';
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
} elseif ($itm['1price'] > 0) {
$u->error = 'Вы успешно обналичили чек на ' . $itm['1price'] . ' кр.';
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
} elseif ($itm['price2'] > 0) {
$u->error = 'Вы успешно обналичили чек на ' . $itm['price2'] . ' екр.';
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
} elseif ($itm['price1'] > 0) {
$u->error = 'Вы успешно обналичили чек на ' . $itm['price1'] . ' кр.';
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
} else {
$u->error = 'Баговый чек! Напишите Администрации!';
}

View File

@ -0,0 +1,7 @@
<?php
if (!defined('GAME')) {
die();
}
//добавляем снежок в инвентарь
ItemsModel::addItem(1000, $this->info['id']);

View File

@ -0,0 +1,50 @@
<?php
if (!defined('GAME')) {
die();
}
if ($itm['magic_inci'] != 'antipropuskpsh') {
return;
}
$test = mysql_fetch_array(mysql_query('SELECT `id`,`time` FROM `actions` WHERE `uid` = "' . $usr['id'] . '" AND `vars` = "psh0" AND `time` > "' . time() . '" LIMIT 1'));
if (!isset($usr['id']) || $usr['room'] != $u->info['room']) {
$u->error = 'Неудалось найти персонажа &quot;' . htmlspecialchars($_GET['login']) . '&quot; или он в другой комнате.';
} elseif ($usr['admin'] > 0 || ($usr['align'] > 3 && $usr['align'] < 4) || ($usr['align'] > 1 && $usr['align'] < 2)) {
$u->error = 'Не удалось использовать &quot;' . htmlspecialchars($_GET['login']) . '&quot; под защитой.';
} elseif ($u->info['align'] != 2) {
if ($u->info['money'] > 100) {
if (!isset($test['id'])) {
$u->addAction(time() + 300, 'psh0', $usr['id'], $usr['id']);
$test = mysql_fetch_array(mysql_query('SELECT `id`,`time` FROM `actions` WHERE `uid` = "' . $usr['id'] . '" AND `vars` = "psh0" AND `time` > "' . time() . '" LIMIT 1'));
}
$u->addAction(time(), 'propuskpsh', '', $usr['id']);
$u->error = 'Все прошло успешно, задержки в пещеры увеличены на 24 часа для &quot;' . $usr['login'] . '&quot;.';
Delo::add(
4,
'System.magic',
$usr['id'],
'&quot;<span style="color: olive; ">System.magic</span>&quot;: На персонажа применил магию Клаустрофобия ' . $u->info['login'],
);
$u->info['money'] = $u->info['money'] - 100;
mysql_query('UPDATE `users` SET `money` = `money` -100 WHERE `id` = ' . $u->info['id'] . ' LIMIT 1');
$test['time'] = time() + 86400;
mysql_query('UPDATE `actions` SET `time` = "' . $test['time'] . '" WHERE `uid` = ' . $usr['id'] . ' AND `id` = "' . $test['id'] . '" LIMIT 1');
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
$eff = mysql_fetch_array(mysql_query('SELECT * FROM `eff_users` WHERE `id_eff` = 476 AND `uid` = "' . $usr['id'] . '" LIMIT 1'));
if (isset($eff['id'])) {
mysql_query('DELETE FROM `eff_users` WHERE `id` = ' . $eff['id'] . ' AND `id_eff` = 476');
}
$this->add_eff($usr['id'], 476);
mysql_query(
'UPDATE `eff_users` SET `name` = "Клаустрофобия «' . $u->info['login'] . '»" WHERE `uid` = ' . $usr['id'] . ' AND `uid` = "' . $usr['id'] . '" AND `delete` = 0 AND `id_eff`= "476" LIMIT 1'
);
} else {
$u->error = 'У Вас недостаточно кр! Применение стоит 100кр.';
}
} else {
$u->error = 'Хаосники не могут пользоваться этим свитком!';
}

View File

@ -0,0 +1,76 @@
<?php
if (!defined('GAME')) {
die();
}
if ($itm['magic_inci'] == 'arhmoney') {
if ($u->info['inTurnir'] == 0) {
$u->error = 'Необходимо участвовать в турнире Башни Смерти';
} else {
$noarh = true;
$bsd = mysql_fetch_array(mysql_query('SELECT `id`,`users`,`arhiv`,`count`,`city`,`money` FROM `bs_turnirs` WHERE `id` = "' . $u->info['inTurnir'] . '" LIMIT 1'));
if (isset($bsd['id'])) {
$bsd_arh = mysql_fetch_array(mysql_query('SELECT `u`.`id`,`u`.`battle`,`s`.`x`,`s`.`y` FROM `users` AS `u` LEFT JOIN `stats` AS `s` ON `s`.`id` = `u`.`id` WHERE `u`.`inTurnir` = "' . $u->info['inTurnir'] . '" AND `u`.`login` = "Архивариус" AND `u`.`pass` = "bstowerbot" LIMIT 1'));
if ($bsd['users'] > 1 && $noarh == false && true == false) {
$u->error = 'Вы должны остаться единственным участником Башни Смерти';
} else {
if ($u->info['inUser'] == 0) {
$usr_tk = mysql_fetch_array(mysql_query('SELECT `level`,`id`,`money`,`login`,`align`,`clan`,`sex` FROM `users` WHERE `inUser` = "' . $u->info['id'] . '" LIMIT 1'));
if (isset($usr_tk['id'])) {
if ($itm['price2'] == 0) {
$u->addKr($itm['price1']);
} else {
$u->addEkr($itm['price2'], $usr_tk['id']);
}
mysql_query('UPDATE `items_users` SET `iznosNOW` = `iznosNOW` + 1 WHERE `id` = ' . $itm['id'] . ' LIMIT 1');
if ($itm['price2'] == 0) {
$u->error = 'Вы успешно обналичил чек на ' . $itm['price1'] . ' кр.';
} else {
$u->error = 'Вы успешно обналичил чек на ' . $itm['price2'] . ' екр.';
}
//Добавляем в лог БС
if ($itm['price2'] == 0) {
if ($u->info['sex'] == 0) {
$text = '{u1} обналичил чек на <b>' . $itm['price1'] . ' кр.</b>';
} else {
$text = '{u1} обналичила чек на <b>' . $itm['price1'] . ' кр.</b>';
}
} else {
if ($u->info['sex'] == 0) {
$text = '{u1} обналичил чек на <b>' . $itm['price2'] . ' екр.</b>';
} else {
$text = '{u1} обналичила чек на <b>' . $itm['price2'] . ' екр.</b>';
}
}
if (isset($usr_tk['id'])) {
$mereal = '';
if ($usr_tk['align'] > 0) {
$mereal .= '<img src=//img.new-combats.tech/i/align/align' . $usr_tk['align'] . '.gif width=12 height=15 >';
}
if ($usr_tk['clan'] > 0) {
$mereal .= '<img src=//img.new-combats.tech/i/clan/' . $usr_tk['clan'] . '.gif width=24 height=15 >';
}
$mereal .= '<b>' . $usr_tk['login'] . '</b> [' . $usr_tk['level'] . ']<a target=_blank href=/info/' . $usr_tk['id'] . ' ><img width=12 hiehgt=11 src=//img.new-combats.tech/i/inf_capitalcity.gif ></a>';
} else {
$mereal = '<i>Невидимка</i>[??]';
}
$text = str_replace('{u1}', $mereal, $text);
//Добавляем в лог БС
mysql_query('INSERT INTO `bs_logs` (`type`,`text`,`time`,`id_bs`,`count_bs`,`city`,`m`,`u`) VALUES (
"1", "' . mysql_real_escape_string($text) . '", "' . time() . '", "' . $bsd['id'] . '", "' . $bsd['count'] . '", "' . $bsd['city'] . '",
"' . round($bsd['money'] * 0.85, 2) . '","' . $i . '"
)');
//
} else {
$u->error = 'Что-то здесь не так...';
}
} else {
$u->error = 'Вы должны участвовать в турнире Башни Смерти';
}
}
} else {
$u->error = 'Необходимо участвовать в турнире Башни Смерти';
}
}
}
?>

View File

@ -1,6 +1,6 @@
<?php
//Феерверк
use Core\ConversionHelper;
use Helper\Conversion;
if (!defined('GAME')) {
die();
@ -20,14 +20,13 @@ if ($u->room['id'] != '9') {
$cmsg->setType(6);
$cmsg->setTypeTime(2);
$po = ConversionHelper::dataStringToArray($itm['data']);
$po = Conversion::dataStringToArray($itm['data']);
$fid = 'fw04';
if (isset($po['feerverk_eff'])) {
$fid = $po['feerverk_eff'];
}
mysql_query(
'INSERT INTO `feerverks` (`room`,`uid`,`time`,`fid`) VALUES ("' . $u->info['room'] . '","' . $u->info['id'] . '","' . time(
) . '","' . $fid . '")'
'INSERT INTO `feerverks` (`room`,`uid`,`time`,`fid`) VALUES ("' . $u->info['room'] . '","' . $u->info['id'] . '","' . time() . '","' . $fid . '")'
);
//
$a = $u->info['sex'] == 1 ? 'a' : ''; //окончание рода М\Ж в словах
@ -45,8 +44,7 @@ if ($u->room['id'] != '9') {
// У персонажа легкая травма - "Ожог от фейерверка" еще 3 мин. 43 сек.
// 22.02.14 21:14 лосенка пострадала от фейерверка! :fingal:
$spf = mysql_query(
'SELECT `id`,`login`,`sex` FROM `users` WHERE `online` > "' . (time(
) - 120) . '" AND `invis` = 0 AND `battle` = 0 AND `room` = "' . $u->info['room'] . '" ORDER BY `online` DESC LIMIT 100'
'SELECT `id`,`login`,`sex` FROM `users` WHERE `online` > "' . (time() - 120) . '" AND `invis` = 0 AND `battle` = 0 AND `room` = "' . $u->info['room'] . '" ORDER BY `online` DESC LIMIT 100'
);
$fusr = [];
while ($plf = mysql_fetch_array($spf)) {

View File

@ -1,4 +1,7 @@
<?php
use User\ItemsModel;
if(!defined('GAME'))
{
die();
@ -15,40 +18,40 @@ if(date('Y')==2013 || $u->info['id'] == 1) {
7. Новогодний Эликсир
*/
//Снежок 0/13 (x1)
$idit = \User\ItemsModel::addItem(1000,$u->info['id']);
$idit = ItemsModel::addItem(1000,$u->info['id']);
if($idit > 0) {
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "13" WHERE `id` = "'.$idit.'" LIMIT 1');
//Новогодний эликсир (x1)
$idit = \User\ItemsModel::addItem(997,$u->info['id']);
$idit = ItemsModel::addItem(997,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "7" WHERE `id` = "'.$idit.'" LIMIT 1');
//Новогодний эликсир (x1)
$idit = \User\ItemsModel::addItem(2870,$u->info['id']);
$idit = ItemsModel::addItem(2870,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "7" WHERE `id` = "'.$idit.'" LIMIT 1');
//Звездное сияние (x1)
$idit = \User\ItemsModel::addItem(1462,$u->info['id']);
$idit = ItemsModel::addItem(1462,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "7" WHERE `id` = "'.$idit.'" LIMIT 1');
//Открытка (x1)
$idit = \User\ItemsModel::addItem(996,$u->info['id']);
$idit = ItemsModel::addItem(996,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Новый Год" , `gtxt1` = "Администрация проекта поздравляет Вас с Новым, 2013, Годом!" WHERE `id` = "'.$idit.'" LIMIT 1');
//Нападалка 0/13 (x1)
$idit = \User\ItemsModel::addItem(874,$u->info['id']);
$idit = ItemsModel::addItem(874,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "13" WHERE `id` = "'.$idit.'" LIMIT 1');
//Кольцо жизни (x1)
$idit = \User\ItemsModel::addItem(2101,$u->info['id'],'|noremont=1|srok=1209600|sudba='.$u->info['login']);
$idit = ItemsModel::addItem(2101,$u->info['id'],'|noremont=1|srok=1209600|sudba='.$u->info['login']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год",`iznosMAX` = "13" WHERE `id` = "'.$idit.'" LIMIT 1');
//Восстановление Энергии 900НР (x3)
$idit = \User\ItemsModel::addItem(2710,$u->info['id']);
$idit = ItemsModel::addItem(2710,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год" WHERE `id` = "'.$idit.'" LIMIT 1');
$idit = \User\ItemsModel::addItem(2710,$u->info['id']);
$idit = ItemsModel::addItem(2710,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год" WHERE `id` = "'.$idit.'" LIMIT 1');
$idit = \User\ItemsModel::addItem(2710,$u->info['id']);
$idit = ItemsModel::addItem(2710,$u->info['id']);
mysql_query('UPDATE `items_users` SET `gift` = "Старый Год" WHERE `id` = "'.$idit.'" LIMIT 1');
$u->error = 'Вы успешно использовали &quot;'.$itm['name'].'&quot;. В инвентарь добавлены подарки. С Новым, 2013, Годом!';

Some files were not shown because too many files have changed in this diff Show More