Удалён нигде не применявшийся крон.

This commit is contained in:
lopar 2018-02-13 21:09:47 +02:00
parent 44ec1007b8
commit 9819971e7e
2 changed files with 8 additions and 979 deletions

View File

@ -10,13 +10,13 @@ include_once "../functions.php";
$tm = time();
##########
$zay = mysql_query('SELECT * FROM `zayavka`');
while($z = mysql_fetch_array($zay)) {
if($z['start'] <= time()) {
if($z['level'] == 4 || (($z['t1c'] == count($z['team1'])) && ($z['t2c'] == count($z['team2'])))) {
startbattle("CHAOS", $z['id'], 4);
} elseif($z['level'] == 5) {
startbattle("CHAOS", $z['id'], 5);
$zayavka = db::c()->query('SELECT `id`,`start`,`level`,`t1c`,`team1`,`t2c`,`team2` FROM `zayavka`')->fetch_assoc();
while($zayavka) {
if($zayavka['start'] <= time()) {
if($zayavka['level'] == 4 || (($zayavka['t1c'] == count($zayavka['team1'])) && ($zayavka['t2c'] == count($zayavka['team2'])))) {
startbattle("CHAOS", $zayavka['id'], 4);
} elseif($zayavka['level'] == 5) {
startbattle("CHAOS", $zayavka['id'], 5);
}
}
}
@ -67,7 +67,7 @@ function getlist($razdel = 1, $level = null, $id = null ) {
}
$zay[$row['id']] = array("team1" => fteam($row['team1']), "team2" => fteam($row['team2']), "coment" => $row['coment'], "type" => $row['type'], "timeout" => $row['timeout'], "start" => $row['start'], "t1min" => $row['t1min'], "t1max" => $row['t1max'], "t2min" => $row['t2min'], "t2max" => $row['t2max'], "t1c" => $row['t1c'], "t2c" => $row['t2c'], "podan" => $row['podan'], "id" => $row['id'], "level" => $row['level'], "blood" => $row['blood'], "bots" => $row['bots']);
}
return $zay;
return $zayavka;
}
function startbattle($id, $zay, $r) {

View File

@ -1,971 +0,0 @@
<?php
/* cron file */
//error_reporting(E_ALL);
//ini_set("display_errors", 1);
/*
//Считываем текущее время
$mtime = microtime();
//Разделяем секунды и миллисекунды
$mtime = explode(" ",$mtime);
//Составляем одно число из секунд и миллисекунд
$mtime = $mtime[1] + $mtime[0];
//Записываем стартовое время в переменную
$tstart = $mtime;*/
die();
session_start();;
$mysql = mysql_connect('localhost','user42163_onli','1W7y2E8u');
mysql_select_db('user42163_onli', $mysql);
mysql_query('SET NAMES CP1251;');
include "functions.php";
$tm=time();
/// чистим логи
if(date("H-i")=="03-00")
{
$del_tm=time()-60*60*24*7;
$us_lim=mysql_fetch_array(mysql_query("SELECT `id` FROM `battle` WHERE `to1`<'{$del_tm}' ORDER BY to1 DESC LIMIT 1;"));
$us_lim=$us_lim['id'];
mysql_query("DELETE FROM `logs` WHERE `id`<'{$us_lim}';");
mysql_query("DELETE FROM `battle` WHERE `id`<'{$us_lim}';");
$del_tm=time()-60*60*24*60;
mysql_query("DELETE FROM `delo` WHERE `date`<'".$del_tm."';");
mysql_query("OPTIMIZE `logs`,`battle`,`delo`;");
}
if(date("H-i")=="06-00")
{
//обнуляем способности
$abil=array("0"=>"1","1"=>"1","2"=>"2");
mysql_query("UPDATE `users` SET `abil`='".serialize($abil)."' WHERE `align`='2' OR `align`='8.31';");
$abil=array("0"=>"3","1"=>"0","2"=>"0");
mysql_query("UPDATE `users` SET `abil`='".serialize($abil)."' WHERE `level`='7' AND `align`='6';");
$abil=array("0"=>"3","1"=>"2","2"=>"0");
mysql_query("UPDATE `users` SET `abil`='".serialize($abil)."' WHERE `level`='8' AND `align`='6';");
$abil=array("0"=>"3","1"=>"2","2"=>"1");
mysql_query("UPDATE `users` SET `abil`='".serialize($abil)."' WHERE `level`>='9' AND `align`='6';");
for($i=0;$i<10;$i++) $abil[$i]=9;
mysql_query("UPDATE `users` SET `abil`='".serialize($abil)."' WHERE `align`>'7' AND `align`<'8';");
//обнуляем диггеров
mysql_query("UPDATE digger SET count_dig='0',count_guard='0';");
//обнуляем подарки
mysql_query("UPDATE `users` SET `podarokAD`='0';");
//обнуляем реферала месяца
if(date("d")=="01")
{
mysql_query("UPDATE variables SET value='{$tm}' WHERE var='ref_month';");
mysql_query("UPDATE variables SET value='0' WHERE var='ref_m_id';");
}
//обнуляем реферала недели
if(date("N")=="7")
{
mysql_query("UPDATE variables SET value='{$tm}' WHERE var='ref_week';");
mysql_query("UPDATE variables SET value='0' WHERE var='ref_w_id';");
}
//обнуляем парк
mysql_query("UPDATE `cit_park` SET `counter`=0,`bots`='',`room`=0;");
//задаем рейд на замок
$cc_time=$tm+rand(60*60*14,60*60*14.5);
mysql_query("UPDATE variables SET value='{$cc_time}' where var='cc_time';");
}
if(date("H-i")=="09-00")
{
//задаем рейд на ЦХ - 10-11
$ch_time=$tm+rand(60*60*1,60*60*2);
mysql_query("UPDATE variables SET value='{$ch_time}' where var='cit_haos_time';");
}
//задаем рейд утром
if(date("H-i")=="10-00")
{
//задаем рейд на город
$raid_time=$tm+rand(60*60*1.5,60*60*2.5);
mysql_query("UPDATE variables SET value='{$raid_time}' where var='raid_on_city';");
}
if(date("H-i")=="20-00")
{
//задаем рейд на ЦХ - 21-22
$ch_time=$tm+rand(60*60*1,60*60*2);
mysql_query("UPDATE variables SET value='{$ch_time}' where var='cit_haos_time';");
}
//берем дату и время Замка Мэра
if(date("z-H-i")==date("z-H-i",$c_castle['value']))
{
$c_castle=mysql_query("SELECT `value` FROM variables WHERE var='cc_time' LIMIT 1;");
addchsys('<font color=red>Начинается прием заявок на владение Замком Мэра! Начало боя через 15 минут.</font>');
}
//кто нападает
$cca=$c_castle['value']+930;
if(date("z-H-i")==date("z-H-i",$cca))
{
$cc_own=mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_owner' LIMIT 1;"));
$cc_k=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_own['value']}' LIMIT 1;"));
$cc_att=mysql_fetch_array(mysql_query("SELECT `value` FROM variables WHERE var='castle_att' LIMIT 1;"));
$cc_a=mysql_fetch_array(mysql_query("SELECT `name` FROM `clans` WHERE `id` = '{$cc_att['value']}' LIMIT 1;"));
if($cc_own['value']>0 && $cc_att['value']>0) {addchsys('<font color=red><strong>Клан <img title="'.$cc_a['name'].'" src="i/klan/'.$cc_a['name'].'.gif">'.$cc_a['name'].'</strong> готовится к битве за Замок Мэра с <strong>кланом <img title="'.$cc_k['name'].'" src="i/klan/'.$cc_k['name'].'.gif">'.$cc_k['name'].'</strong>! Начало боя через 1 минуту!</font>');}
elseif($cc_own['value']>0 && $cc_att['value']==0) {addchsys('<font color=red>Никто не осмелился оспорить права <strong>клана <img title="'.$cc_a['name'].'" src="i/klan/'.$cc_a['name'].'.gif">'.$cc_a['name'].'</strong> на Замок Мэра</font>');}
elseif($cc_own['value']==0 && $cc_att['value']>0) {addchsys('<font color=red><strong>Клан <img title="'.$cc_k['name'].'" src="i/klan/'.$cc_k['name'].'.gif">'.$cc_k['name'].'</strong> готовится к битве за Замок Мэра с <strong>силами Хаоса</strong>! Начало боя через 1 минуту!</font>');}
elseif($cc_own['value']==0 && $cc_att['value']==0) {addchsys('<font color=red>Никто не осмелился отбить у <strong>сил Хаоса</strong> Замок Мэра</font>');}
}
//берем дату-время рейда
$raid_t=mysql_fetch_array(mysql_query("SELECT * FROM variables WHERE var='raid_on_city' limit 1;"));
$ch_t=mysql_fetch_array(mysql_query("SELECT * FROM `variables` WHERE `var` = 'cit_haos_time' LIMIT 1;"));
//берем дату-время ЦХ
$raid_r=date("r",$raid_t['value']);
$ch_r=date("r",$ch_r['value']);
$zay_dub=mysql_fetch_array(mysql_query("SELECT * FROM zayavka WHERE `team1` LIKE '1000%' limit 1;"));
//рейд на город
if(date("H-i")==date("H-i",$raid_t['value']) && !$zay_dub['id']>0)
{
mysql_query("UPDATE variables SET value='2' where var='raid_on_status';");
}
//рейд на ЦХ
if(date("z-H-i")==date("z-H-i",$ch_t['value']))
{
mysql_query("DELETE FROM `cit_haos_status`;");
mysql_query("DELETE FROM `cit_haos_var`;");
addchsys('<font color=red>Начинается прием заявок в рейд на Цитадель Хаоса! Начало рейда через 15 минут.</font>');
}
// hp operations
//комплекты - костыль
$komp_users = mysql_query("SELECT * FROM `users`,`online` WHERE `users`.`id`=`online`.`id` AND `online`.`date` >= ".(time()-60).";");
while($ku=mysql_fetch_array($komp_users))
{
GiveExp($ku['id'],0);
$kompl_raw=mysql_query("SELECT * FROM inventory where owner=".$ku['id']." AND dressed=1");
$items_on_user=array();
$set_id_wear=array();
$kompl_ghp=0;
$kompl_gmana=0;
while ($kompl=mysql_fetch_array($kompl_raw))
{
$items_on_user[]=$kompl['prototype'];
};
$sets_raw=mysql_query("SELECT * FROM item_sets;");
while ($set_items=mysql_fetch_array($sets_raw))
{
$kompl_full=1;
$in_set=explode(',',$set_items['prot_id']);
foreach($in_set as $tmp_set)
if (!in_array($tmp_set,$items_on_user))
{$kompl_full=0;}
if ($kompl_full==1) $set_id_wear[]=$set_items['set_id'];
};
foreach($set_id_wear as $s)
{
$items_raw=mysql_fetch_array(mysql_query("SELECT `ghp`,`gmana` FROM item_sets where set_id='{$s}' limit 1;"));
$kompl_ghp+=$items_raw['ghp'];
$kompl_gmana+=$items_raw['gmana'];
};
if(!$kompl_ghp) $kompl_ghp=0;
if(!$kompl_gmana) $kompl_gmana=0;
mysql_query("UPDATE `users` SET `maxhp` = (IFNULL((SELECT SUM(`ghp`) FROM `inventory` WHERE dressed=1 AND owner = `users`.id),0) + (users.vinos*6)+'{$kompl_ghp}') WHERE `id`='{$ku['id']}';");
mysql_query("UPDATE `users` SET `maxmana` = (IFNULL((SELECT SUM(`gmp`) FROM `inventory` WHERE dressed=1 AND owner = `users`.id),0) + (users.mudra*10)+'{$kompl_gmana}') WHERE `id`='{$ku['id']}';");
}
//комплекты *
//mysql_query("UPDATE `users` SET `maxmana` = (IFNULL((SELECT SUM(`gmp`) FROM `inventory` WHERE dressed=1 AND owner = `users`.id),0) + (users.mudra*10));");
mysql_query("UPDATE `users` SET `hp` = '0' WHERE `hp` < '0' ");
mysql_query("UPDATE `users` SET `mana` = '0' WHERE `mana` < '0' ");
// ломаем шмот
$its = mysql_query("SELECT `id`,`owner`,`name` FROM `inventory` WHERE `dressed` = 0 AND ((`maxdur` <= `duration`) OR (`dategoden` > 0 AND `dategoden` <= '".time()."'));");
while($it = mysql_fetch_array($its))
{
//destructitem($it['id']);
mysql_query("DELETE FROM `inventory` WHERE `id` = '".$it['id']."' LIMIT 1;");
mysql_query("INSERT INTO `delo` (`id` , `author` ,`pers`, `text`, `type`, `date`) VALUES ('','0','\"".$it['name']."\" разрушился id:(cap".$it['id'].").',1,'".time()."');");
}
// травмы и хаос
$effs = mysql_query("SELECT * FROM `effects` WHERE `time` <= ".time().";");
mysql_query("DELETE FROM `effects` WHERE `time` <= ".time().";");
while($eff = mysql_fetch_array($effs)) {
switch ($eff['type'])
{
case 11:
mysql_query("UPDATE `users` SET `sila`=`sila`+'".$eff['sila']."', `lovk`=`lovk`+'".$eff['lovk']."', `inta`=`inta`+'".$eff['inta']."' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
//deltravma($eff['id']);
break;
case 12:
mysql_query("UPDATE `users` SET `sila`=`sila`+'".$eff['sila']."', `lovk`=`lovk`+'".$eff['lovk']."', `inta`=`inta`+'".$eff['inta']."' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
break;
case 13:
mysql_query("UPDATE `users` SET `sila`=`sila`+'".$eff['sila']."', `lovk`=`lovk`+'".$eff['lovk']."', `inta`=`inta`+'".$eff['inta']."' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
break;
case 14:
mysql_query("UPDATE `users` SET `sila`=`sila`+'".$eff['sila']."', `lovk`=`lovk`+'".$eff['lovk']."', `inta`=`inta`+'".$eff['inta']."' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
break;
case 21:
mysql_query("UPDATE `users` SET `sila`=`sila`-'".$eff['sila']."', `lovk`=`lovk`-'".$eff['lovk']."', `inta`=`inta`-'".$eff['inta']."', `vinos`=`vinos`-'".$eff['vinos']."' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
break;
case 4:
mysql_query("UPDATE `users` SET `align`='0' WHERE `id` = '".$eff['owner']."' LIMIT 1;");
break;
}
}
$data = mysql_query("SELECT `id`, `fullhptime` FROM `users` WHERE `hp` < `maxhp` AND `battle` = 0;");
while($user = mysql_fetch_array($data)) {
if ((time()-$user[1])/60 > 0)
{
mysql_query("UPDATE `users` SET `hp` = `hp`+((".time()."-`fullhptime`)/60)*(`maxhp`/20), `fullhptime` = ".time()." WHERE `hp` < `maxhp` AND `id` = '".$user[0]."' LIMIT 1;");
}
}
$data = mysql_query("SELECT `id`, `fullmptime` FROM `users` WHERE `mana` < `maxmana` AND `battle` = 0;");
while($user = mysql_fetch_array($data)) {
if ((time()-$user[1])/60 > 0 && $user[1])
{
mysql_query("UPDATE `users` SET `mana` = `mana`+((".time()."-`fullmptime`)/60)*(`maxmana`/30), `fullmptime` = '".time()."' WHERE `id` = '".$user[0]."' LIMIT 1;");
}
}
mysql_query("UPDATE `users` SET `hp` = `maxhp`, `fullhptime` = ".time()." WHERE `hp` > `maxhp` AND `battle` = 0;");
mysql_query("UPDATE `users` SET `mana` = `maxmana`, `fullmptime` = ".time()." WHERE (`mana` > `maxmana` OR `fullmptime` = 0) AND `battle` = 0;");
//============================ LAB HAOS =========================================
/* mysql_query("TRUNCATE TABLE `lab_inv`;");
mysql_query("TRUNCATE TABLE `lab_bots`;");
mysql_query("TRUNCATE TABLE `lab_trap`;");
// cheki
$paymers = rand (50,100);
for($i=1;$i<=$paymers;$i++) {
mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`) values ('".rand(0,1000)."','1','".(rand(1,10)/100)."');");
}
for($i=1;$i<=50;$i++) {
mysql_query("INSERT INTO `lab_inv` (`id_room`,`type`,`value`) values ('".rand(0,1000)."','2','".(rand(1,10)/100)."');");
}
// roomsi
for($i=1;$i<=1000;$i++) {
mysql_query("UPDATE `lab_rooms` SET p1='".rand(0,1000)."',p2='".rand(0,1000)."',p3='".rand(0,1000)."',p4='".rand(0,1000)."',`exit`=0 WHERE `id` = '".$i."' LIMIT 1;");
}
for($i=1;$i<=800;$i++) {
mysql_query("INSERT INTO `lab_bots` (`id_room`,`id_bot`) values ('".rand(0,1000)."','".(rand(1,4)+78)."');");
}
for($i=1;$i<=5;$i++) {
mysql_query("INSERT INTO `lab_bots` (`id_room`,`id_bot`) values ('".rand(0,1000)."','233');");
}
for($i=1;$i<=300;$i++) {
mysql_query("INSERT INTO `lab_trap` (`id_room`,`type`) values ('".rand(0,1000)."','".(rand(1,4))."');");
}
mysql_query("UPDATE `lab_rooms` SET `exit`=1 WHERE id = ".rand(1,1000)." LIMIT 1;");
*/
//====================================================================================
//start Haos Match - disabled
$hm_ok=array();
/*$hm_ongoing=mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var`='haos_match';"));
$hm_ongoing=unserialize($hm_ongoing['value']);
if($hm_ongoing)
foreach($hm_ongoing as $lvl=>$hm)
{
$check_win=mysql_fetch_array(mysql_query("SELECT `win` FROM `battle` WHERE `id`='{$hm}' LIMIT 1;"));
if(empty($check_win) || $check_win['win']==1 || $check_win['win']==2 || $check_win['win']==0) $hm_ok[$lvl]=1;
else $hm_ok[$lvl]=0;
}
else*/
{
$hm_ok['7']=1;
$hm_ok['8']=1;
$hm_ok['9']=1;
$hm_ok['10']=1;
$hm_ok['11']=1;
$hm_ok['12']=1;
}
/*echo("<pre>");
print_r($hm_ok);
echo("</pre>");*/
if(date("i")%30==0) //%15==0
{
$haos_match=array();
foreach($hm_ok as $lvl=>$flag)
if($flag==1)
{
mysql_query("INSERT INTO `zayavka`
(`start`, `timeout`, `t1c`, `t2c`, `type`, `level`, `coment`, `team1`, `stavka`, `t1min`, `t2min`, `t1max`, `t2max`,`podan`,`blood`) values
(".(time()+5*60).",5,50,50,2,4,'Бой с силами Хаоса {$lvl}','1001;','',49,{$lvl}, 50, {$lvl}, '".date("H:i")."', '0');");
$haos_match[$lvl]=mysql_insert_id();
}
mysql_query("UPDATE `variables` SET `value`='".serialize($haos_match)."' WHERE `var`='haos_match_zay';");
addchsys('<font color=red>Силы Хаоса вызывают бойцов клуба 7-12 уровней на поединок! Начало боя через 5 минут в групповых боях </font>');
}
// start BS
$tr = mysql_fetch_array(mysql_query("SELECT * FROM `deztow_turnir` WHERE `active` = TRUE"));
$turnirstart = mysql_fetch_array(mysql_query("SELECT `value` FROM `variables` WHERE `var` = 'startbs' LIMIT 1;"));
$dd = mysql_fetch_array(mysql_query("SELECT count(`kredit`) FROM `deztow_stavka`;"));
if($dd[0] < 2 && $turnirstart[0] <= time()) {
mysql_query('UPDATE `variables` SET `value` = \''.(time()+60*60*1).'\' WHERE `var` = \'startbs\';');
mysql_query("INSERT INTO `deztow_stavka` (`owner`,`kredit`,`time`) values ('1254','30','".time()."' ); ");
}
if(!$tr && $turnirstart[0] <= time() && $dd[0] >= 2){
// начинаем БС
//mysql_query("LOCK TABLES `shop` WRITE, `deztow_items` WRITE, `deztow_realchars` WRITE, `deztow_charstams` WRITE, `deztow_eff` WRITE, `deztow_gamers_inv` WRITE,`effects` WRITE, `deztow_turnir` WRITE, `deztow_stavka` WRITE, `users` WRITE, `inventory` WRITE, `online` WRITE;");
$minroom = 501;
$maxroom = 560;
// вычисляем кто прошел в турнир
$data = mysql_query("SELECT dt.owner FROM `deztow_stavka` as dt, `online` as o WHERE (SELECT count(`id`) FROM `effects` WHERE `effects`.`owner` = dt.owner AND ( type=11 OR type=12 OR type=13 OR type=14)) = 0 AND o.id = dt.owner AND room = 31 AND o.`date` >= '".(time()-300)."' ORDER by `kredit` DESC, dt.`time` ASC LIMIT 40;");
$stavka = mysql_fetch_array(mysql_query("SELECT SUM(`kredit`)*0.7 FROM `deztow_stavka`;"));
// удаляем сразу, чтоб другим не повадно было
if($data) {
mysql_query("TRUNCATE TABLE `deztow_stavka`;");
mysql_query("TRUNCATE TABLE `deztow_gamers_inv`;");
}
while($row=mysql_fetch_array($data)) {
// делаем каждому чару бекап в базу специальную, раздеваем и все такое
undressall($row[0]); // раздели
$shmot = mysql_query("SELECT * FROM `inventory` WHERE `owner` = '".$row[0]."';");// бекапим весь шмот
mysql_query("UPDATE `inventory` SET `owner` = 0 WHERE `owner` = '".$row[0]."';");
while($sh = mysql_fetch_array($shmot)) {
mysql_query("INSERT `deztow_gamers_inv` (`id_item`,`owner`) values ('".$sh[0]."','".$row[0]."');");
}
// effects
$effs = mysql_query("SELECT * FROM `effects` WHERE `owner` = '".$row[0]."';"); // бекапим ефекты
while($eff = mysql_fetch_array($effs)) {
mysql_query("INSERT `deztow_eff` (`type`, `name`, `time`, `sila`, `lovk`, `inta`, `vinos`, `owner`)
values ('".$eff[1]."','".$eff[2]."','".$eff[3]."','".$eff[4]."','".$eff[5]."','".$eff[6]."','".$eff[7]."','".$eff[8]."');");
//deltravma($eff['id']);
}
mysql_query("DELETE FROM `effects` WHERE `owner` = '".$row[0]."';");
// stats
$tec = mysql_fetch_array(mysql_query("SELECT * FROM `deztow_charstams` WHERE `owner` = '{$row[0]}' AND `def`='1';"));
if($tec[0] && $row[0] != 233) {
// умелки
$u = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '{$row[0]}' LIMIT 1;"));
$master = ($u['noj']+$u['mec']+$u['topor']+$u['dubina']+$u['mfire']+$u['mwater']+$u['mair']+$u['mearth']+$u['mlight']+$u['mgray']+$u['mdark']+$u['master']);
// если есть шаблон - меняем
mysql_query("INSERT `deztow_realchars` (`owner`,`name`,`sila`,`lovk`,`inta`,`vinos`,`intel`,`mudra`,`stats`,`nextup`,`level`,`master`) values
('".$u['id']."','".$u['login']."','".$u['sila']."','".$u['lovk']."','".$u['inta']."','".$u['vinos']."','".$u['intel']."',
'".$u['mudra']."','".$u['stats']."','".$u['nextup']."','".$u['level']."','".$master."');");
//создали запись, теперь выставляем статы))
$stats = ($u['sila']+$u['lovk']+$u['inta']+$u['vinos']+$u['intel']+$u['mudra']+$u['stats'])-
($t['sila']+$t['lovk']+$t['inta']+$t['vinos']+$t['intel']+$t['mudra']);
if ((int)$stats!=0) {
$fffff=fopen('/tmp/bs_s.dat','a');
// $tec['sila']=$u['sila']; $tec['lovk']=$u['lovk']; $tec['$inta']=$u['inta'];
// $tec['vinos']=$u['vinos']; $tec['intel']=$u['intel']; $tec['mudra']=$u['mudra'];
fwrite($fffff,print_r($u)."\n");
fwrite($fffff,print_r($tec)."\n");
fwrite($fffff,(int)$stats."\n");
fwrite($fffff,"\n\n\n");
fclose($fffff);
} //".$stats."
mysql_query("UPDATE `users` SET `sila`='".$tec['sila']."', `lovk`='".$tec['lovk']."',`inta`='".$tec['inta']."',`vinos`='".$tec['vinos']."',`intel`='".$tec['intel']."',`mudra`='".$tec['mudra']."',`stats`='0',
`noj`=0,`mec`=0,`topor`=0,`dubina`=0,`mfire`=0,`mwater`=0,`mair`=0,`mearth`=0,`mlight`=0,`mgray`=0,`mdark`=0,`master`='".$master."',`maxhp`='".($tec['vinos']*6)."',`hp`='".($tec['vinos']*6)."'
WHERE `id` = '".$u['id']."' LIMIT 1;");
// закончили
}
// пихаем учасников в БС
$rum = rand($minroom,$maxroom);
$urs[$row[0]] = $rum;
//mysql_query("UPDATE `users` SET `in_tower` = 1, `room` = '".$rum."' WHERE `id` = '".$row[0]."';");
//mysql_query("UPDATE `online` SET `room` = '".$rum."' WHERE `id` = '".$row[0]."' LIMIT 1 ;");
// в список участников
$i++;
if($i>1) { $lors .= ", "; }
$lors .= nick3($row[0]);
}
// arch================
undressall(233);
mysql_query("DELETE FROM `inventory` WHERE `owner` = '233';");
$rum = rand($minroom,$maxroom);
mysql_query("UPDATE `users` SET `in_tower` = 1, `chattime` = '999999999999', `room` = '".$rum."' WHERE `id` = '233';");
mysql_query("UPDATE `online` SET `room` = '".$rum."' WHERE `id` = '233' LIMIT 1 ;");
$i++;
$lors .= ", ".nick3(233);
//=====================
// разбрасываем шмот по комнатам
mysql_query("TRUNCATE TABLE `deztow_items`;");
// айдишники магазинных прототипов
$shmots = array("1","1","92","92","93","93","19","19","20","20","20","23","23","24","14","87","87","6","6",
"17","17","17","17","11","11","12","12","12","28","28","43","43","36","36","36","37","37","37",
"38","38","38","50","50","57","52","52","51","51","48","48","47","47","49","49","59","59","60",
"60","61","61","63","64","64","65","65","66","66","68","68","69","69","72","72","4","5","79","79",
"80","76","75","75","94","94","95","95","82","91","91","34","34","86","86","86","9","9","101","101",
"101","101","101","97","97","97","97","100","100","100","100","171","171","171","171",
"103","103","103","104","105","105","106","106","107","107","108","108","109",
"110","111","112","112","113","113","119","364","284","284","284","284","284","285","285","285","285","286","286","286","286"
);
while($sh = array_shift($shmots)) {
$shopid = mysql_fetch_array(mysql_query("SELECT * FROM `shop` WHERE `id` = '".$sh."' LIMIT 1;"));
mysql_query("INSERT `deztow_items` (`iteam_id`, `name`, `img`, `room`) values ('".$shopid['id']."', '".$shopid['name']."', '".$shopid['img']."', '".rand($minroom,$maxroom)."');");
}
// формируем лог
$log = '<span class=date>'.date("d.m.y H:i").'</span> Начало турнира. Участники: '.$lors.'<BR>';
// создаем запись о турнире
mysql_query("INSERT `deztow_turnir` (`type`,`winner`,`coin`,`start_time`,`log`,`endtime`,`active`) values ('".rand(1,7)."','','".$stavka[0]."','".time()."','".$log."','0','1');");
//mysql_query("UNLOCK TABLES;");
foreach($urs as $row=>$rum) {
mysql_query("UPDATE `users` SET `in_tower` = 1, `room` = '".$rum."' WHERE `id` = '".$row."';");
mysql_query("UPDATE `online` SET `room` = '".$rum."' WHERE `id` = '".$row."' LIMIT 1 ;");
}
}
// bots razmen
//====================================================================================
/*function nick5 ($id,$st) {
$bots = mysql_fetch_array(mysql_query ('SELECT * FROM `bots` WHERE `id` = '.$id.' LIMIT 1;'));
$id=$bots['prototype'];
$user = mysql_fetch_array(mysql_query("SELECT * FROM `users` WHERE `id` = '{$id}' LIMIT 1;"));
$user['login'] = $bots['name'];
$user['hp'] = $bots['hp'];
$user['id'] = $bots['id'];
if($user[0]) {
return "<span class={$st}>".$user['login']."</span>";
}
}
*/
class botbattle {
public $log = ""; // агреггатор лога
function botbattle () {
global $mysql;
$this->mysql = $mysql;
}
function get_wep_type($idwep) {
if ($idwep == 0) {
return "kulak";
}
$wep = mysql_fetch_array(mysql_query('SELECT `name` FROM `inventory` WHERE `id` = '.$idwep.' LIMIT 1;'));
//print_r($wep);
if(preg_match("/кастет/i",$wep[0]) || preg_match("/нож/i",$wep[0]) || preg_match("/кинжал/i",$wep[0])) {
return "noj";
}
elseif(preg_match("/дубина/i",$wep[0]) || preg_match("/молот/i",$wep[0]) || preg_match("/ледяной/i",$wep[0]) || preg_match("/клевец/i",$wep[0])) {
return "dubina";
}
elseif(preg_match("/топор/i",$wep[0]) OR preg_match("/секира/i",$wep[0]) || preg_match("/аллебарда/i",$wep[0])) {
return "topor";
}
elseif(preg_match("/Меч/i",$wep[0])) {
return "mech";
}
}
function razmen_log($type,$kuda,$chem,$uron,$kto,$c1,$pokomy,$c2,$hp,$maxhp) {
//print_R(func_get_args());
if ($this->enemyhar['sex'] && $kto == $this->enemyhar['id']) { $sex1 = false; }
if (!$this->enemyhar['sex'] && $kto == $this->enemyhar['id']) { $sex1 = true; }
if ($this->enemyhar['sex'] && $pokomy == $this->enemyhar['id']) { $sex2 = false; }
if (!$this->enemyhar['sex'] && $pokomy == $this->enemyhar['id']) { $sex2 = true; }
if ($this->user['sex'] && $kto == $this->user['id']) { $sex1 = false; }
if (!$this->user['sex'] && $kto == $this->user['id']) { $sex1 = true; }
if ($this->user['sex'] && $pokomy == $this->user['id']) { $sex2 = false; }
if (!$this->user['sex'] && $pokomy == $this->user['id']) { $sex2 = true; }
if($hp < 0) { $hp = 0; }
// текст по промазыванию
if (!$sex1) {
$textfail = array ( 'думал о <вырезано цензурой>, вследствие чего',
'пытался нанести удар, но ',
'поскользнулся, и',
'старался провести удар, но',
'закашлялся, и',
'пытался провести удар, но безумный',
'потерял самоконтроль, вследствие чего',
'думал не о том и');
} else {
$textfail = array ( 'думала о <вырезано цензурой>, вследствие чего',
'пыталась нанести удар, но ',
'поскользнулась, и',
'старалась провести удар, но',
'закашлялась, и',
'пыталась провести удар, но ',
'потеряла самоконтроль, вследствие чего',
'думала не о том и');
}
// чем били
$textchem = array (
"kulak" => array("грудью","ребром руки","лбом","кулаком","ногой","левой ногой","правой ногой","коленом"),
"noj" => array("ножем","тыльной стороной лезвия ножа","рукоятью ножа","лезвием ножа"),
"dubina" => array("сучковатой палкой","поленом","тяжелой дубиной","дубиной","рукоятью молота"),
"topor" => array("секирой","топором","лезвием секиры","аллебардой","тяжелым держаком","длинной секирой"),
"mech" => array("ножнами","гардой","мечем","лезвием меча","рукоятью меча","тупым лезвием","острой стороной меча","огромным мечем",)
);
$textchem = $textchem[$chem];
// куда били
$udars = array(
'1' => array ('в нос','в глаз','в челюсть','по переносице','в кадык','по затылку','в правый глаз','в левый глаз','в скулу'),
'2' => array ('в грудь','в корпус','в солнечное сплетение','в сердце','в бок','в область лопаток','по желудку','по левой руке','по правой руке'),
'3' => array ('по <вырезано цензурой>','в пах','в промежность','по левой ягодице','по правой ягодице'),
'4' => array ('по ногам','в область правой пятки','в область левой пятки','по коленной чашечке','по икрам')
);
$kuda = $udars[$kuda][rand(0,count($udars[$kuda])-1)];
//тест по попаданию
if (!$sex2) {
$textud = array ('забылся, и тут',
'замешкался, и за это бесчувственный',
'растерялся, как вдруг расстроенный',
'ковырялся в зубах, и тут',
'поперхнулся, но вдруг храбрый',
'пытался что-то сказать но вдруг, неожиданно',
'растерялся, как вдруг',
'засмотрелся на <вырезано цензурой>, а в это время',
'высморкался, и в это время',
'думал не о том и',
'пришел в себя, но в это время обезумевший',
'обернулся, как внезапно');
} else {
$textud = array ('забылась, и тут',
'замешкалась, и за это ',
'растерялась, как вдруг ',
'ковырялась в зубах, и тут ',
'поперхнулась, но вдруг ',
'пыталась что-то сказать но вдруг, неожиданно',
'растерялась, как вдруг',
'засмотрелась на <вырезано цензурой>, а в это время',
'высморкалась, и в это время',
'думала не о том и',
'пришла в себя, но в это время ',
'обернулась, как внезапно');
}
switch ($type) {
// уворот
case "uvorot":
if ($sex2) {
$textuvorot = array (" уклонилась от удара "," увернулась от удара "," отскочила от удара ");
}
else {
$textuvorot = array (" уклонился от удара "," увернулся от удара "," отскочил от удара ");
}
return '<span class=date>'.date("H:i").'</span> '.nick5($kto,$c1).' '.$textfail[rand(0,count($textfail)-1)].' '.nick5($pokomy,$c2).' '.$textuvorot[rand(0,count($textuvorot)-1)].' '.$textchem[rand(0,count($textchem)-1)].' '.$kuda.'.<BR>';
break;
//блок
case "block":
if ($sex2) {
$textblock = array (" заблокировала удар "," остановила удар "," отбила удар ");
}
else {
$textblock = array (" заблокировал удар "," остановил удар "," отбил удар ");
}
return '<span class=date>'.date("H:i").'</span> '.nick5($kto,$c1).' '.$textfail[rand(0,count($textfail)-1)].' '.nick5($pokomy,$c2).' '.$textblock[rand(0,count($textblock)-1)].' '.$textchem[rand(0,count($textchem)-1)].' '.$kuda.'.<BR>';
break;
//крит
case "krit":
if ($sex1) {
$textkrit = array (", напугав всех, неслышно подойдя сзади ударила по голове булыжником оппонента.",", сказав \"БУ!\", ласково заломила руку за спину соперника.",", расслабившись, расцарапала нос соперника.",", показав сразу два пальца, наступила на ногу врага.",", напугав всех, укусила в нос противника.",", проклиная этот сайт, провела ужасный бросок через пупок оппонента.");
}
else {
$textkrit = array (", напугав всех, неслышно подойдя сзади ударил по голове булыжником оппонента.",", сказав \"БУ!\", ласково заломил руку за спину соперника.",", расслабившись, расцарапал нос соперника.",", показав сразу два пальца, наступил на ногу врага.",", напугав всех, укусил в нос противника.",", проклиная этот сайт, провел ужасный бросок через пупок оппонента.");
}
return '<span class=date>'.date("H:i").'</span> '.nick5($pokomy,$c2).' '.$textud[rand(0,count($textud)-1)].' '.nick5($kto,$c1).' '.$textkrit[rand(0,count($textkrit)-1)].' <b><font color=red>-'.$uron.'</font></b> ['.$hp.'/'.$maxhp.']'.'<BR>';
break;
// попадание
case "udar":
if ($sex1) {
$textudar = array(", разбежавшись, рубанула"," отчаянно проткнула "," нехотя уколола "," не подумав, рубанула ",", улыбаясь, саданула укол "," приложила удар "," ударила "," сдуру вмазала ");
}
else {
$textudar = array(", разбежавшись, рубанул"," отчаянно проткнул "," нехотя уколол "," не подумав, рубанул ",", улыбаясь, саданул укол "," приложил удар "," ударил "," сдуру вмазал ");
}
return '<span class=date>'.date("H:i").'</span> '.nick5($pokomy,$c2).' '.$textud[rand(0,count($textud)-1)].' '.nick5($kto,$c1).''.$textudar[rand(0,count($textudar)-1)].' '.$textchem[rand(0,count($textchem)-1)].' '.$kuda.' <b>-'.$uron.'</b> ['.$hp.'/'.$maxhp.']'.'<BR>';
break;
}
}
function update_battle () {
return mysql_query('UPDATE `battle` SET `teams` = \''.serialize($this->battle).'\', `damage` = \''.serialize($this->damage).'\' WHERE `id` = '.$this->battle_data['id'].' ;');
}
function add_log ($text) {
$this->log .= $text;
}
function write_log () {
if($this->log){$this->log=$this->log."<hr>";}
addlog($this->user['battle'],$this->log);
/*$fp = fopen("/tmp/backup/logs/battle".$this->battle_data['id'].".txt","a"); //открытие
flock($fp,LOCK_EX); //БЛОКИРОВКА ФАЙЛА
fputs($fp , $this->log); //работа с файлом
fflush($fp); //ОЧИЩЕНИЕ ФАЙЛОВОГО БУФЕРА И ЗАПИСЬ В ФАЙЛ
flock($fp,LOCK_UN); //СНЯТИЕ БЛОКИРОВКИ
fclose($fp); //закрытие
$this->log = '';*/
}
function solve_mf($enemy,$enemy2,$en1att,$en2att) {
$mf = array ();
$bots = mysql_fetch_array(mysql_query ('SELECT * FROM `bots` WHERE `id` = '.$enemy2.' LIMIT 1;'));
$this->enemyhar = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = \''.$bots['prototype'].'\' LIMIT 1;'));
$this->enemy_dress = mysql_fetch_array(mysql_query('SELECT sum(minu),sum(maxu),sum(mfkrit),sum(mfakrit),sum(mfuvorot),sum(mfauvorot),sum(bron1),sum(bron2),sum(bron3),sum(bron4) FROM `inventory` WHERE `dressed`=1 AND `owner` = \''.$bots['prototype'].'\' LIMIT 1;'));
$this->enemyhar['hp'] = $bots['hp'];
$bots = mysql_fetch_array(mysql_query ('SELECT * FROM `bots` WHERE `id` = '.$enemy.' LIMIT 1;'));
$this->user = mysql_fetch_array(mysql_query('SELECT * FROM `users` WHERE `id` = \''.$bots['prototype'].'\' LIMIT 1;'));
$this->user_dress = mysql_fetch_array(mysql_query('SELECT sum(minu),sum(maxu),sum(mfkrit),sum(mfakrit),sum(mfuvorot),sum(mfauvorot),sum(bron1),sum(bron2),sum(bron3),sum(bron4) FROM `inventory` WHERE `dressed`=1 AND `owner` = \''.$bots['prototype'].'\' LIMIT 1;'));
$this->user['hp'] = $bots['hp'];
// мои МФ в отношении противника
$mf['me'] = array (
'udar' => rand(floor($this->user['sila']/3)+2+$this->user_dress[0],floor($this->user['sila']/3)+4+$this->user_dress[1])-rand(1,$this->enemy_dress[5+$en1att]),
'krit' => $this->user_dress[2]-$this->enemy_dress[3]+floor($this->user['inta']*4)-floor($this->enemyhar['inta']*4),
'uvorot' => $this->user_dress[4]-$this->enemy_dress[5]+floor($this->user['lovk']*4)-floor($this->enemyhar['lovk']*4),
);
if($this->get_wep_type($this->user['weap']) == 'kulak' && $this->user['align'] == '2') { $mf['me']['udar'] += $this->user['level']; }
//бонусы от умений к урону
switch($this->get_wep_type($this->user['weap'])) {
case "noj":
$mf['me']['udar'] += $this->user['noj'];
break;
case "dubina":
$mf['me']['udar'] += $this->user['dubina'];
break;
case "topor":
$mf['me']['udar'] += $this->user['topor'];
break;
case "mech":
$mf['me']['udar'] += $this->user['mec'];
break;
}
if($bmfud>5) $mf['me']['udar']+=$bmfud;
if($mf['me']['udar'] < 0) { $mf['me']['udar'] = 0; }
if($bmfud<=5) $mf['me']['udar']+=$bmfud;
if($mf['me']['krit'] < 1)
{ $mf['me']['krit'] = 1; }
elseif (($mf['me']['krit'] >= 50)&&($mf['me']['krit']<100))
{ $mf['me']['krit'] = 50; }
elseif (($mf['me']['krit'] >= 100)&&($mf['me']['krit']<200))
{ $mf['me']['krit'] = 55; }
elseif (($mf['me']['krit'] >= 200)&&($mf['me']['krit']<300))
{ $mf['me']['krit'] = 60; }
elseif (($mf['me']['krit'] >= 300)&&($mf['me']['krit']<400))
{ $mf['me']['krit'] = 65; }
elseif (($mf['me']['krit'] >= 400)&&($mf['me']['krit']<500))
{ $mf['me']['krit'] = 70; }
elseif ($mf['me']['krit'] >= 500)
{ $mf['me']['krit'] = 75; }
if($mf['me']['uvorot'] < 1)
{ $mf['me']['uvorot'] = 1; }
elseif (($mf['me']['uvorot'] >= 50)&&($mf['me']['uvorot']<100))
{ $mf['me']['uvorot'] = 50; }
elseif (($mf['me']['uvorot'] >= 100)&&($mf['me']['uvorot']<200))
{ $mf['me']['uvorot'] = 55; }
elseif (($mf['me']['uvorot'] >= 200)&&($mf['me']['uvorot']<300))
{ $mf['me']['uvorot'] = 60; }
elseif (($mf['me']['uvorot'] >= 300)&&($mf['me']['uvorot']<400))
{ $mf['me']['uvorot'] = 65; }
elseif (($mf['me']['uvorot'] >= 400)&&($mf['me']['uvorot']<500))
{ $mf['me']['uvorot'] = 70; }
elseif ($mf['me']['uvorot'] >= 500)
{ $mf['me']['uvorot'] = 75; }
switch($this->get_wep_type($this->user['weap'])) {
case "noj":
$ver=$this->user['noj'];
break;
case "dubina":
$ver=$this->user['dubina'];
break;
case "topor":
$ver=$this->user['topor'];
break;
case "mech":
$ver=$this->user['mech'];
break;
}
if(mt_rand(0,100)<$ver)
switch($this->get_wep_type($this->user['weap'])) {
case "noj":
$mf['me']['udar']+=(($this->user['lovk']+$this->user['inta'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "dubina":
$mf['me']['udar']+=(($this->user['sila']+$this->user['vinos'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "topor":
$mf['me']['udar']+=(($this->user['inta']+$this->user['vinos'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "mech":
$mf['me']['udar']+=(($this->user['lovk']+$this->user['sila'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
}
//округляем урон
$mf['me']['udar']=round($mf['me']['udar']);
// МФ врага в отношении меня
$mf['he'] = array (
'udar' => rand(floor($this->enemyhar['sila']/3)+2+$this->enemy_dress[0],floor($this->enemyhar['sila']/3)+4+$this->enemy_dress[1])-rand(1,$this->user_dress[5+$en2att]),
'krit' => $this->enemy_dress[2]-$this->user_dress[3]+floor($this->enemyhar['inta']*4)-floor($this->user['inta']*4),
'uvorot' => $this->enemy_dress[4]-$this->user_dress[5]+floor($this->enemyhar['lovk']*4)-floor($this->user['lovk']*4),
);
if($this->get_wep_type($this->enemyhar['weap']) == 'kulak' && $this->enemyhar['align'] == '2') { $mf['he']['udar'] += $this->enemyhar['level']; }
switch($this->get_wep_type($this->enemyhar['weap'])) {
case "noj":
$mf['he']['udar'] += $this->enemyhar['noj'];
break;
case "dubina":
$mf['he']['udar'] += $this->enemyhar['dubina'];
break;
case "topor":
$mf['he']['udar'] += $this->enemyhar['topor'];
break;
case "mech":
$mf['he']['udar'] += $this->enemyhar['mec'];
break;
}
if($bmfud1<5) $mf['he']['udar']+=$bmfud1;
if($mf['he']['udar'] < 0) { $mf['he']['udar'] = 0; }
if($bmfud1>=5) $mf['he']['udar']+=$bmfud1;
//if($mf['he']['krit'] < 1) { $mf['he']['krit'] = 1; } elseif ($mf['he']['krit'] > 50) { $mf['he']['krit'] = 50; }
//if($mf['he']['uvorot'] < 1) { $mf['he']['uvorot'] = 1; } elseif ($mf['he']['uvorot'] > 65) { $mf['he']['uvorot'] = 65; }
if($mf['he']['krit'] < 1)
{ $mf['he']['krit'] = 1; }
elseif (($mf['he']['krit'] >= 50)&&($mf['he']['krit']<100))
{ $mf['he']['krit'] = 50; }
elseif (($mf['he']['krit'] >= 100)&&($mf['he']['krit']<200))
{ $mf['he']['krit'] = 55; }
elseif (($mf['he']['krit'] >= 200)&&($mf['he']['krit']<300))
{ $mf['he']['krit'] = 60; }
elseif (($mf['he']['krit'] >= 300)&&($mf['he']['krit']<400))
{ $mf['he']['krit'] = 65; }
elseif (($mf['he']['krit'] >= 400)&&($mf['he']['krit']<500))
{ $mf['he']['krit'] = 70; }
elseif ($mf['he']['krit'] >= 500)
{ $mf['he']['krit'] = 75; }
if($mf['he']['uvorot'] < 1)
{ $mf['he']['uvorot'] = 1; }
elseif (($mf['he']['uvorot'] >= 50)&&($mf['he']['uvorot']<100))
{ $mf['he']['uvorot'] = 50; }
elseif (($mf['he']['uvorot'] >= 100)&&($mf['he']['uvorot']<200))
{ $mf['he']['uvorot'] = 55; }
elseif (($mf['he']['uvorot'] >= 200)&&($mf['he']['uvorot']<300))
{ $mf['he']['uvorot'] = 60; }
elseif (($mf['he']['uvorot'] >= 300)&&($mf['he']['uvorot']<400))
{ $mf['he']['uvorot'] = 65; }
elseif (($mf['he']['uvorot'] >= 400)&&($mf['he']['uvorot']<500))
{ $mf['he']['uvorot'] = 70; }
elseif ($mf['he']['uvorot'] >= 500)
{ $mf['he']['uvorot'] = 75; }
//проф урон
switch($this->get_wep_type($this->user['weap'])) {
case "noj":
$ver=$this->user['noj'];
break;
case "dubina":
$ver=$this->user['dubina'];
break;
case "topor":
$ver=$this->user['topor'];
break;
case "mech":
$ver=$this->user['mech'];
break;
}
if(mt_rand(0,100)<$ver)
switch($this->get_wep_type($this->user['weap'])) {
case "noj":
$mf['he']['udar']+=(($this->user['lovk']+$this->user['inta'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "dubina":
$mf['he']['udar']+=(($this->user['sila']+$this->user['vinos'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "topor":
$mf['he']['udar']+=(($this->user['inta']+$this->user['vinos'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
case "mech":
$mf['he']['udar']+=(($this->user['lovk']+$this->user['sila'])*$this->user['level']*mt_rand(5,15)/(2*10*10));
break;
}
//if(in_array($enemy,$this->botsid)) { $mf['he']['udar'] += $this->user_dress[1]; }
if($enemy > _BOTSEPARATOR_) {
$mf['he']['krit'] -= 6;
}
//округляем урон
$mf['he']['udar']=round($mf['he']['udar']);
//if(in_array($enemy,$this->botsid)) { $mf['he']['udar'] += $this->user_dress[1]; }
// result
return $mf;
}
function get_chanse ($persent) {
if (rand(1,100) < $persent) {
return true;
}
else {
return false;
}
}
function get_block ($att,$def) {
// по типам блоков
$blocks = array (
'1' => array (1,2),
'2' => array (2,3),
'3' => array (3,4),
'4' => array (4,1)
);
if (!in_array($att,$blocks[$def])) {
return true;
} else {
return false;
}
}
function razmen_init ($enemy,$enemy2,$battle_id) {
$bots1 = mysql_fetch_array(mysql_query ('SELECT * FROM `bots` WHERE `id` = '.$enemy.' AND `battle` = '.$battle_id.' AND `hp` > 0 LIMIT 1;'));
$bots2 = mysql_fetch_array(mysql_query ('SELECT * FROM `bots` WHERE `id` = '.$enemy2.' AND `battle` = '.$battle_id.' AND `hp` > 0 LIMIT 1;'));
if($bots1 && $bots2) {
$this->battle_data = mysql_fetch_array(mysql_query ('SELECT * FROM `battle` WHERE `id` = '.$battle_id.' LIMIT 1;'));
// получили дамагу
$this->damage = unserialize($this->battle_data['damage']);
// кто драчуется?
$this->battle = unserialize($this->battle_data['teams']);
// режем тимзы
$this->t1 = explode(";",$this->battle_data['t1']);
$this->t2 = explode(";",$this->battle_data['t2']);
// проставляем кто-где
if (in_array ($enemy,$this->t1)) {
$this->my_class = "B1";
$this->en_class = "B2";
$this->team_mine = $this->t1;
$this->team_enemy = $this->t2;
} else {
$this->my_class = "B2";
$this->en_class = "B1";
$this->team_mine = $this->t2;
$this->team_enemy = $this->t1;
}
// проверяем прафильность
$en1att = mt_rand(1,4);
$en2att = mt_rand(1,4);
$en1b = mt_rand(1,4);
$en2b = mt_rand(1,4);
// х-ки драчующихся
$mf = $this->solve_mf($enemy,$enemy2,$en1att,$en2att);
//echo $this->get_wep_type($this->enemyhar['weap']);
// проверяем кто куда попал
// удар по мне
if ($this->get_chanse($mf['my']['uvorot']))
{
// я увернулся;
$this->add_log ($this->razmen_log("uvorot",$en2att,$this->get_wep_type($this->enemyhar['weap']),0,$enemy2,$this->en_class,$enemy,$this->my_class,0,0));
}
elseif($this->get_chanse($mf['he']['krit'])) {
// меня кританули
$this->damage[$enemy2] += ($mf['he']['udar']*2);
$this->add_log ($this->razmen_log("krit",$en2att,$this->get_wep_type($this->enemyhar['weap']),($mf['he']['udar']*2),$enemy2,$this->en_class,$enemy,$this->my_class,($this->user['hp']-$mf['he']['udar']*2),$this->user['maxhp']));
mysql_query('UPDATE bots SET `hp` = `hp` - '.($mf['he']['udar']*2).' WHERE `id` = '.$enemy.'');
}
elseif($this->get_block ($en2att,$en1b)) {
// противник попал куда надо
$this->damage[$enemy2] += ($mf['he']['udar']);
$this->add_log ($this->razmen_log("udar",$en2att,$this->get_wep_type($this->enemyhar['weap']),$mf['he']['udar'],$enemy2,$this->en_class,$enemy,$this->my_class,($this->user['hp']-$mf['he']['udar']),$this->user['maxhp']));
mysql_query('UPDATE bots SET `hp` = `hp` - '.($mf['he']['udar']).' WHERE `id` = '.$enemy.'');
}
else {
// противник мазила
$this->add_log ($this->razmen_log("block",$en2att,$this->get_wep_type($this->enemyhar['weap']),0,$enemy2,$this->en_class,$enemy,$this->my_class,0,0));
}
// удар по противнику
if ($this->get_chanse($mf['he']['uvorot']))
{
// он увернулся;
$this->add_log ($this->razmen_log("uvorot",$en1att,$this->get_wep_type($this->user['weap']),0,$enemy,$this->my_class,$enemy2,$this->en_class,0,0));
}
elseif($this->get_chanse($mf['my']['krit'])) {
// его кританули
$this->damage[$enemy] += ($mf['me']['udar']*2);
$this->add_log ($this->razmen_log("krit",$en1att,$this->get_wep_type($this->user['weap']),($mf['me']['udar']*2),$enemy,$this->my_class,$enemy2,$this->en_class,($this->enemyhar['hp']-$mf['me']['udar']*2),$this->enemyhar['maxhp']));
mysql_query('UPDATE `bots` SET `hp` = `hp` - '.($mf['me']['udar']*2).' WHERE `id` = '.$enemy2.'');
}
elseif($this->get_block ($en1att,$en2b)) {
// я попал куда надо
$this->damage[$enemy] += ($mf['me']['udar']);
$this->add_log ($this->razmen_log("udar",$en1att,$this->get_wep_type($this->user['weap']),$mf['me']['udar'],$enemy,$this->my_class,$enemy2,$this->en_class,($this->enemyhar['hp']-$mf['me']['udar']),$this->enemyhar['maxhp']));
mysql_query('UPDATE `bots` SET `hp` = `hp` - '.($mf['me']['udar']).' WHERE `id` = '.$enemy2.'');
}
else {
// я мазила
$this->add_log ($this->razmen_log("block",$attack,$this->get_wep_type($this->user['weap']),0,$enemy,$this->my_class,$enemy2,$this->en_class,0,0));
}
$this->write_log();
$this->update_battle ();
mysql_query("UPDATE `battle` SET `to1` = '".time()."', `to2` = '".(time())."' WHERE `id` = ".$this->battle_data['id']." LIMIT 1;");
}
}
}
$bots = mysql_query ('SELECT * FROM `bots` WHERE `hp` > 0;');
$bb = new botbattle;
while ($bot = mysql_fetch_array($bots)) {
$bd = mysql_fetch_array(mysql_query ('SELECT * FROM `battle` WHERE `id` = '.$bot['battle'].' LIMIT 1;'));
$battle = unserialize($bd['teams']);
// листаем противников, делаем размен.
if ($battle[$bot['id']]) {
foreach ($battle[$bot['id']] as $k => $v) {
if($battle[$bot['id']][$k][0] == 0 && $k > _BOTSEPARATOR_) {
//echo("Bots:".$bot['id']."vs".$k."<BR/>");
//srand(microtime(true));
$bb->razmen_init($bot['id'],$k,$bot['battle']);
}
}
}
//mysql_query('UPDATE `battle` SET `teams` = \''.serialize($battle).'\' WHERE `id` = '.$bot['battle'].' ;');
}
//====================================================================================
/*
$mtime = microtime();
$mtime = explode(" ",$mtime);
$mtime = $mtime[1] + $mtime[0];
//Записываем время окончания в другую переменную
$tend = $mtime;
//Вычисляем разницу
$totaltime = ($tend - $tstart);
//Выводим не экран
printf ("PGT: %f секунд", $totaltime); */
?>