<?php

use Battles\DressedItems;
use Battles\GameLogs;
use Battles\ShopItem;
use Battles\Template;
use Battles\User;

require_once 'functions.php';
//require_once 'cave/cave_bots.php';
$userslots = ['sergi', 'kulon', 'perchi', 'weap', 'bron', 'r1', 'r2', 'r3', 'helm', 'shit', 'boots', 'rybax', 'plaw', 'm1', 'm2', 'm3', 'm4', 'm5', 'm6', 'm7', 'm8', 'm9', 'm10'];
function cancarry($m, $uid)
{
    if (!$uid) {
        $uid = User::getInstance()->getId();
    }
    $weight = \Battles\Database\Db::getInstance()->execute('select sum(weight) from inventory where owner_id = ? and on_sale = 0', $uid)->fetchColumn();
    $maxWeight = \Battles\Database\Db::getInstance()->execute('select strength * 4 from users where id = ?', $uid)->fetchColumn();
    return $weight + $m > $maxWeight ? false : true;
}

function placeinbackpack($qty, $userid = null)
{
    if (is_null($userid)) {
        $userid = User::getInstance()->getId();
    }
    $user1 = $userid === User::getInstance()->getId() ? User::getInstance() : User::getInstance($userid);
    $count = \Battles\Database\Db::getInstance()->execute('select count(*) from inventory where owner_id = ? and on_sale = 0', $user1->getId())->fetchColumn();
    return $count + $qty <= $user1->getLevel() * 10 + 5;
}

// x, $btl
// x, 0, $otherbots
function battlewithbot($b, $otherbots = [], $noredir = 0)
{
    $user1 = User::getInstance();

    $bot = mysql_fetch_array(mysql_query("SELECT `login`, `maxhp` FROM `users` WHERE `id` = '$b' LIMIT 1"));

    $name = $bot['login'];

    mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$name', '$b', '', '" . $bot['maxhp'] . "')");
    $hps[$b] = $bot['maxhp'];
    $botid1 = mysql_insert_id();
    $cond = " `id` = '$botid1' ";

    $teams = [];
    $teams[$user1['id']][$botid1] = [0, 0, time()];
    $teams[$botid1][$user1['id']] = [0, 0, time()];
    $t2 = "$botid1";

    $others = "";
    $hps = [];

    foreach ($otherbots as $k => $v) {
        if (CaveBots::$botnames[$v['name']]) {
            $i = 1;
            while (CaveBots::$botnames["$v[name] ($i)"]) $i++;
            $botname = "$v[name] ($i)";
        } else {
            $botname = $v['name'];
        }
        CaveBots::$botnames[$botname] = 1;
        if (!@$hps[$v['id']]) {
            $hps[$v['id']] = mysql_fetch_array(mysql_query("SELECT `maxhp` FROM `users` WHERE `id` = '$v[id]' LIMIT 1"));
        }
        mysql_query("INSERT INTO `bots` (`name`, `prototype`, `battle`, `hp`) VALUES ('$botname', '$v[id]', '', '" . $hps[$v['id']]['maxhp'] . "')");
        $botid = mysql_insert_id();
        $cond .= " OR `id` = '$botid' ";
        $teams[$user1['id']][$botid] = [0, 0, time()];
        $teams[$botid][$user1['id']] = [0, 0, time()];
        $others .= "<span class=date>" . date("H:i") . "</span> <span class=B2>$botname</span> вмешался в поединок.<BR>";
        $t2 .= ";$botid";
    }
    mysql_query("INSERT INTO `battle` (`id`, `coment`, `teams`, `timeout`, `type`, `status`, `t1`, `t2`, `to1`, `to2`, `blood`, `date`) VALUES (NULL, '', '" . serialize($teams) . "', '" . 3 . "', 1, 0, '" . $user1['id'] . "', '" . $t2 . "', '" . time() . "', '" . time() . "', 10, '" . date("Y-m-d H:i") . "')");

    $battleid = mysql_insert_id();
    mysql_query("UPDATE `bots` SET `battle` = {$battleid} WHERE $cond");
    mysql_query("UPDATE `users` SET `battle` = {$battleid} WHERE `id` = {$user1['id']} LIMIT 1");

    if ($user1['invis'] == 1) {
        $rr = "<b>невидимка</b> и <b>" . Nick::id($botid1)->full(1) . "</b>";
    } else {
        $rr = "<b>" . Nick::id($user1['id'])->full(1) . "</b> и <b>" . Nick::id($botid1)->full(1) . "</b>";
    }
    GameLogs::addBattleLog($battleid, "Часы показывали <span class=date>" . date("Y.m.d H.i") . "</span>, когда " . $rr . " бросили вызов друг другу. <BR>" . ($others ? "$others<BR>" : ""));
    if (!$noredir) {
        header("Location: fbattle.php");
    }

    return $battleid;
}

function gotoroom($r, $redir = 1)
{
    mysql_query("UPDATE `users`, `online` SET `users`.`room` = '$r', `online`.`room` = '$r' WHERE `online`.`id` = `users`.`id` AND `online`.`id` = '{$_SESSION['uid']}'");
    if ($redir) {
        redirectbyroom($r);
    }
}

function redirectbyroom($r)
{
    if (in_array($r, CANAL_ENTERS)) {
        header("location: enter_cave.php");
        exit;
    }
    if ($r == 1) {
        header("location: main.php");
        exit;
    }
}


$roomnames = [621 => "Рудник"];

if ($user["login"] == "Rallo Tabs") {
    if (isset($_GET['goto'])) {
        mysql_query("UPDATE `caveparties` SET  `x` =  '$_GET[x]', `y` =  '$_GET[y]', `floor` =  '$_GET[floor]' WHERE `caveparties`.`user` = $user[id] LIMIT 1");
        header('Location: cave.php');
        exit();
    }
    header("Content-Type: text/html; charset=utf-8");
}

if ($user['battle'] > 0) {
    header("location: fbattle.php");
    exit;
}

$objsizes = [0 => [0, 0], 1 => [120, 60], 2 => [120, 60], 3 => [120, 60], 4 => [110, 72], 5 => [120, 120]];

$objdata[3][0] = ["wd" => 1.44, "ht" => 1.44, "y" => 1, "x" => 176];
$objdata[3][1] = ["coef" => 1, "y" => 202, "x" => 176];
$objdata[1][1] = ["coef" => 1, "y" => 202, "x" => -65];
$objdata[5][1] = ["coef" => 1, "y" => 202, "x" => 435];
$objdata[3][2] = ["coef" => 0.67, "y" => 162, "x" => 176];
$objdata[1][2] = ["coef" => 0.67, "y" => 162, "x" => 18];
$objdata[5][2] = ["coef" => 0.67, "y" => 162, "x" => 342];
$objdata[3][3] = ["coef" => 0.50, "y" => 141, "x" => 176];
$objdata[1][3] = ["coef" => 0.50, "y" => 141, "x" => 50];
$objdata[5][3] = ["coef" => 0.50, "y" => 141, "x" => 300];
$imgdata[3][0] = ["wd" => 173, "ht" => 317, "y" => 1, "x" => [-37, 89, 215]];
$imgdata[3][1] = ["wd" => 87, "ht" => 161, "y" => 41, "x" => [68, 132, 196]];
$imgdata[1][1] = ["wd" => 87, "ht" => 161, "y" => 41, "x" => [-171, -44, -44]];
$imgdata[5][1] = ["wd" => 87, "ht" => 161, "y" => 41, "x" => [308, 308, 435]];
$imgdata[3][2] = ["wd" => 58, "ht" => 107, "y" => 55, "x" => [104, 147, 189]];
$imgdata[1][2] = ["wd" => 58, "ht" => 107, "y" => 55, "x" => [-56, 29, 29]];
$imgdata[5][2] = ["wd" => 58, "ht" => 107, "y" => 55, "x" => [264, 264, 350]];
$imgdata[3][3] = ["wd" => 44, "ht" => 81, "y" => 61, "x" => [122, 154, 186]];
$imgdata[1][3] = ["wd" => 44, "ht" => 81, "y" => 61, "x" => [1, 65, 65]];
$imgdata[5][3] = ["wd" => 44, "ht" => 81, "y" => 61, "x" => [242, 242, 306]];

$eventdata[3][1] = ["x" => 176, "y" => 200, "q" => 1];
$eventdata[3][2] = ["x" => 176, "y" => 149, "q" => 0.66];
$eventdata[1][2] = ["x" => 16, "y" => 149, "q" => 0.66];
$eventdata[5][2] = ["x" => 335, "y" => 149, "q" => 0.66];
$eventdata[3][3] = ["x" => 176, "y" => 133, "q" => 0.5];
$eventdata[1][3] = ["x" => 56, "y" => 133, "q" => 0.5];
$eventdata[5][3] = ["x" => 296, "y" => 133, "q" => 0.5];

$objects = [1 => "Спуск", 2 => "Спуск", 3 => "Спуск", 4 => "Сундук", 5 => "Спуск"];
$events = [];
$dialogs = [];
$noautoexit = 0;

function usagesleft($x, $y)
{
    global $map;
    $cell = explode("/", $map[$y * 2][$x * 2]);
    return $cell[3];
}

function takeusage($x, $y)
{
    global $map;
    $cell = explode("/", $map[$y * 2][$x * 2]);
    $cell[3]--;
    $map[$y * 2][$x * 2] = implode("/", $cell);
    updmap();
}

