\n";
echo "\n";
setlocale (LC_CTYPE, 'ru_RU.CP1251');
function win2unicode ( $s ) { if ( (ord($s)>=192) & (ord($s)<=255) ) $hexvalue=dechex(ord($s)+848); if ($s=="Ё") $hexvalue="401"; if ($s=="ё") $hexvalue="451"; return("".$hexvalue.";");}
function translate($s) {return(preg_replace("/[А-яЁё]/e","win2unicode('\\0')",$s));}
}
//===============================================
// обработка ошибок
//===============================================
function errorexit($s) { // эта функция выводит текст ошибки и завершает работу скрипта
ob_start("translate");echo " \n".$s."\n
Fatal error in line ".$errline." of file ".$errfile); break;
case ERROR: errorexit("ERROR [$errno] $errstr
in line ".$errline." of file ".$errfile); break;
case WARNING:errorexit("WARNING [$errno] $errstr
in line ".$errline." of file ".$errfile); break;
default: break;
}
}
//set_error_handler("myErrorHandler");
//===============================================
// работа с сессиями
//===============================================
if (!$login) $login=$sid; else {$login="user.".$login; $sid=$login;} // FIX: временно
/*
if ($usesession) {
if ($sid) {session_id($sid);session_start();} // надо вызывать перед стартом
else {session_start(); $sid = session_id();$sid=substr($sid,0,6); session_id($sid);} // укорачиваем имя сессии до 5 символов
} else $sid="";
*/
//===============================================
// загрузка сохраненной игры
//===============================================
if (file_exists($game_file)) { // FIX: тут надо заблокировать файл
$game = implode("",file($game_file));
$game = unserialize($game);
} else
$game = array(
"lastid" => 2,
"online" => array (),
"templates" => array(),
"players" => array(),
"locations" => array(
"loc.0" => array(
"id" =>"loc.0",
"title" => "Начало",
"desc" => "Вы стоите непонятно где. Хотя понятно - на начальной локации :-)",
"guard" => "0",
"exits" => array(),
"items" => array()
)
)
);
//===============================================
// искусственный интелект
//===============================================
if (time()-$game["lastai"]>$time_ai) ai();
//===============================================
// страницы логина и регистрации
//===============================================
//linkОсновнойСайт
if ($tmp=='') msg("Основная страница игры
Войти
Регистрация
Правила
Автор");
if ($rule==1) msg("Это онлайн RPG, все действия делаются из меню.");
if ($about==1) msg("Я автор типа...");
if ($connect==1) { //linkЛогин
msg ("
Регистрация "); msg($page_main); } if ($connect==2) { if (isset($game["players"][$login])) { if ($game["players"][$login]["password"]!=$password) msg("Неправильный пароль"); // добавляем в список Online $game["online"][$login]=$game["players"][$login]["title"]; // добавляем в локацию... $game["locations"][$game["players"][$login]["loc"]]["items"][$login]=array("id"=>$login); // всем в локации в журнал, что пришел такой-то addjournalall($game["players"][$login]["loc"],"Появился ".$game["players"][$login]["title"],$login); // очищаем свой журнал $game["players"][$login]["journal"]=""; // очищаем старый статус, кроме криминала (если крим, обновляем время крима) unset($game["players"][$login]["status"]); if ($game["players"][$login]["crim"]) {$game["players"][$login]["status"]["crim"]="криминал "; $game["players"][$login]["time_crim"] = time()+$time_crim;} $look=1; // при первом заходе выведем инфу о локации }else msg ("Неправильный логин: $login"); } if ($reg==1) { //linkРегистрация msg("
"); } if ($reg==2) { if ($game["players"][$login]=='') { $game["players"][$login] = array( "id"=>$login, "title"=>$name, "password"=>$password, "sex"=>$sex, "age"=>$age, "points"=>"2", "str"=>"2", "dex"=>"2", "int"=>"2", "loc"=>"loc.0", "time"=>time(), "ghost"=>"0", "attack"=>"", "crim"=>"0", "level"=>"0", "status"=>array(), "macros"=>array(1=>array("name"=>"повторить","act"=>"last","obj"=>"\"last\"","to"=>"\"last\"")), "journal"=>array(), "items"=>array(), "magic"=>array(), "skills"=>array() ); calcparam($login); // обновим все значения msg("Регистрация завершена"; $edit_view=str_replace("\\","",$edit_view); //print_r($edit_view); eval("print_r($edit_view);"); echo ""; $page_main.= "
Номер макроса должен быть в пределах от 1 до 9"); if (!$name) msg("
Задайте макросу имя!"); $game["players"][$login]["macros"][$num]["name"]=$name; $game["players"][$login]["macros"][$num]["act"]=$act; $game["players"][$login]["macros"][$num]["obj"]="\"".$obj."\""; $game["players"][$login]["macros"][$num]["to"]="\"".$to."\""; msg("
Макрос ".$name." сохранен"); } if ($macros=='delete' && $num) {// удалим $num unset($game["players"][$login]["macros"][$num]); msg("
Макрос ".$num." удален"); } if ($macros>0 && $macros<10) { // сам макрос $act = $game["players"][$login]["macros"][$macros]["act"]; if ($act=='last') $act=$game["players"][$login]["macros"]["last"]["action"]; $obj = $game["players"][$login]["macros"][$macros]["obj"]; if ($obj=='"last"') $obj=$game["players"][$login]["macros"]["last"]["object"]; $to = $game["players"][$login]["macros"][$macros]["to"]; if ($to=='"last"') $to=$game["players"][$login]["macros"]["last"]["target"]; if ($to=='"self"') $to=$login; // переназначаем переменные if ($act && $obj) eval('$'.$act."=".$obj.";"); if ($to) eval('$to='.$to.";"); } else msg("
Нет такого макроса"); } //=============================================== // переход в другую локацию //=============================================== if ($go) { //linkИдти // проверим, если такой выход в локации с игроком if (!isset($game["locations"][$game["players"][$login]["loc"]]["exits"][$go])) msg("Нет выхода $go в локации ".$game["locations"][$game["players"][$login]["loc"]]["id"]); $flag_go=1; // флаг, что надо перейти (он может измениться в eval) // если есть eval, то вначале выполним... if (isset($game["locations"][$game["players"][$login]["loc"]]["exits"][$go]["eval"])) eval($game["locations"][$game["players"][$login]["loc"]]["exits"][$go]["eval"]); if ($flag_go) { // переход // предупреждение о гард-зоне if (!$game["locations"][$game["players"][$login]["loc"]]["guard"] && $game["locations"][$go]["guard"]) addjournal($login,"Вы на охраняемой территории"); if ($game["locations"][$game["players"][$login]["loc"]]["guard"] && !$game["locations"][$go]["guard"]) addjournal($login,"Вы покинули охраняемую территорию"); // добавим всем в локацию, что такой-то ушел туда-то addjournalall($game["players"][$login]["loc"],$game["players"][$login]["title"]." ушел ".$game["locations"][$game["players"][$login]["loc"]]["exits"][$go]["title"],$login); // удаляем себя из старой локации unset($game["locations"][$game["players"][$login]["loc"]]["items"][$login]); // переходим в новую локацию $game["players"][$login]["loc"]=$go; // добавляем себя в эту новую локацию $game["locations"][$game["players"][$login]["loc"]]["items"][$login]=array("id"=>$login); // обновляем статус unset($game["players"][$login]["status"]["do"]); unset($game["players"][$login]["status"]["attack"]); // добавим всем в новой локации, что такой-то пришел оттуда-то addjournalall($game["players"][$login]["loc"],"Пришел ".$game["players"][$login]["title"],$login); $page_desc = "1"; } } //=============================================== // сказать //=============================================== if ($speak) { //linkСказать if (isset($game["players"][$speak])) {$to=$speak; $speak=1;} // разговор с игроком, подставим его имя в пле в расширенном экране разговора if ($speak==1) { if ($to) $to.=", "; $page_main.= "
------------ Сказать ------------";
$page_main.= "
";
$page_main.= "-----------------------------------";
msg($page_main);
} else // проверим, не наш ли это npc
if ($game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["owner"]==$login) {
$title = $game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["title"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["title"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["template"]]["title"];
$sayok = $game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["sayok"];
if ($sayok) $sayok=$sayok[rand(0,count($sayok)-1)]; else $sayok="[молча смотрит на вас]"; // случайная фраза из массива
$stmp = " ".$sayok;
if (!$id) { // основной диалог
$stmp.=" Выберите кого защищать:";
foreach ($game["locations"][$game["players"][$login]["loc"]]["items"] as $i) if ($i["id"]!=$login) if (substr($i["id"],0,4)=='npc.' || substr($i["id"],0,5)=='user.') {
if (isset($game["players"][$i["id"]])) $tto = $game["players"][$i["id"]]["title"]; else $tto = $i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
$stmp.=" Выберите за кем следовать:";
foreach ($game["locations"][$game["players"][$login]["loc"]]["items"] as $i) if ($i["id"]!=$login) if (substr($i["id"],0,4)=='npc.' || substr($i["id"],0,5)=='user.') {
if (isset($game["players"][$i["id"]])) $tto = $game["players"][$i["id"]]["title"]; else $tto = $i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
$stmp.=" Вы не можете разговаривать с персонажами, потому что вы призрак, найдите лекаря или камень воскрешения");
$game["players"][$login]["status"]["attack"]=""; // сбрасываем, что он атаковал
$game["players"][$login]["status"]["do"]="говорит с ";
$game["players"][$login]["status"]["do"].=$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["title"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["title"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["template"]]["title"];
$game["players"][$login]["status"]["do"].=" ";
if (!$id) $id="begin"; //FIX: если не указан id, то начнем с темы "begin"
$dialog=$dialog[$id];
$skillup=0; // если изменится в eval, то надо повысить навык
if (isset($dialog["eval"])) eval ($dialog["eval"]); // макрос в разговоре
if ($addmagic) { // добавляем магию $addmagic за $cost
// проверим, может такая магия уже есть
if (isset($game["players"][$login]["magic"][$addmagic])) msg(" У вас уже есть это заклинание");
// проверим, хватит ли денег
if ($cost) {
if (isset($game["players"][$login]["items"]["item.misc.money"]) && !isset($game["players"][$login]["items"]["item.misc.money"]["count"])) $game["players"][$login]["items"]["item.misc.money"]["count"]="1";
if (!isset($game["players"][$login]["items"]["item.misc.money"]) || $game["players"][$login]["items"]["item.misc.money"]["count"]<$cost) msg(" У вас недостаточно денег: ".$cost);
// снимаем деньги, если надо
$game["players"][$login]["items"]["item.misc.money"]["count"]-=$cost; if ($game["players"][$login]["items"]["item.misc.money"]["count"]==0) unset($game["players"][$login]["items"]["item.misc.money"]);
}
// добавляем заклинание в список
$game["players"][$login]["magic"][$addmagic]=$addmagic;
}else
if (!$skillup) {
$stmp=" ".$dialog["title"];
foreach($dialog["exits"] as $i) $stmp.=" У вас недостаточно денег: ".$cost);
}
// проверим, хватит ли очков опыта
if (!$num) $num=1;
if ($num>$game["players"][$login]["points"]) msg (" Не хватает очков опыта!");
// STR,DEX,INT
if ($skillup=='str' || $skillup=='dex' || $skillup=='int') {
if ($num+$game["players"][$login][$skillup]>$points_limit_attr_one) msg(" Невозможно повысить аттрибут ".$game["templates"]["misc.$skillup"]["title"].", т.к. он уже на максимальном уровне");
if ($skilldown) {
if ($game["players"][$login][$skilldown]-$num<1) msg(" Невозможно понизить ".$game["templates"]["misc.$skilldown"]["title"]." на ".$num." очков, выберите другой аттрибут или меньшее кол-во очков");
$game["players"][$login][$skilldown]-=$num;
}
$game["players"][$login][$skillup]+=$num;
$sum = $game["players"][$login]["str"]+$game["players"][$login]["dex"]+$game["players"][$login]["int"];
if ($sum>$points_limit_attr) {
$game["players"][$login][$skillup]-=$num;
$num=$sum-$points_limit_attr;
$stmp.= " Превышен предел суммы очков (".$points_limit_attr.") для аттрибутов, выберите что уменьшить на ".$num.": ";
if ($skillup!='str') $stmp.= " ".$game["templates"]["misc.$skillup"]["title"].": +".$num;
if ($skilldown) $stmp.=" Невозможно повысить навык ".$game["templates"][$skillup]["title"].", т.к. он уже на максимальном уровне");
if ($skilldown) {
if ($game["players"][$login]["skills"][$skilldown]["value"]-$num<0) msg(" Невозможно понизить ".$game["templates"][$skilldown]["title"]." на ".$num." очков, выберите другой навык или меньшее кол-во очков");
$game["players"][$login]["skills"][$skilldown]["value"]-=$num;
}
$game["players"][$login]["skills"][$skillup]["value"]+=$num;
$sum=0;
foreach ($game["players"][$login]["skills"] as $i) $sum+=$i["value"];
if ($sum>$points_limit_skills) {
$game["players"][$login]["skills"][$skillup]["value"]-=$num;
$num=$sum-$points_limit_skills;
$stmp.= " Превышен предел суммы очков (".$points_limit_skills.") для навыков, выберите что уменьшить на ".$num.": ";
foreach ($game["players"][$login]["skills"] as $i) if ($i["id"]!=$skillup) $stmp.= " ".$game["templates"][$skillup]["title"].": +".$num;
if ($skilldown) $stmp.=" Вряд ли вам удастся поговорить...");
} else msg(" Не с кем говорить");
}
if ($say) {
// добавим всем, включая себя, в журнал что сказали
addjournalall($game["players"][$login]["loc"],$game["players"][$login]["title"].": ".$say);
// добавим в макросы, что последнее действие было say
$game["players"][$login]["macros"]["last"]["action"]="say";
$game["players"][$login]["macros"]["last"]["object"]="\"".$say."\"";
}
//===============================================
// где я?
//===============================================
if ($pos==1) { //linkГдеЯ
// показываем инфу о месте где мы находимся
msg(" ".$game["locations"][$game["players"][$login]["loc"]]["pos"],"Где я?");
}
//===============================================
// Смотреть
//===============================================
if ($look) { //linkСмотреть
if ($look==1) {
// описание текущей локации
$page_desc = "1";
}else // игрок
if (isset($game["players"][$look])) {
if ($game["players"][$look]["sex"]=="m") $sex="мужской"; elseif ($game["players"][$look]["sex"]=="f") $sex="женский";
$stmp=" Пол: ".$sex." ";
for ($i=count($game["players"][$login]["journal"])-2;$i>-1;$i--) $stmp.=" Вы не можете ничего передать, поднять или бросить, потому что вы призрак, найдите лекаря или камень воскрешения");
// берем предмет из контейнера (напр. трупа)
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$move]) && !$to && ($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["container"] || $game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["template"]]["container"])) {
if (count($game["locations"][$from]["items"][$move]["items"])==0) msg(" Нет ничего");
if ($game["locations"][$from]["items"][$move]["crim"] || $game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["template"]]["crim"]) $stmp=" Криминал! ";
$stmp.="Выберите предмет:";
foreach($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["items"] as $i) {
$stmp.=" У вас нет ни одного предмета в банке");
$stmp=" Выберите предмет:";
foreach($game["players"][$login]["bank"] as $i) {
$stmp.=" У меня нет товаров на продажу",$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["title"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["title"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["template"]]["title"]);
$stmp=" Выберите предмет:";
foreach($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["bank"] as $i) if ($i["id"]!="item.misc.money") {
$stmp.=" Некому передать предмет");
// FIX: надо отслеживать, кому можно передавать предметы, а кому нет
if ($to!=$login && !isset($game["locations"][$to]) && !isset($game["locations"][$game["players"][$login]["loc"]]["items"][$to]["bankir"]) && !isset($game["locations"][$game["players"][$login]["loc"]]["items"][$to]["trader"])) msg(" Передавать предметы пока можно только банкиру или продавцу");
// указатель на $to
if($game["locations"][$game["players"][$login]["loc"]]["id"]==$to) $to=&$game["locations"][$game["players"][$login]["loc"]];
else if (isset($game["players"][$to])) $to=&$game["players"][$to];
else if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$to])) $to=&$game["locations"][$game["players"][$login]["loc"]]["items"][$to];
// проверим событие on_give у $to
$stmp=""; $stmp=$to["on_give"]?$to["on_give"]:$game["templates"][$to["template"]]["on_give"];
if ($stmp) eval($stmp);
// если даем банкиру, то передаваемый предмет положим себе в bank[]
if (isset($to["bankir"])) {$to=&$game["players"][$login]; $tt="bank";}
// проверим, есть ли в локации от кого передаем
if (!$from) $from=$login; else if ($game["locations"][$game["players"][$login]["loc"]]["id"]!=$from && !isset($game["locations"][$game["players"][$login]["loc"]]["items"][$from])) msg (" Нет от кого передать предмет");
// присвоим переменную от кого
if($game["locations"][$game["players"][$login]["loc"]]["id"]==$from) $from=&$game["locations"][$game["players"][$login]["loc"]];
else if (isset($game["players"][$from])) $from=&$game["players"][$from];
else if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$from])) $from=&$game["locations"][$game["players"][$login]["loc"]]["items"][$from];
// если берем у банкира, то передаваемый предмет возьмем у себя в bank[]
if (isset($from["bankir"])) {$from=&$game["players"][$login]; $ft="bank";} // если явно указан предмет
// если берем у продавца, то у него из bank[]
if (isset($from["trader"])) $ft="bank";
// определим, items[] или bank[]
if ($ft!='bank') $ft='items';
if ($tt!='bank') $tt='items';
// проверим, есть ли этот предмет у $from
if (!isset($from[$ft][$move])) msg(" У передающего нет такого предмета");
// проверим событие on_take у $move
$stmp=""; $stmp=$from[$ft][$move]["on_take"]?$from[$ft][$move]["on_take"]:$game["templates"][$from[$ft][$move]["template"]]["on_take"];
if ($stmp) eval($stmp);
if ($take) {
// проверим, можно ли его брать
$b=$from[$ft][$move]["notmove"]?$from[$ft][$move]["notmove"]:$game["templates"][$from[$ft][$move]["template"]]["notmove"];
if ($b) msg (" Этот предмет нельзя взять");
// FIX: надо проверить вес
// проверим кол-во
if (!isset($from[$ft][$move]["count"])) $from[$ft][$move]["count"]="1";
if (isset($to[$tt][$move]["count"]) && !isset($to[$tt][$move]["count"])) $to[$tt][$move]["count"]="1";
if (intval($num)==0) $num=1;
if ($num<1) $num=1; // операции минимум с одним предметом
if ($num>intval($from[$ft][$move]["count"])) $num=$from[$ft][$move]["count"]; // и максимум со всеми что есть
// если берем у продавца, то посчитаем цену, заберем у игрока
if (isset($from["trader"])) {
$price=$from["bank"][$move]["cost"]?$from["bank"][$move]["cost"]:$game["templates"][$from["bank"][$move]["template"]]["cost"];
$price_buy=$from["price_buy"]?$from["price_buy"]:$game["templates"][$from["template"]]["price_buy"];
if ($price_buy) $price*=$price_buy;
$price=round($price);
// проверим, есть ли у игрока столько денег и если есть, уменьшаем кол-во или удаляем вообще
if ($game["players"][$login]["items"]["item.misc.money"]["count"]<$price*$num) msg(" У вас нет столько денег: ".$price*$num);
else if ($game["players"][$login]["items"]["item.misc.money"]["count"]>$price*$num) $game["players"][$login]["items"]["item.misc.money"]["count"]-=$price*$num; else unset($game["players"][$login]["items"]["item.misc.money"]);
}
// если передаем продавцу, то посчитаем цену, добавим к игроку
if (isset($to["trader"])) {
if ($move=="item.misc.money") msg(" Не надо мне отдавать деньги, вначале выбери товар",$to["title"]?$to["title"]:$game["templates"][$to["template"]]["title"]);
$price=$game["players"][$login]["items"][$move]["cost"]?$game["players"][$login]["items"][$move]["cost"]:$game["templates"][$game["players"][$login]["items"][$move]["template"]]["cost"];
$price_sell=$to["price_sell"]?$to["price_sell"]:$game["templates"][$to["template"]]["price_sell"];
if ($price_sell) $price*=$price_sell;
$price=round($price);
if (!$buy) msg(" Я дам за это ".$price*$num." монет Вы не можете атаковать, потому что вы призрак, найдите лекаря или камень воскрешения");
$game["players"][$login]["macros"]["last"]["action"]="attack";
$game["players"][$login]["macros"]["last"]["object"]="\"".$attack."\"";
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$attack])) {
if (substr($attack,0,4)=='npc.' || substr($attack,0,5)=='user.') {
// установим статус, что нападаем на такого-то
if (isset($game["players"][$attack])) $i=$game["players"][$attack];
else $i=$game["locations"][$game["players"][$login]["loc"]]["items"][$attack];
// проверим, не криминал ли нападать на него... FIX: надо иметь список на кого напал, а вдруг он резко напал на другого?
// нападать можно на кримов, на тех кто напала на вас первым (attack=вы) или на животных animal=1
$crim=$i["crim"]?$i["crim"]:$game["templates"][$i["template"]]["crim"];
$animal = $i["animal"]?$i["animal"]:$game["templates"][$i["template"]]["animal"];
if ($i["attack"]==$login || $crim || $animal) $crim=0; else $crim=1;
if ($crim) {$game["players"][$login]["crim"]="1";$game["players"][$login]["time_crim"] = time()+$time_crim; $game["players"][$login]["attack"]=$attack; $game["players"][$login]["status"]["crim"]="криминал ";}
$title = $i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
$game["players"][$login]["status"]["attack"]="атакует ".$title." ";
attack($game["players"][$login]["loc"],$login,$attack);
} else addjournal($login,"Нападать можно только на людей, NPC и монстров");
} else addjournal($login,"Не на кого напасть");
}
//===============================================
// ИСПОЛЬЗОВАТЬ
//===============================================
if ($use) { //linkИспользовать
// .. если используем оружие item.weapon.xxx, то должно быть в руках, предметы можно и так
if ($game["players"][$login]["ghost"]) msg(" Вы не можете ничего использовать, потому что вы призрак, найдите лекаря или камень воскрешения");
$game["players"][$login]["macros"]["last"]["action"]="use";
$game["players"][$login]["macros"]["last"]["object"]="\"".$use."\"";
$game["players"][$login]["macros"]["last"]["target"]="\"".$to."\"";
if (substr($use,0,5)=="item.") { // предмет
// FIX: если пытаемся использовать оружие, вывести, что оно должно быть в руках
if (!isset($game["players"][$login]["items"][$use])) msg(" У вас нет этого предмета");
//if (!isset($game["players"][$login]["items"][$use]["equip"])) msg(" Вначале возьмите оружие в руки!");
$needtarget=$game["players"][$login]["items"][$use]["needtarget"]?$game["players"][$login]["items"][$use]["needtarget"]:$game["templates"][$game["players"][$login]["items"][$use]["template"]]["needtarget"];
if ($needtarget) $all=$use; else {
}
}
if (substr($use,0,6)=="magic.") { // магия
if ($game["templates"][$use]["needtarget"]) $all=$use; else {
}
}
if (substr($use,0,6)=="skill.") { // скилл
if ($game["templates"][$use]["needtarget"]) $all=$use; else {
}
}
// если не удалось использовать, выведем сообщение
if (!$used) addjournal($login,"Никакого эффекта");
}
//===============================================
// НАВЫКИ список
//===============================================
if ($skill) { //linkНавыки
// в $to цель, а в $skill=1
$stmp=" ";
if (!$to) $stmp.="Сила: ".$game["players"][$login]["str"]." У вас нет ни одного заклинания");
$stmp=" ";
if ($to) $stmp.="Выберите заклинание: "; else $stmp.="Заклинания: ";
foreach($game["players"][$login]["magic"] as $i) {
if ($to) {
$stmp.=" Вы не можете ничего одеть или снять, потому что вы призрак, найдите лекаря или камень воскрешения");
// проверим, есть ли такой предмет в инвентори
if (!isset($game["players"][$login]["items"][$equip])) msg("У вас нет такого предмета");
if ($game["players"][$login]["items"][$equip]["equip"]) { // надо снять
$stmp="";$stmp=$game["players"][$login]["items"][$equip]["on_deequip"]?$game["players"][$login]["items"][$equip]["on_deequip"]:$game["templates"][$game["players"][$login]["items"][$equip]["template"]]["on_deequip"];
if ($stmp) eval($stmp);
unset($game["players"][$login]["items"][$equip]["equip"]);
calcparam($login);
}else {//надо одеть
$eqt=$game["players"][$login]["items"][$equip]["equip_type"]?$game["players"][$login]["items"][$equip]["equip_type"]:$game["templates"][$game["players"][$login]["items"][$equip]["template"]]["equip_type"];
if (!$eqt) msg("Этот предмет нельзя одеть или взять в руки");
// вначале снимем если одет такой же тип
foreach ($game["players"][$login]["items"] as $i) if ($i["equip"]) {
$eqtold=$i["equip_type"]?$i["equip_type"]:$game["templates"][$i["template"]]["equip_type"];
if ($eqt==$eqtold) { // нашли такой же тип
$stmp=""; $stmp=$i["on_deequip"]?$i["on_deequip"]:$game["templates"][$i["template"]]["on_deequip"];
if ($stmp) eval($stmp);
unset($game["players"][$login]["items"][$i["id"]]["equip"]); // сняли
break; // для ускорения
}
}
$stmp=""; $stmp=$game["players"][$login]["items"][$equip]["on_equip"]?$$game["players"][$login]["items"][$equip]["on_equip"]:$game["templates"][$game["players"][$login]["items"][$equip]["template"]]["on_equip"];
if ($stmp) eval($stmp);
$game["players"][$login]["items"][$equip]["equip"]="1"; // одеваем
calcparam($login); // пересчитаем основные параметры
}
$inv=1;// это чтобы дальше показать инвентори
}
//===============================================
// ПРЕДМЕТЫ список
//===============================================
if ($inv) { //linkПредметы
// в $to цель, а в $inv=1|use|give
$stmp=" ";
if (!$to) {
$armor=$game["players"][$login]["armor"]; if (!$armor) $armor=0;
$stmp.="Урон: ".$game["players"][$login]["damage_min"]."-".$game["players"][$login]["damage_max"]." Броня: ".$armor;
} else $stmp.="Выберите предмет: ";
// FIX: тут надо сортировать предметы в таком порядке: оружие, руны, напитки, броня, еда, прочее
if (count($game["players"][$login]["items"])==0) $stmp.=" На себя Объекты:";
foreach($game["locations"][$game["players"][$login]["loc"]]["items"] as $i) if ($i["id"]!=$login) {
$stmp.=" Инвентори:";
foreach($game["players"][$login]["items"] as $i) {
$stmp.="
Обновить Выйти
$login
сказать
инвентори
магия
навыки";
for ($i=1;$i<10;$i++) if (isset($game["players"][$login]["macros"][$i])) $page_main.=" ".$game["players"][$login]["macros"][$i]["name"]."";
$page_main.=" (добавить)";
$curruser = &$game["players"][$login]; // текущий игрок
$currloc = &$game["locations"][$curruser["loc"]]; // текущая локация
// MAIN PAGE
//$page_main.= " Локация: ".$currloc["title"];
$page_main.= " ".$game["players"][$login]["life"]."/".$game["players"][$login]["mana"];
if ($game["players"][$login]["ghost"]) $page_main.= " Вы призрак";
if ($game["players"][$login]["crim"]) $page_main.= " Объекты:".$stmp;
// EXITS
if (count($currloc["exits"])>0) {
$page_main.= " Действия:";
foreach ($currloc["exits"] as $i) $page_main.= " ----------- NPC меню ----------";
$page_main.= "
\n";
if ($debug) echo "ЖУРНАЛ: \n";
if ($debug) echo "ОПИСАНИЕ: ".$title." ";
if (substr($msg,0,3)!=" ") $msg=" ".$msg;
echo "\n".$msg;
echo "\n
Насчет боя...";
$stmp.="
Насчет движения...";
$stmp.="
Приласкать";
$stmp.="
Состояние";
}
if ($id=='battle') { // режим боя
$stmp.="
Защищай меня";
$stmp.="
Не лезь в драку";
$stmp.="
Защищай...";
}
if ($id=='guardme') { // охранять меня
$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["guard"]=$login;
$stmp.="
Теперь будет защищать вас";
}
if ($id=='nelez') { // не вмешиваться в бой
unset($game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["guard"]);
$stmp.="
Не будет вмешиваться в бой";
}
if ($id=='guardlist') { // список кого защищать
$stmp="
".$tto."";
}
}
if ($id=='guard' && $who && $tto) { // защищать $who
$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["guard"]=$who;
$stmp.="
С этого момента будет защищать ".$tto;
}
if ($id=='move') { // режим движения
$stmp.="
Следуй за мной";
$stmp.="
Стой здесь";
$stmp.="
Следуй за...";
}
if ($id=='followme') { // следуй за мной
$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["follow"]=$login;
$stmp.="
Теперь будет следовать за вами";
}
if ($id=='stay') { // стой здесь
unset($game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["follow"]);
$stmp.="
Будет стоять здесь, пока не позовете";
}
if ($id=='followlist') { // список за кем следовать
$stmp="
".$tto."";
}
}
if ($id=='follow' && $who && $tto) { // следовать за $who
$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["follow"]=$who;
$stmp.="
С этого момента будет следовать за ".$tto;
}
if ($id=='lask') { // приласкать
if (rand(0,100)<$game["players"][$login]["skills"]["skill.animaltaming"]*10) {
if ($game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["time_owner"]) {
$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["time_owner"]+=rand(0,$game["players"][$login]["skills"]["skill.animallore"]*60);
$stmp.="
Кажется, вы стали ему нравиться немного больше";
}else $stmp.="
Он будет вам предан всегда, нет нужды в поощрении";
}else $stmp.="
Ваша попытка не призвела на него впечатления";
}
if ($id=='info') { // инфо когда покинет
if (!$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["time_owner"]) $stmp.="
Никогда вас не покинет";
else {
$timeleft = 60*($game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["time_owner"]-time());
// srand();
$pogr = rand(0,10*(10-$game["players"][$login]["skills"]["skill.animallore"]*2));
$pogr = $pogr*$timeleft/100;
$stmp.="
Покинет вас через ".($timeleft-$pogr)." - ".($timeleft+$pogr)." минут";
}
}
msg($stmp,$title);
} else // проверим npc
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$speak])) {
$dialog=$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["speak"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["speak"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$speak]["template"]]["speak"];
if ($dialog) {
if ($game["players"][$login]["ghost"]) msg("
".$i["title"]."";
$stmp=str_replace("
".$game["templates"]["misc.str"]["title"].": ".$game["players"][$login]["str"]."";
if ($skillup!='dex') $stmp.= "
".$game["templates"]["misc.dex"]["title"].": ".$game["players"][$login]["dex"]."";
if ($skillup!='int') $stmp.= "
".$game["templates"]["misc.int"]["title"].": ".$game["players"][$login]["int"]."";
msg($stmp);
} else {
$game["players"][$login]["points"]-=$num;
// если надо, уменьшим кол-во денег
if ($cost) {$game["players"][$login]["items"]["item.misc.money"]["count"]-=$cost; if ($game["players"][$login]["items"]["item.misc.money"]["count"]==0) unset($game["players"][$login]["items"]["item.misc.money"]);}
$stmp="
".$game["templates"]["misc.$skilldown"]["title"].": -".$num;
calcparam($login); // пересчитаем основные параметры
msg($stmp);
}
// НАВЫКИ
} else {
if ($num+$game["players"][$login]["skills"][$skillup]["value"]>$points_limit_skills_one) msg("
".$game["templates"][$i["id"]]["title"].": ".$i["value"]."";
msg($stmp);
} else {
$game["players"][$login]["points"]-=$num;
// если надо, уменьшим кол-во денег
if ($cost) {$game["players"][$login]["items"]["item.misc.money"]["count"]-=$cost; if ($game["players"][$login]["items"]["item.misc.money"]["count"]==0) unset($game["players"][$login]["items"]["item.misc.money"]);}
$stmp="
".$game["templates"][$skilldown]["title"].": -".$num;
calcparam($login); // пересчитаем основные параметры
msg($stmp);
}
}
//------------
}
} else msg("
Возраст: ".$game["players"][$look]["age"];
//новичок или опытный игрок
$stmp.="
";
$sum=$game["players"][$look]["level"];
$sum=$level*100/($points_limit_attr+$points_limit_skills);
if ($sum<5) $stmp.="Новичок";
if ($sum>=5 && $sum<15) $stmp.="Начинающий";
if ($sum>=15 && $sum<30) $stmp.="Приключенец";
if ($sum>=30 && $sum<50) $stmp.="Опытный";
if ($sum>=50 && $sum<60) $stmp.="Мастер";
if ($sum>=60 && $sum<80) $stmp.="Грандмастер";
if ($sum>=80 && $sum<90) $stmp.="Витязь";
if ($sum>=90) $stmp.="Лорд";
$stmp2="";
foreach($game["players"][$look]["items"] as $i) if (isset($i["equip"])) $stmp2.="
".$i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
if ($stmp2) $stmp.="
Одето:".$stmp2;
msg($stmp,$game["players"][$look]["title"],1);
}
else // предмет в инвентори может иметь свое описание
if (isset($game["players"][$login]["items"][$look])) {
$stmp="";
if ($game["players"][$login]["items"][$look]["crim"] || $game["templates"][$game["players"][$login]["items"][$look]["template"]]["crim"]) $stmp.="Предмет проклят!
";
$stmp.=$game["players"][$login]["items"][$look]["desc"]?$game["players"][$login]["items"][$look]["desc"]:$game["templates"][$game["players"][$login]["items"][$look]["template"]]["desc"];
msg($stmp);
}
else // любой предмет в окружении тоже может иметь свое описание
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$look])) {
$stmp="";
if ($game["locations"][$game["players"][$login]["loc"]]["items"][$look]["owner"]) $stmp.="Принадлежит ".$game["players"][$game["locations"][$game["players"][$login]["loc"]]["items"][$look]["owner"]]["title"]."
";
$stmp.=$game["locations"][$game["players"][$login]["loc"]]["items"][$look]["desc"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$look]["desc"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$look]["template"]]["desc"];
msg($stmp);
}
else // что либо стандартное: магия, скилл и т.д.
msg($game["templates"][$look]["desc"]);
}
//===============================================
// журнал
//===============================================
if ($journal==1) {
// выведем весь доступный журнал
$stmp="
".$game["players"][$login]["journal"][$i];
msg($stmp,"Журнал",0);
}
//===============================================
// передать
//===============================================
if ($move) { //linkПередать
$take=1;
if ($game["players"][$login]["ghost"]) if (isset($game["locations"][$from]) && ($game["locations"][$from]["items"][$move]["ressurect"] || $game["templates"][$game["locations"][$from]["items"][$move]["template"]]["ressurect"])) {ressurect($login); $take=0;} else msg("
";else $stmp="
";
$stmp.=$i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
$stmp.="";
}
msg($stmp);
}
// $move=предмет|банкир, $to=кому|loc, $from=от кого|loc=$login, [$num=кол-во=1, $tt=bank, $ft=bank]
// если в $move==банкир, то выведем список всего что в банке
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["bankir"])) {
if (count($game["players"][$login]["bank"])==0) msg("
";
if (isset($i["title"])) $stmp.=$i["title"]; else $stmp.=$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
$stmp.="";
}
msg($stmp);
}
// если в $move==продавец, то выведем список всего что у него банке на продажу
if (isset($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["trader"])) {
if (count($game["locations"][$game["players"][$login]["loc"]]["items"][$move]["bank"])==0) msg("
";
if (isset($i["title"])) $stmp.=$i["title"]; else $stmp.=$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
$price=$i["cost"]?$i["cost"]:$game["templates"][$i["template"]]["cost"];
$price_buy=$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["price_buy"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["price_buy"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["template"]]["price_buy"];
if ($price_buy) $price*=$price_buy;
$stmp.=" : ".$price;
$stmp.="";
}
msg($stmp,$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["title"]?$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["title"]:$game["templates"][$game["locations"][$game["players"][$login]["loc"]]["items"][$move]["template"]]["title"],1);
}
// проверим, есть ли в локации кому передаем
if (!$to) $to=$login; else if ($game["locations"][$game["players"][$login]["loc"]]["id"]!=$to && !isset($game["locations"][$game["players"][$login]["loc"]]["items"][$to])) msg ("
Согласен",$to["title"]?$to["title"]:$game["templates"][$to["template"]]["title"]);
// проверим, есть ли у игрока денеги и если нет, то добавляем объект деньги, иначе добавляем кол-во
if (isset($game["players"][$login]["items"]["item.misc.money"]) && !isset($game["players"][$login]["items"]["item.misc.money"]["count"])) $game["players"][$login]["items"]["item.misc.money"]["count"]="1";
if (!isset($game["players"][$login]["items"]["item.misc.money"])) $game["players"][$login]["items"]["item.misc.money"]=array("id"=>"item.misc.money","template"=>"item.misc.money","count"=>$price*$num);
else $game["players"][$login]["items"]["item.misc.money"]["count"]+=$price*$num;
$tt="bank";
}
// передаем предмет...
// если берем у крима или крим предмет, то становимся кримом
if ($to["id"]==$login && $from["crim"] || $from[$ft][$move]["crim"] || $game["templates"][$from[$ft][$move]["template"]]["crim"]) {$game["players"][$login]["crim"]="1";$game["players"][$login]["time_crim"] = time()+$time_crim; $game["players"][$login]["status"]["crim"]="криминал ";}
// добавляем к $to
if (isset($to[$tt][$move])) $to[$tt][$move]["count"]+=$num;
else {
$to[$tt][$move]=$from[$ft][$move];
$to[$tt][$move]["count"]="$num";
}
// удаляем флаг "экипирован" у $to
if (isset($to[$tt][$move]["equip"])) unset($to[$tt][$move]["equip"]);
// установим время, когда предмет надо уничтожить, т.к. он валяется
if (isset($to[$tt][$move]["time"])) $to[$tt][$move]["time"]=time()+$time_objects_destroy;
// удаляем из инвентори или уменьшаем кол-во
if ($num>=$from[$ft][$move]["count"]) {
// проверим событие on_deequip, но только для игрока $login
if ($from["id"]==$login) {
$stmp=""; $stmp=$from[$ft][$move]["on_deequip"]?$from[$ft][$move]["on_deequip"]:$game["templates"][$from[$ft][$move]["template"]]["on_deequip"];
if ($stmp) eval($stmp);
}
// снимаем если бросили все что есть
unset($from[$ft][$move]);
} else $from[$ft][$move]["count"]-=$num;
// добавим в журнал
if ($ft!='bank') {
if (isset($game["locations"][$to["id"]])) { // бросил
$stmp="";
if(isset($game["players"][$from])) $stmp=$game["players"][$from]["title"];
else $stmp=$from["title"]?$from["title"]:$game["templates"][$from["template"]]["title"];
addjournalall($to["id"],$stmp." бросил ".$num." предметов",$login);
}
if (isset($game["locations"][$from["id"]])) { // поднял
$stmp="";
if(isset($game["players"][$to])) $stmp=$game["players"][$to]["title"];
else $stmp=$to["title"]?$to["title"]:$game["templates"][$to["template"]]["title"];
addjournalall($from["id"],$stmp." поднял ".$num." предметов",$login);
}
// добавим в свой журнал
if ($to["id"]==$login) addjournal($login,"Вы взяли ".$num." предметов");
if ($from["id"]==$login) addjournal($login,"Вы передали ".$num." предметов");
}
}//if $take
}
//===============================================
// АТАКОВАТЬ
//===============================================
if ($attack) { //linkАтаковать
if ($game["players"][$login]["ghost"]) msg("
Ловкость: ".$game["players"][$login]["dex"]."
Интеллект: ".$game["players"][$login]["int"]."
Опыт: ".$game["players"][$login]["level"]."/".$points_levelup."
Очки опыта: ".$game["players"][$login]["points"];
else $stmp.="Выберите навык:";
foreach($game["players"][$login]["skills"] as $i) {
if ($to) {
$stmp.="
".$game["templates"][$i["id"]]["title"]."";
} else { // в след. экране all выберем цель $to для использования
$stmp.="
".$game["templates"][$i["id"]]["title"].": ".$i["value"]." Описание Использовать";
}
}
msg($stmp,"Навыки",1);
}
//===============================================
// МАГИЯ список
//===============================================
if ($magic) { //linkМагия
// в $to цель, а в $magic=1
if (count($game["players"][$login]["magic"])==0) msg("
".$game["templates"][$i]["title"]."";
} else { // в след. экране all выберем цель $to для использования
$stmp.="
".$game["templates"][$i]["title"]." Описание Использовать";
}
}
msg($stmp,"Магия",1);
}
//===============================================
// Экипироваться
//===============================================
if ($equip) { //linkЭкипироваться
if ($game["players"][$login]["ghost"]) msg("
У вас ничего нет";
foreach($game["players"][$login]["items"] as $i) {
if ($to) { // $inv=use|give
$stmp.="
";
if (isset($i["title"])) $stmp.=$i["title"]; else $stmp.=$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
if ($i["equip"]) $stmp.=" [одето]";
$stmp.="";
} else { // основное меню
$stmp.="
";
if (isset($i["title"])) $stmp.=$i["title"]; else $stmp.=$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
if ($i["equip"]) $stmp.=" [одето]";
$stmp.=" Описание
Использовать
Экипироваться
Бросить";
}
}
msg($stmp,"Предметы",1);
}
//===============================================
// ВСЕ список
//===============================================
if ($all) { //linkВсе
// выводим ссылку на себя, все окружение и все инвентори в отдельной карте
$stmp="
[Инвентори]";
// по всем предметам в локации
$stmp.="
";
if (isset($game["players"][$i["id"]])) $stmp.=$game["players"][$i["id"]]["title"];
else $stmp.=$i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
$stmp.="";
}
// по всем предметам в инвентори
$stmp.="
";
$stmp.=$i["title"]?$i["title"]:$game["templates"][$i["template"]]["title"];
if ($i["count"]>1) $stmp.=" (".$i["count"].")";
$stmp.="";
}
msg($stmp);
}
//===============================================
// собственно игра
//===============================================
//linkИгра
$page_main.= "
Вы криминал";
// SOUNDS
$stmp="";
foreach ($currloc["exits"] as $i) {
if (count($game["locations"][$i["to"]]["items"])>0) foreach($game["locations"][$i["to"]]["items"] as $j) if (substr($j["id"],0,5)=='user.' || substr($j["id"],0,4)=='npc.') {if ($stmp=='') $stmp="
Звуки: ".$i["title"]; else $stmp.=", ".$i["title"]; break;}
};
$page_main.= $stmp;
// FIX: тут надо сортировать: нападающие, нпс, игроки, предметы
// Объекты
$stmp="";
if (count($currloc["items"])>1) { // 1, т.к. не считая себя
foreach ($currloc["items"] as $i) if ($i["id"]!=$login) {
//if ($game["players"][$login]["ghost"] && !isset($game["players"][$i["id"]])) continue; // призраки видят только игроков
if (isset($game["players"][$i["id"]])) $k=&$game["players"][$i["id"]]; else $k=&$currloc["items"][$i["id"]];
$stmp.= "
";
$stmp.= $k["title"]?$k["title"]:$game["templates"][$k["template"]]["title"];
if (isset($k["count"]) && $k["count"]>1) $stmp.=" (".$k["count"].")";
// статус
if (isset($k["status"])) {
$sst=$k["status"]["life"].$k["status"]["crim"].$k["status"]["ghost"].$k["status"]["attack"].$k["status"]["do"];
//foreach($game["players"][$i["id"]]["status"] as $j) $stmp.=$j;
if ($sst) $stmp.=" [".$sst."]";
}
$stmp.= "";
}
}
if ($stmp) $page_main.="
".$i["title"]."";
$page_main.="
Осмотреться
Где я?";
$page_main.= "
-----------------------------------";
}
// NPC
$page_main.= "
Описание
Атаковать
Магия
Навыки
Предмет
Взять
Передать
Говорить
";
$page_main.= "
-----------------------------------";
$page_main.= "
----------------------------------------";
echo $page_journal;
if ($debug) echo "
----------------------------------------
";
echo "\n
----------------------------------------
";
echo $game["locations"][$game["players"][$login]["loc"]]["desc"];
if ($debug) echo "
----------------------------------------
";
echo "\n
----------------------------------------
";
if (substr($msg,strlen($msg)-4)!="