function makedeath()
{
    global $user, $floor, $loses, $x, $y, $dir;
    $cavedata = CAVE_DATA ?? [];
    if (!isset($cavedata[User::getInstance()->getRoom()]['x' . $floor])) {
        $floor = 1;
        loadmap();
    }
    mysql_query("UPDATE `caveparties` SET `floor` = $floor, `x` = '" . $cavedata[User::getInstance()->getRoom()]['x' . $floor] . "', `y` = '" . $cavedata[User::getInstance()->getRoom()]['y' . $floor] . "', `dir` = '" . $cavedata[User::getInstance()->getRoom()]['dir' . $floor] . "', `loses` = (`loses`+1) WHERE `user` = '$user[id]' LIMIT 1");
    mysql_query('UPDATE `users` SET `hp` = 1 WHERE `id` = "' . $user['id'] . '" LIMIT 1');
    $x = $cavedata[User::getInstance()->getRoom()]['x' . $floor];
    $y = $cavedata[User::getInstance()->getRoom()]['y' . $floor];
    $dir = $cavedata[User::getInstance()->getRoom()]['dir' . $floor];
    updparties();
    $loses++;
}

function itemtofloor($item, $foronetrip, $incave = 0, $podzem = 1, $from = 'shop', $small = 0)
{
    global $user, $x, $y, $floor;
    $rec = mysql_fetch_array(mysql_query("SELECT `name`, `img` FROM `$from` WHERE `id` = '$item' LIMIT 1"));
    mysql_query("INSERT INTO `caveitems` SET `leader` = '$user[caveleader]', `name` = '$rec[name]', `img` = '$rec[img]', `small` = '$small', `x` = '" . ($x * 2) . "', `y` = '" . ($y * 2) . "', `floor` = '$floor', `item` = '$item', `foronetrip` = '$foronetrip', `incave` = '$incave', `podzem` = '$podzem'");
    return "Вы нашли <b>$rec[name]</b>.";
}

function cavewall($w)
{
    if ($w < 100) {
        return floor($w / 10);
    } else {
        return floor($w / 1000) + 100;
    }
}

function passablewall($n)
{
    if ($n == 0 || $n == 31) {
        return true;
    }
    return false;
}

function canmoveto($cell, $freecell = 0, $passing = 0)
{
    if (!passablewall($passing)) {
        return false;
    }
    $obj = substr($cell, 0, 1);
    if ($obj == "e" || $obj == "u" || $obj == "s" || $obj == "p") {
        return true;
    }
    if (!$freecell && $cell) {
        return false;
    }
    if ($cell == $freecell) {
        return true;
    }
    return false;
}

function gotoxy($tox, $toy, $tofloor = 0, $msg = '')
{
    global $map, $x, $y, $floor, $user;
    $floor1 = $floor;
    $upd = "";
    if ($tox) {
        $tox = $tox / 2;
        if ($upd) {
            $upd .= ", ";
        }
        $upd .= " `x` = '$tox'";
        $x = $tox;
    }
    if ($toy) {
        $toy = $toy / 2;
        if ($upd) {
            $upd .= ", ";
        }
        $upd .= " `y` = '$toy'";
        $y = $toy;
    }
    if ($tofloor && $tofloor != $floor) {
        if ($upd) {
            $upd .= ", ";
        }
        $upd .= " `floor` = '$tofloor'";
        $floor = $tofloor;
    }
    mysql_query("UPDATE `caveparties` SET $upd WHERE `user` = '$user[id]' LIMIT 1");
    if ($tofloor && $tofloor != $floor1) {
        $map = mysql_fetch_assoc(mysql_query("SELECT `map` FROM `caves` WHERE `leader` = '$user[caveleader]' AND `floor` = '$floor' LIMIT 1"));
        $map = unserialize($map);
    }
    updparties();
    if ($msg) {
        header("Location: " . $_SERVER['PHP_SELF'] . ($msg ? '?msg=' . $msg : ''));
        exit();
    }
}

function updparties()
{
    global $user, $x, $y, $floor, $dir, $party;
    foreach ($party as $k => $v) {
        if ($v['user'] == $user['id']) {
            $party[$k]['dir'] = $dir;
            $party[$k]['x'] = $x;
            $party[$k]['y'] = $y;
            $party[$k]['floor'] = $floor;
        }
    }
}

function loadmap()
{
    global $user, $map, $floor;
    $map = mysql_fetch_array(mysql_query("SELECT `map` FROM `caves` WHERE `leader` = '$user[caveleader]' AND `floor` = '$floor' LIMIT 1"));
    $map = unserialize($map['map']);
}

function getslot($i, $user1 = 0)
{
    global $user, $userslots;
    if (!$user1) {
        $user1 = $user;
    }
    foreach ($userslots as $k => $v) {
        if ($user1[$v] == $i) {
            return $v;
        }
    }
}

function getcavedata($caveleader, $floor)
{
    return unserialize(implode("", file("cavedata/$caveleader-$floor.dat")));
}

if (isset($_GET['direction'])) {
    $dir = (int)$_GET['direction'];
    if ($dir >= 0 && $dir <= 3) {
        mysql_query("UPDATE `caveparties` SET `dir` = '$dir' WHERE `user` = '$user[id]' LIMIT 1");
    }
}

$party = [];
$r = mysql_query("SELECT `user`, `x`, `y`, `dir`, `login`, `shadow`, `floor`, `loses` FROM `caveparties` WHERE `leader` = '$user[caveleader]' ORDER BY `id` DESC");
while ($rec = mysql_fetch_assoc($r)) {
    if ($rec['user'] == $user['id']) {
        $x = $rec['x'];
        $y = $rec['y'];
        $dir = $rec['dir'];
        $floor = $rec['floor'];
        $loses = $rec['loses'];
    }
    $party[] = $rec;
}

if (User::getInstance()->getRoom() == 621) {
    $base = "/underdesigns/alchcave";
}

$maxloses = 3;
if ($loses >= $maxloses && !$noautoexit) {
    $_GET['exit'] = 1;
}

if (@$_GET['kill'] && $user['id'] == $user['caveleader'] && $_GET['kill'] != $user['login']) {
    foreach ($party as $k => $v) {
        if ($v['login'] == $_GET['kill']) {
            mysql_query("DELETE FROM `caveparties` WHERE `user` = '$v[user]'");
            mysql_query("UPDATE `users` SET `room` = (`room`-1), `caveleader` = 0 WHERE `id` = '$v[user]' LIMIT 1");
            $r = mysql_query("SELECT `id`, `dressed` FROM `inventory` WHERE `owner` = '$v[user]' AND `dressed` = 1 AND `foronetrip` = 1");
            if (mysql_num_rows($r) > 0) {
                $usr = mysql_fetch_array(mysql_query("SELECT " . implode(",", $userslots) . " FROM `users` WHERE `id` = '$v[user]'"));
            }
            while ($rec = mysql_fetch_assoc($r)) {
                $slot = getslot($rec['id'], $usr);
                if ($slot) {
                    $item = new DressedItems($v['user']);
                    $item->undressItem($slot);
                }
            }
            mysql_query("DELETE FROM `inventory` WHERE `owner` = '$v[user]' AND `foronetrip` = 1");
            unset($party[$k]);
            $report = "Персонаж $v[login] исключён из похода.";
            break;
        }
    }
    if (!@$report) {
        $report = "Персонаж $_GET[kill] не найден.";
    }
}

if ($_GET['change'] && $user['id'] == $user['caveleader'] && $_GET['change'] != $user['login']) {
    foreach ($party as $k => $v) {
        if ($v['login'] == $_GET['change']) {
            mysql_query("LOCK TABLES `users` WRITE, `caveparties` WRITE, `cavebots` WRITE, `caves` WRITE, `caveitems` WRITE");
            mysql_query("UPDATE `users` SET `caveleader` = '$v[user]' WHERE `caveleader` = '$user[id]'");
            mysql_query("UPDATE `cavebots` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
            mysql_query("UPDATE `caves` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
            mysql_query("UPDATE `caveparties` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
            mysql_query("UPDATE `caveitems` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
            $user['caveleader'] = $v['user'];
            $report = "Персонажу $v[login] присвоено лидерство.";
            mysql_query("UNLOCK TABLES");
            break;
        }
    }
    if (!@$report) {
        $report = "Персонаж $_GET[change] не найден.";
    }
}


if (@$_GET['useitem'] || @$_GET['usewallitem']) {
    mysql_query("LOCK TABLES `effects` WRITE, `cavebots` WRITE, `battle` WRITE, `users` WRITE, `caveparties` WRITE, `caves` WRITE, `shop` WRITE, `inventory` WRITE, `bots` WRITE, `caveitems` WRITE");
}

loadmap();


if ($_GET['useitem']) {
    if ($dir == 0) {
        $tx = $x - 1;
        $ty = $y;
    }
    if ($dir == 1) {
        $tx = $x;
        $ty = $y - 1;
    }
    if ($dir == 2) {
        $tx = $x + 1;
        $ty = $y;
    }
    if ($dir == 3) {
        $tx = $x;
        $ty = $y + 1;
    }
    if ($_GET['useitem'] && file_exists("underground/objects/" . User::getInstance()->getRoom() . ".php")) {
        include "underground/objects/" . User::getInstance()->getRoom() . ".php";
    }

    [$t, $obj] = explode("/", $map[$ty * 2][$tx * 2]);

    if ($t == "o" && $obj == 500) {
        $report = "В этот сундук уже кто-то заглядывал";
    }
    mysql_query("UNLOCK TABLES");
}

function updmap()
{
    global $map, $user, $floor;
    mysql_query("UPDATE `caves` SET `map` = '" . serialize($map) . "' WHERE `leader` = '$user[caveleader]' AND `floor` = '$floor' LIMIT 1");
}

if (@$_GET['usewallitem']) {
    if ($dir == 0) {
        $tx = $x * 2 - 1;
        $ty = $y * 2;
    }
    if ($dir == 1) {
        $tx = $x * 2;
        $ty = $y * 2 - 1;
    }
    if ($dir == 2) {
        $tx = $x * 2 + 1;
        $ty = $y * 2;
    }
    if ($dir == 3) {
        $tx = $x * 2;
        $ty = $y * 2 + 1;
    }

    $obj = $map[$ty][$tx];

    if ($obj == 18) {
        $report = "Вы не обнаружили ничего интересного.";
    }
    if ($obj == 19) {
        $report = "Уже проверено, сюда лучше не лазить.";
    }
    mysql_query("UNLOCK TABLES");
}

$r = mysql_query("SELECT `id`, `bot`, `x`, `y`, `cnt`, `type`, `battle` FROM `cavebots` WHERE `leader` = '$user[caveleader]' AND `floor` = '$floor'");
$mapbots = [];
$ambushes = [];
$cavedata = getcavedata($user['caveleader'], $floor);

if (time() - $cavedata['wander'] > 21) {
    $wander = 1;
} else {
    $wander = 0;
}

$wanderers = [];
while ($rec = mysql_fetch_assoc($r)) {
    if ($rec['type'] == 1 && $wander && $rec['battle'] == 0) {
        $wanderers[] = $rec;
        continue;
    }
    if (!@$mapbots[$rec['y']][$rec['x']]) {
        $mapbots[$rec['y']][$rec['x']] = "b";
    }
    if (($rec['type'] == 1 || $rec['type'] == 2) && $rec['battle'] == 0) {
        $ambushes[$rec['y']][$rec['x']] = 1;
    }
    $mapbots[$rec['y']][$rec['x']] .= "/$rec[bot]/$rec[cnt]";
}

if ($wander && !isset($_GET['attack'])) {
    foreach ($wanderers as $k => $v) {
        $d = rand(0, 3);
        for ($i = 0; $i < 4; $i++) {
            if ($d == 0) {
                $tx = $v['x'] - 2;
                $ty = $v['y'];
            }
            if ($d == 1) {
                $tx = $v['x'];
                $ty = $v['y'] - 2;
            }
            if ($d == 2) {
                $tx = $v['x'] + 2;
                $ty = $v['y'];
            }
            if ($d == 3) {
                $tx = $v['x'];
                $ty = $v['y'] + 2;
            }

            if (User::getInstance()->getRoom() == 74 || User::getInstance()->getRoom() == 76) {
                if (strpos($map[$ty][$tx], 's/') !== false && !@$mapbots[$ty][$tx]) {
                    break;
                }
            } else {
                if ($map[$ty][$tx] == 2 && !@$mapbots[$ty][$tx]) {
                    break;
                }
            }
            $d++;
            if ($d > 3) {
                $d = 0;
            }
        }
        if ($i < 4) {
            mysql_query("UDPATE `cavebots` set `x` = '$tx', `y` = '$ty' WHERE `id` = '$v[id]' LIMIT 1");
            $v['x'] = $tx;
            $v['y'] = $ty;
        }
        if (!@$mapbots[$v['y']][$v['x']]) {
            $mapbots[$v['y']][$v['x']] = "b";
        }
        $ambushes[$v['y']][$v['x']] = 1;
        $mapbots[$v['y']][$v['x']] .= "/$v[bot]/$v[cnt]";
    }
    $cavedata['wander'] = time();
    savecavedata($cavedata, $user['caveleader'], $floor);
}


foreach ($mapbots as $k => $v) {
    foreach ($v as $k2 => $v2) {
        $map[$k][$k2] = $v2;
    }
}

$moved = 0;

if (@$_GET['move'] && $_SESSION['movetime'] < time()) {
    if ($_GET['move'] == "x1" && canmoveto($map[$y * 2][$x * 2 + 2], 2, $map[$y * 2][$x * 2 + 1], 2)) {
        mysql_query("UPDATE `caveparties` SET `x` = (`x`+1) WHERE `user` = '$user[id]' LIMIT 1");
        $x++;
        $moved = 1;
    }
    if ($_GET['move'] == "x2" && canmoveto($map[$y * 2][$x * 2 - 2], 2, $map[$y * 2][$x * 2 - 1])) {
        mysql_query("UPDATE `caveparties` SET `x` = (`x`-1) WHERE `user` = '$user[id]' LIMIT 1");
        $x--;
        $moved = 1;
    }
    if ($_GET['move'] == "y1" && canmoveto($map[$y * 2 + 2][$x * 2], 2, $map[$y * 2 + 1][$x * 2])) {
        mysql_query("UPDATE `caveparties` SET `y` = (`y`+1) WHERE `user` = '$user[id]' LIMIT 1");
        $y++;
        $moved = 1;
    }
    if ($_GET['move'] == "y2" && canmoveto($map[$y * 2 - 2][$x * 2], 2, $map[$y * 2 - 1][$x * 2])) {
        mysql_query("UPDATE `caveparties` SET `y` = (`y`-1) WHERE `user` = '$user[id]' LIMIT 1");
        $y--;
        $moved = 1;
    }
    updparties();
    #$_SESSION['movetime'] = time()+5;
    $_SESSION['movetime'] = time();
}

if ($moved && (substr($map[$y * 2][$x * 2], 0, 1) === "e" || substr($map[$y * 2][$x * 2], 0, 1) === "p")) {
    $tx = $x;
    $ty = $y;
    $tmp = explode("/", $map[$y * 2][$x * 2]);
    if (file_exists("underground/events/" . User::getInstance()->getRoom() . ".php")) {
        include("underground/events/" . User::getInstance()->getRoom() . ".php");
    }
}

$ax = 0;
$ay = 0;
if ($ambushes[$y * 2 + 2][$x * 2] && $map[$y * 2 + 1][$x * 2] == 0) {
    $ax = $x;
    $ay = $y + 1;
}
if ($ambushes[$y * 2 - 2][$x * 2] && $map[$y * 2 - 1][$x * 2] == 0) {
    $ax = $x;
    $ay = $y - 1;
}
if ($ambushes[$y * 2][$x * 2 + 2] && $map[$y * 2][$x * 2 + 1] == 0) {
    $ax = $x + 1;
    $ay = $y;
}
if ($ambushes[$y * 2][$x * 2 - 2] && $map[$y * 2][$x * 2 - 1] == 0) {
    $ax = $x - 1;
    $ay = $y;
}

if ($ax && $ay && $user['hp'] > 0) {
    $cavedata = CAVE_DATA ?? [];
    if (!($cavedata[User::getInstance()->getRoom()]['x' . $floor] == $x && $cavedata[User::getInstance()->getRoom()]['y' . $floor] == $y)) {
        if ($ax < $x) {
            $dir1 = 0;
        } elseif ($ax > $x) {
            $dir1 = 2;
        } elseif ($ay < $y) {
            $dir1 = 1;
        } elseif ($ay > $y) {
            $dir1 = 3;
        }

        if ($dir != $dir1) {
            $dir = $dir1;
            mysql_query("UPDATE `caveparties` SET `dir` = '$dir' WHERE `user` = '$user[id]' LIMIT 1");
            foreach ($party as $k => $v) {
                if ($v['user'] == $user['id']) {
                    $party[$k]['dir'] = $dir1;
                }
            }
        }
        $_GET['attack'] = 1;
    }
}

if (!$_SESSION['movetime']) {
    #$_SESSION['movetime'] = time()+5;
    $_SESSION['movetime'] = time();
}

if ($_GET['takeitem']) {
    $_GET['takeitem'] = (int)$_GET['takeitem'];
    $it = mysql_fetch_array(mysql_query("SELECT `item`, `foronetrip`, `incave`, `podzem` FROM `caveitems` WHERE `leader` = '$user[caveleader]' AND `x` = '" . ($x * 2) . "' AND `y` = '" . ($y * 2) . "' AND `floor` = '$floor' AND `id` = '$_GET[takeitem]' LIMIT 1"));

    if (isset($it['item'])) {
        $ms = mysql_fetch_assoc(mysql_query("SELECT `massa` AS `mass` FROM $shop WHERE `id` = '$it[item]' LIMIT 1"));
        $shop = 'shop';
        if (!placeinbackpack(1, $user['id'])) {
            $report = "У вас в рюкзаке слишком много предметов.";
        } elseif (!cancarry($ms['mass'], $user)) {
            $report = "Ваш рюкзак перегружен.";
        } else {
            $destiny = 0;
            $taken = ShopItem::giveNewItem($it['item'], User::getInstance()->getId());
            if (@$taken['error']) {
                $report = $taken['error'];
            } else {
                mysql_query("DELETE FROM `caveitems` WHERE `leader` = '$user[caveleader]' AND `x` = '" . ($x * 2) . "' AND `y` ='" . ($y * 2) . "' AND `floor` = '$floor' AND `id` = '$_GET[takeitem]' LIMIT 1");
                $report = "Вы нашли $taken[name].";
            }
        }
    } else {
        $report = "Кто-то оказался быстрее...";
    }
}

if (@$_GET['speak']) {
    if ($dir == 0) {
        $x1 = $x * 2 - 2;
    } elseif ($dir == 2) {
        $x1 = $x * 2 + 2;
    } else {
        $x1 = $x * 2;
    }
    if ($dir == 1) {
        $y1 = $y * 2 - 2;
    } elseif ($dir == 3) {
        $y1 = $y * 2 + 2;
    } else {
        $y1 = $y * 2;
    }
    $cell = $map[$y1][$x1];
    $tmp = explode("/", $cell);
    if ($tmp[0] == "d") {
        header("location: dialog.php?char=$tmp[2]");
        exit;
    }

    if ($tmp[0] == "b" && isset($dialogs[CaveBots::$bots[$tmp[1]]])) {
        header("location: dialog.php?char=" . CaveBots::$bots[$tmp[1]]);
        exit;
    }
}

if (@$_GET['attack']) {
    if ($dir == 0) {
        $by = $y * 2;
        $bx = ($x - 1) * 2;
    }
    if ($dir == 1) {
        $by = ($y - 1) * 2;
        $bx = $x * 2;
    }
    if ($dir == 2) {
        $by = $y * 2;
        $bx = ($x + 1) * 2;
    }
    if ($dir == 3) {
        $by = ($y + 1) * 2;
        $bx = $x * 2;
    }

    $r = mysql_query("SELECT `bot`, `cnt`, `battle` FROM `cavebots` WHERE `leader` = '$user[caveleader]' AND `x` = $bx AND `y` = $by AND `floor` = '$floor'");

    $rec = mysql_fetch_assoc($r);
    if ($user['hp'] <= $user['maxhp'] * 0.33) {
        $report = 'Вы слишком ослаблены для поединка';
    } elseif (isset($rec['bot'])) {
        $btl = $rec['battle'];
        if ($btl > 0) {
            battlewithbot(CaveBots::$bots[$rec['bot']], $btl);
        } else {
            $firstbot = CaveBots::$bots[$rec['bot']];
            $otherbots = [];
            $rec['cnt']--;

            while ($rec['cnt'] > 0) {
                $otherbots[] = ['id' => CaveBots::$bots[$rec['bot']], 'name' => CaveBots::$botnames[$rec['bot']]];
                $rec["cnt"]--;
            }

            while ($rec = mysql_fetch_assoc($r)) {
                while ($rec['cnt'] > 0) {
                    $otherbots[] = ['id' => CaveBots::$bots[$rec['bot']], 'name' => CaveBots::$botnames[$rec['bot']]];
                    $rec['cnt']--;
                }
            }
            $btl = battlewithbot($firstbot, 0, $otherbots);
            mysql_query("UPDATE `cavebots` SET `battle` = '$btl' WHERE `leader` = '$user[caveleader]' AND `x` = '$bx' AND `y` = $by AND `floor` = '$floor'");
        }
    }
}

if (@$_GET['exit']) {
    if (count($party) == 1) {
        mysql_query("DELETE FROM `cavebots` WHERE `leader` = '$user[id]'");
        mysql_query("DELETE FROM `caves` WHERE `leader` = '$user[id]'");
        mysql_query("DELETE FROM `caveparties` WHERE `leader` = '$user[id]'");
        mysql_query("DELETE FROM `caveitems` WHERE `leader` = '$user[id]'");
        mysql_query("UPDATE `users` SET `caveleader` = 0 WHERE `id` = '$user[id]' LIMIT 1");
    } else {
        mysql_query("LOCK TABLES `users` WRITE, `caveparties` WRITE, `cavebots` WRITE, `caves` WRITE, `caveitems` WRITE, `diseases` WRITE, `caveeffects` WRITE");
        mysql_query("DELETE FROM `caveparties` WHERE `user` = '$user[id]'");
        mysql_query("UPDATE `users` SET `caveleader` = 0 WHERE `id` = '$user[id]' LIMIT 1");
        if ($user['caveleader'] == $user['id']) {
            foreach ($party as $k => $v) {
                if ($v['user'] != $user['id']) {
                    mysql_query("UPDATE `users` SET `caveleader` = '$v[user]' WHERE `caveleader` = '$user[id]'");
                    mysql_query("UPDATE `cavebots` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
                    mysql_query("UPDATE `caves` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
                    mysql_query("UPDATE `caveparties` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
                    mysql_query("UPDATE `caveitems` SET `leader` = '$v[user]' WHERE `leader` = '$user[id]'");
                }
            }
        }
        mysql_query("UNLOCK TABLES");
    }
    $r = mysql_query("SELECT `id`, `dressed` FROM `inventory` WHERE `owner` = '$user[id]' AND `dressed` = 1 AND `foronetrip` = 1");
    while ($rec = mysql_fetch_assoc($r)) {
        $slot = getslot($rec['id']);
        if ($slot) {
            $item = new DressedItems($user['id']);
            $item->undressItem($slot);
        }
    }
    mysql_query("DELETE FROM `inventory` WHERE `owner` = '$user[id]' AND `foronetrip` = 1");
    gotoroom(User::getInstance()->getRoom() - 1);
}

$standingon = $map[$y * 2][$x * 2];
foreach ($party as $k => $v) {
    $map[$v['y'] * 2][$v['x'] * 2] = "u/" . $v['user'];
}
Template::header('cave');
?>
    <style>
        body {
            font-family: Verdana, Arial, Helvetica, sans-serif;
            font-size: 10px;
            margin: 0 0 0 0;
        }

        .menu {
            z-index: 100;
            background-color: #E4F2DF;
            border-style: solid;
            border-width: 2px;
            border-color: #77c3fc;
            position: absolute;
            left: 0;
            top: 0;
            visibility: hidden;
            cursor: pointer;
        }

        a.menuItem {
            border: 0 solid #000000;
            background-color: #484848;
            color: #000000;
            display: block;
            font-family: Verdana, Arial, serif;
            font-size: 8pt;
            font-weight: bold;
            padding: 2px 12px 2px 8px;
            text-decoration: none;
        }

        a.menuItem:hover {
            background-color: #d4cbaa;
            color: #000000;
        }

        div.MoveLine {
            width: 108px;
            height: 7px;
            size: 2px;
            font-size: 2px;
            position: relative;
            overflow: hidden;
        }

        img.MoveLine {
            width: 108px;
            height: 7px;
            border: 0 solid;
            position: absolute;
            left: 0;
            top: 0
        }

        .cw1 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/cw1.gif?1)
        }

        .cw2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/cw2.gif?1)
        }

        .cw3 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/cw3.gif?1)
        }

        .cw4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/cw4.gif?1)
        }

        .cw5 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/cw5.gif?1)
        }

        .lw0 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw0.gif)
        }

        .lw1 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw1.gif)
        }

        .lw2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw2.gif)
        }

        .lw3 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw3.gif)
        }

        .lw4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw4.gif)
        }

        .rw0 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw0.gif)
        }

        .rw1 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw1.gif)
        }

        .rw2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw2.gif)
        }

        .rw3 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw3.gif)
        }

        .rw4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw4.gif)
        }

        .lsw0 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw0.gif)
        }

        .lsw1 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw1.gif)
        }

        .lsw2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw2.gif)
        }

        .lsw3 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw3.gif)
        }

        .lsw4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw4.gif)
        }

        .lsw42 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lsw42.gif)
        }

        .rsw0 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw0.gif)
        }

        .rsw1 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw1.gif)
        }

        .rsw2 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw2.gif)
        }

        .rsw3 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw3.gif)
        }

        .rsw4 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw4.gif)
        }

        .rsw42 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rsw42.gif)
        }

        .lw42 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/lw42.gif)
        }

        .rw42 {
            position: absolute;
            left: 0;
            top: 0;
            width: 352px;
            height: 240px;
            background-image: url(<?=$base?>/rw42.gif)
        }

        .maptd {
            width: 15px;
            height: 15px;
        }
    </style>
    <script>
        var Hint3Name = '';

        function closehint3() {
            document.getElementById("hint3").style.visibility = 'hidden';
        }

        function findlogin(title, script, name) {
            document.all("hint3").innerHTML = '<form action="' + script + '" method=GET><table width=100% cellspacing=1 cellpadding=0 bgcolor=CCC3AA><tr><td align=center><B style="font-size:11px">' + title + '</td><td width=20 align=right valign=top style="cursor: pointer" onclick="closehint3();"><BIG><B>x</td></tr><tr><td colspan=2>' +
                '<table width=100% cellspacing=0 cellpadding=2 bgcolor=FFF6DD><tr><INPUT TYPE=hidden name=sd4 value="<? echo @$user['id']; ?>"><td colspan=2>' +
                'Укажите логин персонажа:<small><BR>(можно щелкнуть по логину в чате)</TD></TR><TR><TD width=50% align=right><INPUT TYPE=text NAME="' + name + '"></TD><TD width=50%><INPUT TYPE="submit" value=" »» "></TD></TR></TABLE></td></tr></table></form>';
            document.getElementById("hint3").style.visibility = "visible";
            document.getElementById("hint3").style.left = 100;
            document.getElementById("hint3").style.top = 100;
            Hint3Name = name;
            document.all(name).focus();
        }

        function attackmenu(e) {
            var el, x, y;
            el = document.getElementById("oMenu");
            var posx = 0;
            var posy = 0;
            if (!e) var e = window.event;
            if (e.pageX || e.pageY) {
                posx = e.pageX;
                posy = e.pageY;
            } else if (e.clientX || e.clientY) {
                posx = e.clientX + document.body.scrollLeft;
                posy = e.clientY + document.body.scrollTop;
            }
            el.innerHTML = '<div style="color:#000;font-size:14px;padding:5px 10px 5px 10px" class=menuItem onmouseout="this.className=\'menuItem\';" onmouseover="this.className=\'menuItem2\';" onclick="this.disabled = true;document.location.href=\'cave.php?attack=1<?="&", time()?>\';"> <b>Напасть</b> </div>';
            el.style.left = posx + "px";
            el.style.top = posy + "px";
            el.style.visibility = "visible";
        }

        function speakmenu(e) {
            var el, x, y;
            el = document.getElementById("oMenu");
            var posx = 0;
            var posy = 0;
            if (!e) var e = window.event;
            if (e.pageX || e.pageY) {
                posx = e.pageX;
                posy = e.pageY;
            } else if (e.clientX || e.clientY) {
                posx = e.clientX + document.body.scrollLeft;
                posy = e.clientY + document.body.scrollTop;
            }
            el.innerHTML = '<div style="color:#000;font-size:14px;padding:5px 10px 5px 10px" class=menuItem onmouseout="this.className=\'menuItem\';" onmouseover="this.className=\'menuItem2\';" onclick="this.disabled =  true;document.location.href=\'cave.php?speak=1\';closeMenu(event);"> <b>Говорить</b> </div>';
            el.style.left = posx + "px";
            el.style.top = posy + "px";
            el.style.visibility = "visible";
        }

        function speakattackmenu(e) {
            var el, x, y;
            el = document.getElementById("oMenu");
            el2 = document.getElementById("oMenu2");
            var posx = 0;
            var posy = 0;
            if (!e) var e = window.event;
            if (e.pageX || e.pageY) {
                posx = e.pageX;
                posy = e.pageY;
            } else if (e.clientX || e.clientY) {
                posx = e.clientX + document.body.scrollLeft;
                posy = e.clientY + document.body.scrollTop;
            }

            el.innerHTML = '<div style="color:#000;font-size:14px;padding:5px 10px 5px 10px" class=menuItem onmouseout="this.className=\'menuItem\';" onmouseover="this.className=\'menuItem2\';" onclick="this.disabled = true;document.location.href=\'cave.php?attack=1<?="&", time()?>\';"> <b>Напасть</b> </div>';
            el.style.left = posx + "px";
            el.style.top = posy + "px";
            el.style.visibility = "visible";

            el2.innerHTML = '<div style="color:#000;font-size:14px;padding:5px 10px 5px 10px" class=menuItem onmouseout="this.className=\'menuItem\';" onmouseover="this.className=\'menuItem2\';" onclick="this.disabled =  true;document.location.href=\'cave.php?speak=1\';closeMenu(event);"> <b>Говорить</b> </div>';
            el2.style.left = posx + "px";
            el2.style.top = posy + 33 + "px";
            el2.style.visibility = "visible";
        }
    </script>
    <div id=hint3 class=ahint></div>
    <div style="z-index: 100;  background-color: #E4F2DF;  border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute;  left: 0;  top: 0;  visibility: hidden;  cursor:pointer;"
         id="oMenu"></div>
    <div style="z-index: 100;  background-color: #E4F2DF;  border-style: solid; border-width: 2px; border-color: #77c3fc; position: absolute;  left: 0;  top: 0;  visibility: hidden;  cursor:pointer;"
         id="oMenu2"></div>
<?

if ($user['hp'] <= 0) {
    makedeath();
}
$botNames = CaveBots::$botnames;
$botIds = CaveBots::$bots;
function drawmap($map1, $players, $x, $y, $direction)
{
    global $base, $user, $botNames, $imgdata;
    $startx = max($x * 2 - 8, 0);
    $starty = max($y * 2 - 8, 0);

    if ($direction == 0) {
        $x1 = $x * 2 + 2;
        $x2 = $x * 2 - 8;
        $y1 = $y * 2 + 3;
        $y2 = $y * 2 - 4;
    }
    if ($direction == 1) {
        $x1 = $x * 2 - 3;
        $x2 = $x * 2 + 4;
        $y1 = $y * 2 + 2;
        $y2 = $y * 2 - 8;
    }
    if ($direction == 2) {
        $x1 = $x * 2 - 2;
        $x2 = $x * 2 + 8;
        $y1 = $y * 2 - 3;
        $y2 = $y * 2 + 4;
    }
    if ($direction == 3) {
        $x1 = $x * 2 + 3;
        $x2 = $x * 2 - 4;
        $y1 = $y * 2 - 2;
        $y2 = $y * 2 + 8;
    }

    if ($x1 < $x2) {
        $dx = 1;
    } else {
        $dx = -1;
    }
    if ($y1 < $y2) {
        $dy = 1;
    } else {
        $dy = -1;
    }

    $x0 = 0;

    if ($direction % 2 == 1) {
        $sy1 = $y1;
        while ($x1 != $x2) {
            $y1 = $sy1;
            $y0 = -2;
            while ($y1 != $y2) {
                if ($map1[$y1][$x1] == 2) {
                    $sq = 0;
                } elseif (isset($map1[$y1][$x1])) {
                    $sq = $map1[$y1][$x1];
                } else {
                    $sq = 0;
                }
                $map[$x0][$y0] = $sq;
                $y1 += $dy;
                $y0++;
            }
            $x0++;
            $x1 += $dx;
        }
    } else {
        $sx1 = $x1;
        while ($y1 != $y2) {
            $x1 = $sx1;
            $x0 = -2;
            while ($x1 != $x2) {
                if ($map1[$y1][$x1] == 2) {
                    $sq = 0;
                } elseif (isset($map1[$y1][$x1])) {
                    $sq = $map1[$y1][$x1];
                } else {
                    $sq = 0;
                }
                $map[$y0][$x0] = $sq;
                $x1 += $dx;
                $x0++;
            }
            $y0++;
            $y1 += $dy;
        }
    }

    $ret = "<div style=\"width: 530px; height: 260px; background-image: url($base/podzem.jpg); background-repeat: no-repeat; overflow: hidden;\"><table cellspacing=0 cellpadding=0><tr><td style=\"padding-left: 10px; padding-top: 10px;\"><div style=\"position: relative; width: 354px; height: 239px; overflow: hidden;\">";

    $i = 7;
    $centerwall = 8;
    while ($i > 0) {
        if ($map[3][$i]) {
            $centerwall = $i;
        }
        $i -= 2;
    }
    $i = 4;

    function drawbot($cell, $x, $y)
    {
        global $botNames, $imgdata, $botIds, $dialogs, $user, $floor;
        $data = explode("/", $cell);
        $i = 1;
        $bc = (count($data) - 1) / 2;
        while ($data[$i]) {
            $bot = $data[$i];
            $botname = CaveBots::$botnames[$bot];
            $cnt = $data[$i + 1];
            if ($i == 1) {
                if ($bc == 1) {
                    $bn = 1;
                } else {
                    $bn = 0;
                }
            } elseif ($i == 3) {
                if ($bc == 2) {
                    $bn = 2;
                } else {
                    $bn = 1;
                }
            } else {
                $bn = 2;
            }

            $aMap = unserialize(mysql_result(mysql_query("SELECT `map` FROM `caves` WHERE `leader` = '$user[caveleader]' AND `floor` = '$floor'"), 0, 0));

            if (!$GLOBALS['dir']) {
                $xx = ($GLOBALS['x'] * 2) - ($y * 2);
                $yy = ($GLOBALS['y'] * 2) - ($x - 3);
            } elseif ($GLOBALS['dir'] == 1) {
                $xx = ($GLOBALS['x'] * 2) + ($x - 3);
                $yy = ($GLOBALS['y'] * 2) - ($y * 2);
            } elseif ($GLOBALS['dir'] == 2) {
                $xx = ($GLOBALS['x'] * 2) + ($y * 2);
                $yy = ($GLOBALS['y'] * 2) + ($x - 3);
            } else {
                $xx = ($GLOBALS['x'] * 2) - ($x - 3);
                $yy = ($GLOBALS['y'] * 2) + ($y * 2);
            }

            if (strpos($aMap[$yy][$xx], 'o/') !== false || strpos($aMap[$yy][$xx], 'p/') !== false) {
                $ret .= drawobject2($aMap[$yy][$xx], $x, $y);
            }

            $rrm = User::getInstance()->getRoom();

            if (isset($dialogs[CaveBots::$bots[$data[1]]]) && (CaveBots::$bots[$data[1]] == 11147 && User::getInstance()->getRoom() == 74)) {
                $ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? "onclick=\"speakattackmenu(event);\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
            } else {
                $ret .= "<img title=\"$botname" . ($cnt > 1 ? " ($cnt)" : "") . "\" " . ($y == 1 && $x == 3 ? " onclick=\"document.location.href='cave.php?attack=1';\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/mobs/$rrm/$bot.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
            }#onclick=\"attackmenu(event);\"
            $i += 2;
        }
        return $ret;
    }

    function drawdialog($cell, $x, $y)
    {
        global $dialogs, $imgdata;
        $data = explode("/", $cell);
        $i = 1;
        $d = $data[2];
        $bot = $data[$i];
        $botname = CaveBots::$botnames[$bot];
        $cnt = $data[$i + 1];
        $ret = "<img title=\"" . $dialogs[$d] . "\" " . ($x == 3 && $y == 1 ? "onclick=\"speakmenu(event);\"" : "") . " width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/npcs/$d.gif\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][1] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 && $y == 1 ? "cursor: pointer;" : "") . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
        return $ret;
    }

    function drawuser($cell, $x, $y)
    {
        global $botNames, $imgdata, $party;
        $data = explode("/", $cell);
        $i = 1;
        $bc = (count($data) - 1);
        while ($data[$i]) {
            $u = $data[$i];
            if ($i == 1) {
                if ($bc == 1) {
                    $bn = 1;
                } else {
                    $bn = 0;
                }
            } elseif ($i == 3) {
                if ($bc == 2) {
                    $bn = 2;
                } else {
                    $bn = 1;
                }
            } else {
                $bn = 2;
            }
            foreach ($party as $k => $v) {
                if ($v['user'] == $u) {
                    $udata = $v;
                    break;
                }
            }
            $ret .= "<img title=\"$udata[login]\" width=\"" . $imgdata[$x][$y]["wd"] . "\" height=\"" . $imgdata[$x][$y]["ht"] . "\" src=\"/i/dungeon/users/" . $udata['shadow'] . "\" style=\"position: absolute; left: " . $imgdata[$x][$y]["x"][$bn] . "px; top: " . $imgdata[$x][$y]["y"] . "px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
            $i++;
        }
        return $ret;
    }

    function drawobject($cell, $x, $y)
    {
        global $objects, $imgdata, $user, $objdata, $objsizes, $imgmap;
        $tmp = explode("/", $cell);
        $obj = $tmp[1];
        $ht = round($imgdata[$x][$y]["ht"] / 2);

        if ($objsizes[$obj]) {
            $coef = $objdata[$x][$y]["coef"];
            $wd = $objsizes[$obj][0] * $coef;
            $ht = $objsizes[$obj][1] * $coef;
            $left = round($objdata[$x][$y]["x"] - ($wd / 2));
            $top = $objdata[$x][$y]["y"] - $ht;
        } elseif ($obj == 510) {
            $wd = round($imgdata[$x][$y]["wd"] * 2.5);
            $ht = $imgdata[$x][$y]["ht"];
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"];
        } elseif ($obj > 600 && $obj < 700) {
            $wd = round($imgdata[$x][$y]["wd"] * 1.26);
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"] + $ht;
        } elseif ($obj >= 700 && $obj < 800) {
            $wd = round($imgdata[$x][$y]["wd"] * 1.24);
            $ht = $imgdata[$x][$y]["ht"];
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"];
        } else {
            $wd = $imgdata[$x][$y]["wd"];
            $left = $imgdata[$x][$y]["x"][1];
            $top = $imgdata[$x][$y]["y"] + $ht;
        }
        $rrm = User::getInstance()->getRoom();
        if (!isset($imgmap[$obj])) {

            $ret .= "
        " . ($y == 1 && $x == 3 ? "<a href=\"cave.php?useitem=1\">" : "") . " 
        <img border=\"0\" title=\"$objects[$obj]\" width=\"$wd\" height=\"$ht\" src=\"/i/dungeon/objects/$rrm/$obj.gif?1\" style=\"position: absolute; left: {$left}px; top: {$top}px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />
        " . ($y == 1 && $x == 3 ? "</a>" : "");
        } else {
            $ret .= "<img usemap=\"#" . $imgmap[$obj]['name'] . "\" border=\"0\" title=\"$objects[$obj]\" width=\"$wd\" height=\"$ht\" src=\"/i/dungeon/objects/$rrm/$obj.gif?1\" style=\"position: absolute; left: {$left}px; top: {$top}px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
            $ret .= $imgmap[$obj]['code'];
        }
        return $ret;
    }

    function drawobject2($cell, $x, $y)
    {
        global $objects, $imgdata, $user, $objdata, $objsizes, $imgmap;
        $tmp = explode("/", $cell);
        $obj = $tmp[1];
        $ht = round($imgdata[$x][$y]["ht"] / 2);
        if ($objsizes[$obj]) {
            $coef = $objdata[$x][$y]["coef"];
            $wd = $objsizes[$obj][0] * $coef;
            $ht = $objsizes[$obj][1] * $coef;
            $left = round($objdata[$x][$y]["x"] - ($wd / 2));
            $top = $objdata[$x][$y]["y"] - $ht;
        } elseif ($obj == 510) {
            $wd = round($imgdata[$x][$y]["wd"] * 2.5);
            $ht = $imgdata[$x][$y]["ht"];
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"];
        } elseif ($obj > 600 && $obj < 700) {
            $wd = round($imgdata[$x][$y]["wd"] * 1.26);
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"] + $ht;
        } elseif ($obj >= 700 && $obj < 800) {
            $wd = round($imgdata[$x][$y]["wd"] * 1.24);
            $ht = $imgdata[$x][$y]["ht"];
            $left = $imgdata[$x][$y]["x"][1] - round(($wd - $imgdata[$x][$y]["wd"]) / 2);
            $top = $imgdata[$x][$y]["y"];
        } else {
            $wd = $imgdata[$x][$y]["wd"];
            $left = $imgdata[$x][$y]["x"][1];
            $top = $imgdata[$x][$y]["y"] + $ht;
        }
        $rrm = User::getInstance()->getRoom();
        if (!isset($imgmap[$obj])) {
            $ret .= "
        " . ($y == 1 && $x == 3 ? "<a href=\"cave.php?useitem=1\">" : "") . " 
        <img border=\"0\" title=\"$objects[$obj]\" width=\"$wd\" height=\"$ht\" src=\"/i/dungeon/objects/$rrm/$obj.gif?1\" style=\"position: absolute; left: {$left}px; top: {$top}px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5) - 1) . ";" : "") . "\" />
        " . ($y == 1 && $x == 3 ? "</a>" : "");
        } else {
            $ret .= "<img usemap=\"#" . $imgmap[$obj]['name'] . "\" border=\"0\" title=\"$objects[$obj]\" width=\"$wd\" height=\"$ht\" src=\"/i/dungeon/objects/$rrm/$obj.gif?1\" style=\"position: absolute; left: {$left}px; top: {$top}px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5) - 1) . ";" : "") . "\" />";
            $ret .= $imgmap[$obj]['code'];
        }
        return $ret;
    }

    function drawevent($cell, $x, $y)
    {
        global $events, $eventdata;
        $tmp = explode("/", $cell);
        $obj = $tmp[1];
        if ($obj == 1) {
            return "";
        }
        $wd = round($eventdata[$x][$y]["q"] * $events[$obj]["w"]);
        $ht = round($eventdata[$x][$y]["q"] * $events[$obj]["h"]);
        $left = round(-$events[$obj]["h"] / 2 + $eventdata[$x][$y]["x"]);
        $top = round($eventdata[$x][$y]["y"] - $events[$obj]["h"]);
        $ret .= "<img border=\"0\" title=\"" . $events[$obj]["name"] . "\" width=\"$wd\" height=\"$ht\" src=\"/i/dungeon/events/$obj.gif\" style=\"position: absolute; left: {$left}px; top: {$top}px;" . ($x == 3 ? "z-index: " . (99 - ($y * 5)) . ";" : "") . "\" />";
        return $ret;
    }

    while ($i >= 0) {
        if ($i == 4) {
            if ($map[0][7]) {
                $ret .= "<div class=\"lw{$i}2\"></div>";
            }
            if ($map[0][6]) {
                $ret .= "<div class=\"lsw{$i}2\"></div>";
            }
            if ($map[-1][6]) {
                $ret .= "<img width=\"37\" height=\"78\" src=\"/i/dungeon/mobs/" . $map[-1][6] . ".gif\" style=\"position:absolute;left:-20px;top:60px\">";
            }
        }

        $wall = $i * 2 - 1;
        $sidewall = $i * 2;

        if ($map[1][$sidewall] && $i > 0) {
            $obj = substr($map[1][$sidewall], 0, 1);
            if ($obj == "b") {
                $ret .= drawbot($map[1][$sidewall], 1, $i);
            } elseif ($obj == "u") {
                $ret .= drawuser($map[1][$sidewall], 1, $i, $players);
            } elseif ($obj == "o" || $obj == "p") {
                $ret .= drawobject($map[1][$sidewall], 1, $i);
            } elseif ($obj == "e") {
                $ret .= drawevent($map[1][$sidewall], 1, $i);
            } elseif ($obj == "d") {
                $ret .= drawdialog($map[1][$sidewall], 1, $i);
            } elseif ($obj != "s") {
                $o = $map[1][$sidewall] - 10000;
                if ($o == 4) {
                    if ($i == 1) {
                        $ret .= "<img width=\"106\" height=\"101\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: -42px; top: 90px\" />";
                    }
                    if ($i == 2) {
                        $ret .= "<img width=\"86\" height=\"84\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: 137px; top: 90px\" />";
                    }
                    if ($i == 3) {
                        $ret .= "<img width=\"65\" height=\"63\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: 152px; top: 87px\" />";
                    }
                } else {
                    if ($i == 1) {
                        $ret .= "<img width=\"65\" height=\"80\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: 0; top: 110px\" />";
                    }
                    if ($i == 2) {
                        $ret .= "<img width=\"43\" height=\"56\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: 17px; top: 90px\" />";
                    }
                    if ($i == 3) {
                        $ret .= "<img width=\"32\" height=\"40\" src=\"/i/dungeon/objects/$o.gif\" style=\"position: absolute; left: 17px; top: 100px\" />";
                    }
                }
            }
        }

        if ($map[5][$sidewall] && $i > 0) {
            $obj = substr($map[5][$sidewall], 0, 1);
            if ($obj == "b") {
                $ret .= drawbot($map[5][$sidewall], 5, $i);
            } elseif ($obj == "u") {
                $ret .= drawuser($map[5][$sidewall], 5, $i, $players);
            } elseif ($obj == "o" || $obj == "p") {
                $ret .= drawobject($map[5][$sidewall], 5, $i);
            } elseif ($obj == "e") {
                $ret .= drawevent($map[5][$sidewall], 5, $i);
            } elseif ($obj == "d") {
                $ret .= drawdialog($map[5][$sidewall], 5, $i);
            } elseif ($obj != "s") {
                $o = $map[5][$sidewall] - 10000;
                if ($o == 4) {
                    if ($i == 1) $ret .= "<img width=\"106\" height=\"101\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:302px;top:90px\">";
                    if ($i == 2) $ret .= "<img width=\"86\" height=\"84\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:137px;top:90px\">";
                    if ($i == 3) $ret .= "<img width=\"65\" height=\"63\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:152px;top:87px\">";
                } else {
                    if ($i == 1) $ret .= "<img width=\"65\" height=\"80\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:320px;top:90px\">";
                    if ($i == 2) $ret .= "<img width=\"43\" height=\"56\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:300px;top:100px\">";
                    if ($i == 3) $ret .= "<img width=\"32\" height=\"40\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:317px;top:110px\">";
                }
            }
        }
        if ($i > 0 && $map[1][$wall]) $ret .= "<div class=\"lw$i\"></div>";

        $objInWall = explode('/', $map[4][$sidewall]);
        if ($objInWall[1] == 'o') {
            if (!passablewall($map[4][$sidewall])) $ret .= "<div  style=\"position:absolute;left:0;top:0;width:352px;height:240px;background-image:url($base/rsw$i$objInWall[2].gif)\"></div>";
        } else {
            if (!passablewall($map[4][$sidewall])) $ret .= "<div class=\"rsw$i\"></div>";
        }
        $objInWall = explode('/', $map[2][$sidewall]);
        if ($objInWall[1] == 'o') {
            if (!passablewall($map[2][$sidewall])) $ret .= "<div  style=\"position:absolute;left:0;top:0;width:352px;height:240px;background-image:url($base/lsw$i$objInWall[2].gif)\"></div>";
        } else {
            if (!passablewall($map[2][$sidewall])) $ret .= "<div class=\"lsw$i\"></div>";
        }

        if ($i > 0 && $map[5][$wall]) $ret .= "<div class=\"rw$i\"></div>";

        if ($map[3][$sidewall] && $i > 0 && $sidewall < $centerwall) {
            $obj = substr($map[3][$sidewall], 0, 1);
            if ($obj == "b") {
                $ret .= drawbot($map[3][$sidewall], 3, $i);
            } elseif ($obj == "u") {
                $ret .= drawuser($map[3][$sidewall], 3, $i, $players);
            } elseif ($obj == "o" || $obj == "p") {
                $ret .= drawobject($map[3][$sidewall], 3, $i);
            } elseif ($obj == "e") {
                $ret .= drawevent($map[3][$sidewall], 3, $i);
            } elseif ($obj == "d") {
                $ret .= drawdialog($map[3][$sidewall], 3, $i);
            } elseif ($obj != "s") {
                $o = $map[3][$sidewall] - 10000;
                if ($o == 4) {
                    if ($i == 1) $ret .= "<img width=\"130\" height=\"126\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:112px;top:80px\">";
                    if ($i == 2) $ret .= "<img width=\"86\" height=\"84\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:137px;top:90px\">";
                    if ($i == 3) $ret .= "<img width=\"65\" height=\"63\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:147px;top:87px\">";
                } else {
                    if ($i == 1) $ret .= "<a style=\"position:absolute;left:157px;top:110px;z-index:100\" href=\"cave.php?useitem=1\"><img border=\"0\" width=\"65\" height=\"80\" src=\"/i/dungeon/objects/$o.gif\"></a>";
                    if ($i == 2) $ret .= "<img width=\"43\" height=\"56\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:157px;top:105px\">";
                    if ($i == 3) $ret .= "<img width=\"32\" height=\"40\" src=\"/i/dungeon/objects/$o.gif\" style=\"position:absolute;left:157px;top:100px\">";
                }
            }
        }
        if ($map[3][$wall]) {
            if ($i > 0) $ret .= "<div class=\"cw$i\" " . ($map[3][$wall] > 2 ? "style=\"background-image:url('$base/cw$i" . cavewall($map[3][$wall]) . ".gif')\"" : "") . "></div>";
            if ($i == 1 && $map[3][$wall] > 2) {
                if ($map[3][$wall] > 1000) {
                    $ret .= "<a style=\"position:absolute;z-index:99;left:150px;top:35px\" href=\"cave.php?usewallitem=1&" . time() . "\"><img border=\"0\" src=\"" . IMGBASE . "/i/empty.gif\" width=\"45\" height=\"100\"></a>";
                } elseif ($map[3][$wall] > 100) {
                    $ret .= "<a style=\"position:absolute;z-index:99;left:150px;top:85px\" href=\"cave.php?usewallitem=1\"><img border=\"0\" src=\"" . IMGBASE . "/i/empty.gif\" width=\"100\" height=\"55\"></a>";
                } else $ret .= "<a style=\"position:absolute;z-index:99;left:60px;top:113px\" href=\"cave.php?usewallitem=1\"><img border=\"0\" src=\"" . IMGBASE . "/i/empty.gif\" width=\"128\" height=\"55\"></a>";
            }
            $objInWall = explode('/', $map[3][$wall]);
            if ($objInWall[1] == "o") {
                if (User::getInstance()->getRoom() == 83 && !(!$direction && (($x == 13 && $y == 4) || ($x == 12 && $y == 4)))) { // исключение 2-ух клеток в комнате 82
                    $ret .= drawobject('//' . $objInWall[2], 3, $i);
                }
            }
            $nocenter = 1;
        }
        if ($i == 4) {
            if ($map[7][6]) $ret .= "<img width=\"37\" height=\"78\" src=\"/i/dungeon/mobs/" . $map[7][6] . ".gif\" style=\"position:absolute;left:330px;top:60px\">";
        }
        $i--;
    }

    $ret .= "</div>
    </td><td valign=\"top\">
    <div style=\"height:116px;position:relative\">
    <div style=\"padding-top:11px;padding-left:33px\">
    <DIV class=\"MoveLine\"><IMG src=\"/i/move/wait3.gif\" id=\"MoveLine\" class=\"MoveLine\"></DIV>
    <div style=\"visibility:hidden; height:0\" id=\"moveto\">0</div>
    </div>";

    if ($direction == 0) {
        $forwardlink = "?move=x2&" . time();
        $backlink = "?move=x1&" . time();
        $leftlink = "?move=y1&" . time();
        $rightlink = "?move=y2&" . time();
    }
    if ($direction == 2) {
        $forwardlink = "?move=x1&" . time();
        $backlink = "?move=x2&" . time();
        $leftlink = "?move=y2&" . time();
        $rightlink = "?move=y1&" . time();
    }
    if ($direction == 1) {
        $forwardlink = "?move=y2&" . time();
        $backlink = "?move=y1&" . time();
        $leftlink = "?move=x2&" . time();
        $rightlink = "?move=x1&" . time();
    }
    if ($direction == 3) {
        $forwardlink = "?move=y1&" . time();
        $backlink = "?move=y2&" . time();
        $leftlink = "?move=x1&" . time();
        $rightlink = "?move=x2&" . time();
    }
    if (passablewall($map[3][1]) && canmoveto($map[3][2])) $ret .= "<div style='position:absolute; left:65px; top:38px;'><a onClick=\"return check('m1');\" id=\"m1\" href=\"$forwardlink\"><img src=\"/i/dungeon/forward.gif\"  border=\"0\" /></a></div>";
    if (passablewall($map[3][-1]) && canmoveto($map[3][-2])) $ret .= "<div style='position:absolute; left:65px; top:84px;'><a onClick=\"return check('m5');\" id=\"m5\" href=\"$backlink\"><img src=\"/i/dungeon/back.gif\" border=\"0\" /></a></div>";
    if (passablewall($map[2][0]) && canmoveto($map[1][0])) $ret .= "<div style='position:absolute; left:17px; top:49px;'><a onClick=\"return check('m7');\" id=\"m7\" href=\"$leftlink\"><img src=\"/i/dungeon/left.gif\" border=\"0\" /></a></div>";
    if (passablewall($map[4][0]) && canmoveto($map[5][0])) $ret .= "<div style='position:absolute; left:127px; top:48px;'><a onClick=\"return check('m3');\" id=\"m3\" href=\"$rightlink\"><img src=\"/i/dungeon/right.gif\" border=\"0\" /></a></div>";

    $ret .= "<div style='position:absolute; left:37px; top:37px;'><a href=\"?direction=" . ($direction == 0 ? 3 : $direction - 1) . "&" . time() . "\" title=\"Поворот налево\"><img src=\"/i/dungeon/turnleft.gif\" width=\"22\" height=\"20\" border=\"0\" /></a></div>";

    $ret .= "<div style='position:absolute; left:112px; top:37px;'><a href=\"?direction=" . (($direction + 1) % 4) . "&" . time() . "\" title=\"Поворот направо\"><img src=\"/i/dungeon/turnright.gif\" width=\"21\" height=\"20\" border=\"0\" /></a></div>";

    $ret .= "<div style='position:absolute; left:66px; top:62px;'><a href=\"$_SERVER[PHP_SELF]\"><img src=\"/i/dungeon/ref.gif\" border=\"0\"/></a></div>";
    $ret .= "</div>
    <div style=\"margin-left:20px;position:relative\">";

    foreach ($players as $k => $v) {
        if ($v["x"] - ($startx / 2) >= 0 && $v["x"] - ($startx / 2) <= 8 && $v["y"] - ($starty / 2) >= 0 && $v["y"] - ($starty / 2) <= 8) {
            $ret .= "<img alt=\"$v[login]\" title=\"$v[login]\" style=\"position:absolute;left:" . (($v["x"] - ($startx / 2)) * 15 + 3) . "px;top:" . (($v["y"] - ($starty / 2)) * 15 + 3) . "px\" src=\"/i/dungeon/" . ($k + 1) . "$v[dir].gif\">";
        }
    }
    $ret .= "<table cellspacing=0 cellpadding=0>";
    $i = $starty;
    while ($i < $starty + 18) {
        $ret .= "<tr>";
        $i2 = $startx;
        while ($i2 < $startx + 18) {
            $ret .= "<td class=\"maptd\">";
            if (strpos($map1[$i][$i2], 'h/') !== false) {
                $map1[$i][$i2] = 0;
            }
            if ($map1[$i][$i2]) {
                $ret .= "<img src=\"/i/dungeon/";
                if (!passablewall($map1[$i][$i2 - 1])) $ret .= "0"; else $ret .= "1";
                if (!passablewall($map1[$i - 1][$i2])) $ret .= "0"; else $ret .= "1";
                if (!passablewall($map1[$i][$i2 + 1])) $ret .= "0"; else $ret .= "1";
                if (!passablewall($map1[$i + 1][$i2])) $ret .= "0"; else $ret .= "1";
                $ret .= ".gif\">";
            }
            $ret .= "</td>";
            $i2 += 2;
        }
        $ret .= "</tr>";
        $i += 2;
    }
    $ret .= "</table></div>
    </td></tr></table>";

    $ret .= ">&nbsp;</span>';if (i<32) {s+='&nbsp;'}}document.getElementById('prcont').innerHTML=s;
    </script></div>";

    $ret .= "<TABLE><tr>
    <td nowrap=\"nowrap\" id=\"moveto\">
    </td></tr></TABLE>";
    $ret .= "</div>";
    $ret .= ">
var progressEnd = 108;		// set to number of progress <span>'s.
var progressColor = '#00CC00';	// set to progress bar color
var mtime = parseInt('";
    if (time() < $_SESSION["movetime"]) $ret .= $_SESSION["movetime"] - time();
    else $ret .= 0;
    $ret .= "');
if (!mtime || mtime <= 0 ) mtime = 0;
var progressInterval = Math.round( mtime * 1000 / progressEnd );
var is_accessible = true;
var progressAt = progressEnd;
var progressTimer;
function progress_clear() {
progressAt = 1;

for (var t = 1; t <= 8; t++) {
if( document.getElementById('m'+t) && ( t != 2 && t != 8 ))
document.getElementById('m'+t).style.backgroundImage = \"none\";
}
is_accessible = false;
set_moveto(true);
}
function progress_update() {
progressAt++;
if (progressAt > progressEnd) {
for (var t = 1; t <= 8; t++) {
if( document.getElementById('m'+t) && ( t != 2 && t != 8 ))
document.getElementById('m'+t).style.backgroundImage = \"\";
}
is_accessible = true;
if (window.solo_store && solo_store) { solo(solo_store, \"\"); } // go to stored
set_moveto(false);
} else {
if( !( progressAt % 2 ) )
document.getElementById('MoveLine').style.left = progressAt - progressEnd;
progressTimer = setTimeout('progress_update()',progressInterval);
}
}
function set_moveto (val) {
document.getElementById('moveto').disabled = val;
if (document.getElementById('bmoveto')) {
document.getElementById('bmoveto').disabled = val;
}
}
function progress_stop() {
clearTimeout(progressTimer);
progress_clear();
}
function check(it) {
return is_accessible;
}
function check_access () {
return is_accessible;
}
function ch_counter_color (color) {
progressColor = color;
for (var i = 1; i <= progressAt; i++) {
document.getElementById('progress'+i).style.backgroundColor = progressColor;
}
}
if (mtime>0) {
progress_clear();
progress_update();
}
</script>
";
    return $ret;
}

?>
    <table width="100%" border="0" cellspacing="0" cellpadding="0">
        <tr>
            <td valign="top" align="left">
                <br>
                <table width="400" border="0" cellspacing="1" cellpadding="0" bgcolor="#000000"
                       style="margin-left: 21px;">
                    <?
                    foreach ($party as $k => $v) {
                        if ($v["user"] == $user["id"]) {
                            $usr = $user;
                        } else {
                            $usr = mysql_fetch_array(mysql_query("SELECT `level`, `hp`, `maxhp` FROM `users` WHERE `id` = '$v[user]'"));
                        }
                        $wd = floor($usr["hp"] / $usr["maxhp"] * 120);
                        echo "<tr><td background=\"/i/bg_scroll_05.gif\" align=\"left\">
<a href=\"javascript:top.AddToPrivate('$v[login]', top.CtrlPress)\"><img src=\"i/lock.gif\" title=\"Приват\" border=\"0\" /></a> <a href=\"inf.php?$v[user]\" target=_blank title=\"Информация о $v[login]\">$v[login]</a> [$usr[level]]<a href='inf.php?$v[user]' target='_blank'><img src='/i/inf.gif' border=0></a></td>
<td background=\"/i/bg_scroll_05.gif\" nowrap style=\"font-size:9px\">
<div style=\"position: relative;padding-left:5px\">
<table cellspacing=\"0\" cellpadding=\"0\" style='line-height: 1'><td nowrap style=\"font-size:9px\" style=\"position: relative\"><SPAN " . ($v["user"] == $user["id"] ? "id=\"HP\"" : "") . " style='position: absolute; left: 5px; z-index: 1; font-weight: bold; color: #FFFFFF'>" . ($v["user"] == $user["id"] ? "<span id=\"hp_value\">" : "") . "$usr[hp]" . ($v["user"] == $user["id"] ? "</span>" : "") . "/$usr[maxhp]</SPAN><img src=\"/i/1green.gif\" alt=\"Уровень жизни\" " . ($v["user"] == $user["id"] ? "name=\"HP1\"" : "") . " width=\"$wd\" height=\"9\" " . ($v["user"] == $user["id"] ? "id=\"HP1\"" : "") . "><img src=\"/i/bk_life_loose.gif\" alt=\"Уровень жизни\" " . ($v["user"] == $user["id"] ? "name=\"HP2\"" : "") . " width=\"" . (120 - $wd) . "\" height=\"9\" " . ($v["user"] == $user["id"] ? "id=\"HP2\"" : "") . "></td></table></div></td>
<td background=\"/i/bg_scroll_05.gif\" align=\"center\"></td>
<td background=\"/i/bg_scroll_05.gif\" align=\"center\">";
                        if ($v["user"] == $user["id"] && $user["id"] == $user["caveleader"]) echo "<IMG src=\"/i/lead1.gif\" width=24 height=15><A href=\"#\" onClick=\"findlogin('Выберите персонажа которого хотите выгнать','cave.php', 'kill')\"><IMG alt=\"Выгнать супостата\" src=\"/i/ico_kill_member1.gif\" WIDTH=\"14\" HEIGHT=\"17\"></A>&nbsp;<A href=\"#\" onClick=\"findlogin( 'Выберите персонажа которому хотите передать лидерство','cave.php', 'change')\"><IMG alt=\"Новый царь\" src=\"/i/ico_change_leader1.gif\" WIDTH=\"14\" HEIGHT=\"17\"></A>";
                        echo "</td>
</tr>";
                    }
                    ?>
                </table>
                <br>
                <div style="padding-left: 15px; padding-right: 15px;">
                    <?php

                    if (isset($_GET['msg'])) {
                        $report = $_GET['msg'];
                    }

                    ?>
                    <font color=red><?= @$report ?>&nbsp;</font></div>
                <br/>
                <br><br/>
                <center>
                    <?
                    $r = mysql_query("SELECT * FROM `caveitems` WHERE `leader` = '$user[caveleader]' AND `x` = '" . ($x * 2) . "' AND `y` = '" . ($y * 2) . "' AND `floor` = '$floor'");
                    if (mysql_num_rows($r) > 0) echo "<font color=red>В комнате разбросаны вещи:</font><div style=\"font-size:3px\">&nbsp;</div>";
                    while ($rec = mysql_fetch_assoc($r)) {
                        echo "<a title=\"Поднять $rec[name]\" href=\"cave.php?takeitem=$rec[id]\"><img src=\"/i/sh/$rec[img]\"></a> ";
                    }
                    ?></center>
                <br>
                <?
                if ($loses >= 3) echo "<center><b><font color=red>Вас убили 3 раза, и вы покидете подземелье</font></b><br><br>
  <a href=\"cave.php?exit=1\">Вернуться</a></center><br>";
                if ($loses) echo "<div style=\"padding-left:20px\"><b>Количество смертей: $loses</b></div>";

                ?>
            </td>
            <td width=540>
                <div style="text-align:right;padding-right:30px">
                    <font style='font-size:14px; color:#8f0000'><b><?
                            $dMap = unserialize(mysql_result(mysql_query("SELECT `map` FROM `cavemaps` WHERE `floor` = $floor AND `room` = " . (User::getInstance()->getRoom() - 1)), 0, 0));
                            $cPlace = $dMap[$y * 2][$x * 2];
                            $tmp = explode("/", $cPlace);
                            if (User::getInstance()->getRoom() == 621) {
                                if ($floor == 1) {
                                    echo 'Проклятый Рудник, 1 этаж';
                                } elseif ($floor == 2) {
                                    echo 'Проклятый Рудник, 2 этаж';
                                }
                            } elseif (@$roomnames[$tmp[1]]) echo $roomnames[$tmp[1]];
                            else echo $rooms[$user["room"]];
                            ?></b></font>&nbsp;&nbsp;&nbsp;&nbsp;
                    <font style='font-size:14px; color:#8f0000'><b></b></font>&nbsp;&nbsp;&nbsp;&nbsp;<a
                            style="cursor:pointer;"
                            onclick="if (confirm('Вы уверены что хотите выйти?')) window.location='cave.php?exit=1'">&nbsp;<b
                                style='font-size:14px; color:#000066;'>Выйти</b></a>
                </div>
                <?
                echo drawmap($map, $party, $x, $y, $dir);
                ?>
            </td>
        </tr>
    </table>
<?

if ($user["login"] == "Rallo Tabs") {
    echo '
        <form action="cave.php" method="GET">
            x:&nbsp;<input size="2" name="x" value="' . $x . '" />
            y:&nbsp;<input size="2" name="y" value="' . $y . '" />
            floor:&nbsp;<input size="2" name="floor" value="' . $floor . '" />&nbsp;
            <input type="submit" name="goto" value="перейти" />
        </form>';
}
?>