View file mafia/maf.php

File size: 103.14Kb
<?

function getmicrotime()   //микровремя

{ 

    list($usec, $sec) = explode(" ", microtime()); 

    return ((float)$usec + (float)$sec); 

}
$title='Mafia'; 
require"../system/config.php";
 require"../system/func.php";
 require"../system/head.php";
 require"../system/error.php";
echo"<div class=\"i\">$title
</div>";


$ref=rand(10000,1000000);

        $result = mysql_query ("Select * from mafusers where id_user='$user[id_user]'");    
		$row = mysql_fetch_array ($result);
		$id = (int)$row["id_user"];
		$us=htmlspecialchars($row["name"]);
		if(!empty($_POST['msg'])) $msg=mysql_real_escape_string($_POST['msg']);
		if ($row['translit']==1) $msg=translit($msg);
		if(!empty($_POST['prvt'])) $prvt=(int)$_POST['prvt'];
		if(!empty($_GET['uid'])) {$towhom=(int)$_GET['uid'];}
		$avr=$row['avr'];
		if ($avr>0){echo "<META HTTP-EQUIV='Refresh' CONTENT='$avr'; URL='".$_SERVER['PHP_SELF']."'>";}

						if (!empty($_GET['rm'])){ $rm = (int)htmlspecialchars($_GET['rm']);} 
							$rmaf = "maf".$rm;
							$rmafaction = "mafaction".$rm;
							$rscores = "scores".$rm;
							$ringame = "ingame".$rm;
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////							
function role_to_tpadej($role)
	{
	switch ($role)
    {
    case "обыватель" : $trole = "обывателем";break; 
    case "комиссар катани" : $trole = "инспектором катани";break;
    case "главарь мафии" : $trole = "главарем мафии";break;
    case "доктор" : $trole = "доктором";break;
    case "маньяк" : $trole = "маньяком";break;
    case "путана" : $trole = "путаной";break;
    case "бомж" : $trole = "бомжом";break; 
    case "мафиози" : $trole = "мафиози";break; 
    case "горец" : $trole = "горцем";break;
    case "жена комиссара" : $trole = "женой комиссара";break;
    case "клоун" : $trole = "клоуном";break;
    default : $trole = $role; break;
    }
		return ($trole);
	}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
    function role_to_rpadej($role)
		{
		switch ($role)
		{
		case "обыватель" : $rrole = "обывателя";break; 
		case "комиссар катани" : $rrole = "комиссара катани";break;
        case "главарь мафии" : $rrole = "главаря мафии";break;
        case "доктор" : $rrole = "доктора";break;
        case "маньяк" : $rrole = "маньяка";break;
		case "путана" : $rrole = "путану";break;
        case "бомж" : $rrole = "бомжа";break;
		case "мафиози" : $rrole = "мафиози";break;  
		case "горец" : $rrole = "горца";break;
        case "жена комиссара" : $rrole = "жены комиссара";break;
		case "клоун" : $rrole = "клоуна";break;
		default: $rrole = $role; break;
        }
			return($rrole);
		}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////		
        function get_name_by_id($id_in_game, $rm)
			{ 
            $ringame = "ingame".$rm;
            $req = mysql_query("select * from $ringame WHERE id_in_game = '".$id_in_game."'");
            $ms = mysql_fetch_array($req);
            $gamer_id = $ms["gamer_id"];
            $req = mysql_query("select * from mafusers WHERE id = '".$gamer_id."'");
            $ms = mysql_fetch_array($req);
            $name = $ms["user"];
				unset($gamer_id);
					unset($ms);
						unset($req);
							return($name);
            }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
			function get_role_by_id($id_in_game, $rm)
				{ 
                $ringame = "ingame".$rm;
                $req = mysql_query("select * from $ringame WHERE id_in_game = '".$id_in_game."'");
                $ms = mysql_fetch_array($req);
                $role = $ms["role"];
					unset($ms);
						unset($req);
							return($role);
                }
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////				
				function trun_to_rus($str)
					{
					$str=str_replace("ch","С‡",$str);
					$str=str_replace("sc","С‰",$str); 
					$str=str_replace("ye","СЌ",$str);
					$str=str_replace("yu","СЋ",$str);
					$str=str_replace("ya","СЏ",$str);
					$str=str_replace("CH","Р§",$str);
					$str=str_replace("SC","Р©",$str); 
					$str=str_replace("\"\"","РЄ",$str);
					$str=str_replace("\"","СЉ",$str);
					$str=str_replace("&#8216;&#8216;","Р¬",$str);
					$str=str_replace("&#8216;","СЊ",$str);
					$str=str_replace("YE","Р­",$str);
					$str=str_replace("YU","Р®",$str);
					$str=str_replace("YA","РЇ",$str);
					$str=strtr($str,array("a"=>"Р°","b"=>"Р±","v"=>"РІ","g"=>"Рі","d"=>"Рґ","e"=>"Рµ","j"=>"Р¶","z"=>"Р·","i"=>"Рё","y"=>"Р№","k"=>"Рє","l"=>"Р»","m"=>"Рј","n"=>"РЅ","o"=>"Рѕ","p"=>"Рї","r"=>"СЂ","s"=>"СЃ","t"=>"С‚","u"=>"Сѓ","f"=>"С„","h"=>"С…","c"=>"С†","w"=>"С€","x"=>"С‹","A"=>"Рђ","B"=>"Р‘","V"=>"Р’","G"=>"Р“","D"=>"Р”","E"=>"Р•","J"=>"Р–","Z"=>"Р—","I"=>"Р?","Y"=>"Р™","K"=>"Рљ","L"=>"Р›","M"=>"Рњ","N"=>"Рќ","O"=>"Рћ","P"=>"Рџ","R"=>"Р ","S"=>"РЎ","T"=>"Рў","U"=>"РЈ","F"=>"Р¤","H"=>"РҐ","C"=>"Р¦","W"=>"РЁ","X"=>"Р«"));
					return $str;
					} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////					
					function scores($rm)
						{ 
						$rscores = "scores".$rm;
						$r = mysql_query("select * from $rscores"); 
						$mmes = "";
						while (($a = mysql_fetch_array($r))!==false)
							{
							$gamer_id = $a["gamer_id"];
							$score = $a["score"];
							mysql_query("update mafusers set credits = credits + creditsingame WHERE id = '".$gamer_id."'");  //начисляем очки
							$re = mysql_query("select user from mafusers WHERE id = '".$gamer_id."'");
							$b = mysql_fetch_array($re);
							$mmes = $mmes.$b["user"]." - <b>$score</b>, ";
							}                                             
							$mmes = substr($mmes,0,strlen($mmes)-2);
								return($mmes);
	
						}                     
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Автоматическая оптимизация и чистка
$r = mysql_query ("SELECT * FROM optim");
$a = mysql_fetch_array ($r);
	if ($a["go"]<time())
		{
		$i = time() + 1800; //Время следующей чистки - через полчаса
		mysql_query ("Update optim set go='".$i."' WHERE klu4 = '1'"); 
		$i = time() - 3600;
			for ($num = 1; $num <= 3; $num++)
				{
				$roptim = "maf".$num;  
				mysql_query("delete from $roptim WHERE id<'".$i."'");
				mysql_query("OPTIMIZE TABLE $roptim");
				} 
		}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Конец чистки
//В игре человек или нет:
mysql_query ("select * from $ringame WHERE gamer_id = '".$id."'");
	if (mysql_affected_rows()!=0) $gmes = 1; else $gmes = 0;  
//Проверка, на связи ли человек:       
$tm = time()-300;
$r = mysql_query ("select * from $ringame WHERE (onl<'".$tm."')");
	if (mysql_affected_rows() != 0)
		{
		$mmsg = "";        
		//mysql_query("LOCK TABLES mafusers, ingame, scores WRITE, maf READ");
			while (($a = mysql_fetch_array($r))!==false)
				{
				$grole = get_role_by_id($a["id_in_game"], $rm);
				$gname = get_name_by_id($a["id_in_game"], $rm);                
				$gid = $a["gamer_id"];
				$mmsg = $mmsg."$grole $gname покидает игру (превышено время ожидания ответа)! ";        
				//Вычитаем очки:   
				mysql_query("update mafusers set creditsingame = creditsingame - 100 WHERE id = '".$gid."'");
				$r = mysql_query("select creditsingame from mafusers WHERE id = '".$gid."'");
				$a = mysql_fetch_array($r);
				$cring = $a["creditsingame"];     
				//Записываем для дальнейшего вывода, кто сколько очков набрал
				mysql_query("insert into $rscores set gamer_id = '".$gid."', score = '".$cring."'"); 
				mysql_query("delete from $ringame WHERE gamer_id = '".$gid."'"); 
				}          
//mysql_query("UNLOCK TABLES");
	$tm = getmicrotime();
	$today=date ("H:i:s");
	$rnd = rand(0,99999999); 
	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");
	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");         
	$vktr = false; 
//mysql_query("LOCK TABLES mafusers, mafaction, ingame, scores WRITE, maf READ");
$r = mysql_query("select count(*) as sm from $ringame");
$a = mysql_fetch_array($r);
$sm = $a["sm"];  //в $sm - число игроков
mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
	if (mysql_affected_rows()==0&&$sm!=0)
		{ //Убит главный маф, и еще есть игроки
		$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
			if (mysql_affected_rows()==0)
				{ //Мафов больше нет, победа мирных жителей  
				$vktr = true;
				//mysql_query ("LOCK TABLES mafaction WRITE, maf, $ringame, mafusers READ");
				mysql_query ("update $rmafaction set action = 'nogame'"); 
				//mysql_query ("UNLOCK TABLES");     
				//Мирным начисляем очки
				$r = mysql_query("select role, gamer_id from $ringame");
					while (($a = mysql_fetch_array($r))!==false)
						{
						$role = $a["role"];
						$gamer_id = $a["gamer_id"];
							if ($role == "обыватель") mysql_query("update mafusers set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
								else mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
						}
//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 100 WHERE (ingame.role = 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим обывателям +100
//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (ingame.role != 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим другим +50
$mmsg = "Р?РіСЂР° окончена, победа мирных жителей! Рђ роли были такие: "; 
$r = mysql_query("Select * from $ringame");
	while (($a = mysql_fetch_array($r))!==false)
		{  //Какие у кого роли
        $gnick = get_name_by_id($a["id_in_game"], $rm);
        $grole = get_role_by_id($a["id_in_game"], $rm);
        $mmsg = $mmsg."<b>$gnick</b> - $grole, ";
        } 
				$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
				mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
				mysql_query ("delete from $ringame");
				//mysql_query("UNLOCK TABLES");
				$tm = getmicrotime();
				$today=date ("H:i:s");
				$rnd = rand(0,99999999); 
				mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
				mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
				$mmsg = "За эту игру заработали столько очков: "; 
				$mmes = scores($rm); 
				$mmsg = $mmsg.$mmes; 
				$tm = getmicrotime();
				$today=date ("H:i:s");
				$rnd = rand(0,99999999); 
				mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
				mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
				}
					else
						{ //Назначение нового главаря мафии
						$a = mysql_fetch_array($r);  
						$id_in_game = $a["id_in_game"];
						$gamer_id = $a["gamer_id"];
						mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
						$mmsg = "Теперь вы главарь мафии!"; 
						//mysql_query("UNLOCK TABLES");
						$tm = getmicrotime();
						$today=date ("H:i:s");
						$rnd = rand(0,99999999); 
						mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1'");            
						mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
						}
		} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Проверка, победили ли Мафы или ничья
	if ($vktr!==true)
		{
		$r = mysql_query ("select count(*) as sm from $ringame");
		$a = mysql_fetch_array($r); 
			if ($a["sm"]==2)
				{
				mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')"); 
					if (mysql_affected_rows()==2) $vk = "maf";
						if (mysql_affected_rows()==1)
							{ //1 маф
							mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
							if (mysql_affected_rows() != 0) $vk = "ni4"; else $vk = "maf";
							}	
				}
					if ($a["sm"]==1)
						{
						mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
							if (mysql_affected_rows() != 0) $vk = "maf";
						}
							if ($a["sm"]==0) $vk = "ni4";
								mysql_query("select * from $ringame");
								$nm = round(mysql_affected_rows()/2-0.5); //Большинство
								$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
								$a = mysql_fetch_array($r);
								$sm = $a["sm"];
									if ($sm>$nm) $vk = "maf";
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (isset($vk))
	{  //Р?РіСЂР° окончена
	$vktr = true;
		if ($vk == "ni4")
			{ //Ничья
			$vktr = true;
			//mysql_query ("LOCK TABLES mafaction WRITE, maf, ingame, mafusers READ");
			mysql_query ("update $rmafaction set action = 'nogame'");
			//mysql_query ("UNLOCK TABLES"); 
			//Начисляем очки выжившим
			$r = mysql_query("select gamer_id from $ringame");
				while (($a = mysql_fetch_array($r))!==false)
					{
					$gamer_id = $a["gamer_id"];
					mysql_query("update mafusers set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
					}
					//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 25 WHERE mafusers.id = ingame.gamer_id"); //выжившим +25
			        $mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
					$r = mysql_query("Select * from $ringame");
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
				while (($a = mysql_fetch_array($r))!==false)
					{  //Какие у кого роли
					$gnick = get_name_by_id($a["id_in_game"], $rm);
					$grole = get_role_by_id($a["id_in_game"], $rm);
					$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
					} 
			$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
			mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
			mysql_query ("delete from $ringame");
			//mysql_query("UNLOCK TABLES");
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
			$mmsg = "За эту игру заработали столько очков: "; 
			$mmes = scores($rm); 
			$mmsg = $mmsg.$mmes;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if ($vk == "maf")
	{ 
    //mysql_query ("LOCK TABLES mafaction WRITE, maf, ingame, mafusers READ");
    $vktr = true;
    mysql_query ("update $rmafaction set action = 'nogame'"); 
    //mysql_query ("UNLOCK TABLES"); 
    //Начисляем очки мафам 
    $r = mysql_query("select role, gamer_id from $ringame");
		while (($a = mysql_fetch_array($r))!==false)
			{
			$role = $a["role"];
			$gamer_id = $a["gamer_id"];
				if ($role == "мафиози"||$role == "главарь мафии") mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
			}
			//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (mafusers.id = ingame.gamer_id)and((ingame.role='мафиози')or(ingame.role='главарь мафии'))"); //Мафам +25
			$mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
			$r = mysql_query("Select * from $ringame");
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
			while (($a = mysql_fetch_array($r))!==false)
				{  //Какие у кого роли
				$gnick = get_name_by_id($a["id_in_game"], $rm);
				$grole = get_role_by_id($a["id_in_game"], $rm);
				$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
				} 
	$mmsg = substr($mmsg,0,strlen($mmsg)-2);
	mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
	mysql_query ("delete from $ringame");
	//mysql_query("UNLOCK TABLES");
	$tm = getmicrotime();
	$today=date ("H:i:s");
	$rnd = rand(0,99999999); 
	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");
	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");    
	$mmsg = "За эту игру заработали столько очков: "; 
	$mmes = scores($rm); 
	$mmsg = $mmsg.$mmes;
	$tm = getmicrotime();
	$today=date ("H:i:s");
	$rnd = rand(0,99999999); 
	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
	}
	} 
		}
		//Конец if($vktr!==true)
		//Конец проверки    
		//mysql_query("UNLOCK TABLES");
		}
		//Конец проверки
		$tm = time();
		mysql_query ("update mafusers set onl = '".$tm."' WHERE id = '".$id."'"); 
			if ($gmes == 1) mysql_query ("update $ringame set onl = '".$tm."' WHERE gamer_id = '".$id."'");
				//mysql_query ("LOCK TABLES mafaction WRITE, maf, $ringame, mafusers READ");
				$r = mysql_query ("select * from $rmafaction");
				$a = mysql_fetch_array($r);
				$action = $a["action"];         
				$nexttime = $a["nexttime"]; 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (($action == "game_night"&&$tm>$nexttime)||($action == "dvote"&&$tm>$nexttime))
	{ //Начинается ночь  
	$tm = time()+120;
	mysql_query ("update $rmafaction set action = 'game_day', nexttime = '".$tm."', kiked = '0', cround = cround + 1"); 
	//mysql_query ("UNLOCK TABLES");
	$kiked = $a["kiked"];
		if ($kiked==1) 
			$mmsg = "Наступает ночь, все жители засыпают, кроме некоторых..."; 
				else 
					$mmsg = "Жители, прогалдев целый день, так ничего и не решили. Наступает ночь...";
			//Скидываем голосования 
			mysql_query("update $ringame set dvote = '0', wholin = '0'");
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
			//Проверяем, может ли жена комиссара убить
			mysql_query("select gamer_id from $ringame WHERE role = 'комиссар катани'");
				if(mysql_affected_rows()==0)
					{ //Комиссара нет  
					$r = mysql_query("select state from $ringame WHERE role = 'жена комиссара'");      
						if (mysql_affected_rows()!=0)
							{ //Жена жива
							$a = mysql_fetch_array($r);
								if ($a["state"]==0) mysql_query ("update $ringame set state = '1' WHERE role = 'жена комиссара'");

							}

					}				
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Мафия: 
mysql_query("update $ringame set gamer_act = ''");
//Сообщаем сообщников для мафии
$r = mysql_query("select * from $ringame WHERE role = 'мафиози'");
	if (mysql_affected_rows()!=0)
		{
			while (($a = mysql_fetch_array($r))!==false)
				{
				$thg = $a["gamer_id"];
				$re = mysql_query("select * from $ringame WHERE ((role = 'мафиози')or(role = 'главарь мафии'))and(gamer_id != '".$thg."')");
				$so = "";
					while (($b = mysql_fetch_array($re))!==false)
						{
						$sname = get_name_by_id($b["id_in_game"], $rm);
							if (get_role_by_id($b["id_in_game"], $rm)!="главарь мафии") $so = $so."$sname, "; 
								else $so = $so."$sname(главарь), ";

						}			    
				$so = substr($so,0,strlen($so)-2);
				$mmsg = "Сообщники: $so";
				$tm = getmicrotime();
				$today=date ("H:i:s");
				$rnd = rand(0,99999999); 
				mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$thg."', gamemes='1'");  
				mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
				}          

		}
	$r = mysql_query("select * from $ringame WHERE role = 'главарь мафии'");
	$a = mysql_fetch_array($r);
	$glmaf_id = $a["gamer_id"];             
	$mmsg = "Выбирайте, кому сегодня не поздоровится(!номер, в приват Мафу): ";
	$r = mysql_query("select * from $ringame");
	$kol = mysql_affected_rows();
		for ($i=1;$i<=$kol;$i++)
			{
			$a = mysql_fetch_array($r);
			$gamer_id = $a["gamer_id"];
			$r2 = mysql_query ("select * from mafusers where id = '".$gamer_id."'");
			$b = mysql_fetch_array($r2);
			$gname = $b["user"];
			$id_in_game = $a["id_in_game"];
			$s = $s."$id_in_game - $gname, "; 
			}      
	$mmsg = $mmsg.$s;
	$mmsg = substr($mmsg,0,strlen($mmsg)-2);
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
	//Кто еще мафы:
	$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'"); 
		if (mysql_affected_rows()!=0)
			{
			$sg = "";
				while (($a = mysql_fetch_array($r))!==false)
					{
					$sname = get_name_by_id($a["id_in_game"], $rm);
					$sg = $sg."$sname, ";
					}
			$sg = substr($sg,0,strlen($sg)-2);
			$mmsg = $mmsg."<br/>"."(ваши сообщники: $sg)";
			}
	$tm = getmicrotime();
	$today=date ("H:i:s");
	$rnd = rand(0,99999999); 
	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='".$glmaf_id."', gamemes='1'"); 
	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
//Комиссар
	$r = mysql_query("select * from $ringame WHERE role = 'комиссар катани'"); 
		if (mysql_affected_rows()!=0)
			{
			$a = mysql_fetch_array($r);
			$kom_id = $a["gamer_id"];
			$mmsg = "Выбирайте, кого проверить (!номер, в приват Мафу) или убить (!!номер): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$kom_id."', gamemes='1'"); 
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Маньяк  
	$r = mysql_query("select * from $ringame WHERE role = 'маньяк'"); 
		if (mysql_affected_rows()!=0)
			{
			$a = mysql_fetch_array($r);
			$man_id = $a["gamer_id"];
			$mmsg = "Кто же будет жертвой маньяка? (!номер, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='".$man_id."', gamemes='1'"); 
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Путана 
	$r = mysql_query("select * from $ringame WHERE role = 'путана'");  
		if (mysql_affected_rows()!=0)
			{
			$a = mysql_fetch_array($r);
			$put_id = $a["gamer_id"];
			$mmsg = "К кому же шлюха направится сегодня? (!номер, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$put_id."', gamemes='1'");   
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");         
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Бомж  
	$r = mysql_query("select * from $ringame WHERE role = 'Р±РѕРјР¶'"); 
		if (mysql_affected_rows()!=0)
			{
			$a = mysql_fetch_array($r);
			$bomj_id = $a["gamer_id"];
			$mmsg = "У кого роемся в карманах? (!номер, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$bomj_id."', gamemes='1'");    
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Доктор
	$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
		if (mysql_affected_rows()!=0)
			{ 
			$a = mysql_fetch_array($r);
			$dok_id = $a["gamer_id"];
			$mmsg = "Кого лечим? (!номер, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$dok_id."', gamemes='1'");          
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
			}      
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Клоун
	$r = mysql_query("select * from $ringame WHERE role = 'клоун'"); 
	$a = mysql_fetch_array($r);
	$state = $a["state"];
		if (mysql_affected_rows()!=0&&$state==0)
			{ 
			$kloun_id = $a["gamer_id"];
			$mmsg = "Выберите, чьи роли поменять местами(''!номер !номер'', через пробел, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$kloun_id."', gamemes='1'");          
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
			}   
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Жена комиссара
	$r = mysql_query("select * from $ringame WHERE role = 'жена комиссара'"); 
	$a = mysql_fetch_array($r);
	$state = $a["state"];
		if (mysql_affected_rows()!=0&&$state==1)
			{ 
			$jena_id = $a["gamer_id"];
			$mmsg = "На кого выпустим нашу месть? (!номер, в приват Мафу): ".$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$jena_id."', gamemes='1'");          
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
			}      
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Конец

	} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if (($action=="game_day"&&$tm>$nexttime)||$action == "allvoted")
	{  //Наступает день... 
	$tm = time()+180;
	mysql_query ("update $rmafaction set action = 'game_night', nexttime = '".$tm."'"); 
	//mysql_query ("UNLOCK TABLES");
	$kom_kil = 0;
	$maf_kil = 0;
	$man_kil = 0;  
	$jena_kil = 0;
	$mmsg = "Вот и день наступил. Но все ли дожили до него?";
	$r = mysql_query("select * from $ringame WHERE role = 'путана'");
	$a = mysql_fetch_array($r);
	$put_act = 0;
	$put_act = $a["gamer_act"];
	$put_id = $a["gamer_id"]; 
	$r = mysql_query("select * from $ringame WHERE role = 'горец'");
	$a = mysql_fetch_array($r);
	$gor_id_in_game = $a["id_in_game"];
		if ($put_act != 0) mysql_query("update mafusers set creditsingame = creditsingame + 5 WHERE id = '".$put_id."'"); //Путана, если действует, получает +5 очков
			$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
			$a = mysql_fetch_array($r);
			$doknotact = false;
			$dok_act = 0;
				if ($put_act != $a["id_in_game"]) $dok_act = $a["gamer_act"]; //Доктор лечит, если его не отвлекала шлюха
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////				
//Действия комиссара
	$r = mysql_query("select * from $ringame WHERE role = 'комиссар катани'");
		if (mysql_affected_rows()!=0)
			{  //РћРЅ РІ РёРіСЂРµ
			$a = mysql_fetch_array($r);
			$kom_id = $a["gamer_id"];
				if ($a["gamer_act"]!="")
					{ //Он выбрал жертву
					$wh = get_name_by_id($a["gamer_act"], $rm);
						if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Р?нспектор катани РІСЃСЋ ночь был занят шлюхой, Рё РЅРµ успел отловить бандитов."; 
							else if (strpos($a["gamer_act"],"!")===false)
								{
                                mysql_query("update mafusers set creditsingame = creditsingame + 5 WHERE id = '".$kom_id."'"); //Получает +5 очков за проверку
                                $mmsg = $mmsg." Р?нспектор катани времени Р·СЂСЏ РЅРµ терял. Проведя тщательное расследование, РѕРЅ наконец-то выяснил, кто такой $wh!";
                                    if (get_role_by_id($a["gamer_act"], $rm)=="мафиози"||get_role_by_id($a["gamer_act"], $rm)=="главарь мафии")$tokom = "$wh - мафиози"; 
										else 
											$tokom = "$wh - мирный житель";  
                                            $tm = getmicrotime();
                                            $today=date ("H:i:s");
                                            $rnd = rand(0,99999999); 
                                            mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$tokom."', id='".$tm."', towhom='".$kom_id."', gamemes='1'");              
                                            mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
                                }
									else  //Убийство
										{       
                                        $a["gamer_act"] = str_replace("!","",$a["gamer_act"]);
                                        $wh = get_name_by_id($a["gamer_act"], $rm);
                                        $kto = role_to_rpadej(get_role_by_id($a["gamer_act"], $rm));  
                                            if ($gor_id_in_game!=$a["gamer_act"])
												{      //Если не горец
                                                    if ($a["gamer_act"] != $dok_act)
														{ //Доктор не того выбрал
                                                            if (get_role_by_id($a["gamer_act"], $rm)=="мафиози"||get_role_by_id($a["gamer_act"], $rm)=="главарь мафии") 
																{
																$mmsg = $mmsg." Проведя сложнейшую операцию, инспектор катани наконец-то вычислил и убил $kto $wh!!!"; mysql_query("update mafusers set creditsingame = creditsingame + 20 WHERE id = '".$kom_id."'");
																}//Казнил мафа, +20 очков
                                                                    else 
																		{
																		$mmsg = $mmsg." Р?нспектор катани так спятил, что казнил РЅРё РІ чем РЅРµ РїРѕРІРёРЅРЅРѕРіРѕ $kto $wh!"; mysql_query("update mafusers set creditsingame = creditsingame - 20 WHERE id = '".$kom_id."'");}//Казнил мирного, -20 очков   
                                                                        $kom_kil = $a["gamer_act"];
                                                        }
															else 
																{   //Вылечил доктор
                                                                $mmsg = $mmsg." Комиссар катани почти расстрелял $wh, но добрый доктор буквально достал того из гроба."; 
                                                                $doknotact = true;
                                                                } 
                                                }
													else 
														{     //нарвался на горца
                                                        $mmsg = $mmsg." Комиссар катани расстрелял ночью горца, и был очень удивлен, когда тот не умер.";
                                                        }
                                        }
					}
						//else $mmsg = $mmsg." Р?нспектор катани так набухался, что провалялся РІСЃСЋ ночь РґРѕРјР°, так ничего Рё РЅРµ выяснив";
						//$tm = time();
						//$today=date ("H:i:s");
						//$rnd = rand(0,99999999); 
						//mysql_query ("Insert into maf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom=''");            
			}    
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия мафии
	$r = mysql_query("select * from $ringame WHERE role = 'главарь мафии'");
	$a = mysql_fetch_array($r);
	$maf_id = $a["gamer_id"];
		if ($a["gamer_act"]!="")
			{
			$wh = get_name_by_id($a["gamer_act"], $rm);
			if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Шлюха направилась в логово к мафии и всю ночь пробыла с главарем мафии, отвлекая его от дел."; 
				else 
					{   
						if ($gor_id_in_game != $a["gamer_act"])
							{ //Если не горец
							mysql_query("update mafusers set creditsingame = creditsingame + 10 WHERE id = '".$maf_id."'"); //Мафия всегда получает за любое убийство +10 очков
							$kto = role_to_tpadej(get_role_by_id($a["gamer_act"], $rm));  
								if ($dok_act != $a["gamer_act"])
									{
									$mmsg = $mmsg." Мафия сегодня зверски расправилась с $kto $wh!";             
									$maf_kil = $a["gamer_act"];
									}
										else 
											{ //Вылечил доктор

                                                  $mmsg = $mmsg." Мафы убили $wh, но доктор сгонял на кладбище и пришил ему все обратно";    

                                                  $doknotact = true; //Тогда дальше не пишем сообщение о том, кого лечил доктор

                                                  } 

                                           }else { //нарвались на горца

                                                  $mmsg = $mmsg." Мафия ночью нарвалась на горца, он ей так накостылял, что мафы еле ноги унесли.";

                                                  }

					}		

			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия маньяка   
	$r = mysql_query("select * from $ringame WHERE role = 'маньяк'");
		if (mysql_affected_rows()!=0)
			{  //РѕРЅ РІ РёРіСЂРµ   
			$a = mysql_fetch_array($r);
			$man_id = $a["gamer_id"];
			$man_act = $a["gamer_act"]; 
				if ($a["gamer_act"]!="")
					{                    
					$wh = get_name_by_id($a["gamer_act"], $rm);
						if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Маньяк так хотел намотать кишки на руку кому-нибудь этой ночью, но встретил шлюху и решил отложить это дело."; 
							else 
								{        
								$kto = get_role_by_id($a["gamer_act"], $rm); 
									if ($dok_act != $a["gamer_act"])
										{  
										//Добавляем очки
										mysql_query("select * from $ringame WHERE (id_in_game = '".$man_act."')and((role = 'мафиози')or(role = 'главарь мафии'))");
											if (mysql_affected_rows()!=0) mysql_query("update mafusers set creditsingame = creditsingame + 20 WHERE id = '".$man_id."'"); //Маньяк казнил мафа, +20 очков
												else mysql_query("update mafusers set creditsingame = creditsingame - 5 WHERE id = '".$man_id."'"); //Маньяк казнил мирного, -5 очков
										$mmsg = $mmsg." $kto $wh был наден утром в мусорном баке с топором в жопе. Похоже, тут не обошлось без маньяка...";
										$man_kil = $a["gamer_act"];
                                        }
											else
												{ //Вылечил док
                                                $mmsg = $mmsg." Маньяк вставил топор в жопу $wh, но операция была успешной, док его вытащил"; 
                                                $doknotact = true;
                                                }
								}
					}
			}    
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия бомжа
	$r = mysql_query("select * from $ringame WHERE role = 'Р±РѕРјР¶'");
		if (mysql_affected_rows()!=0)
			{  //РћРЅ РІ РёРіСЂРµ  
			$a = mysql_fetch_array($r);
			$bomj_id = $a["gamer_id"];                                   
				if ($a["gamer_act"]!="")
					{                    
					$wh = get_name_by_id($a["gamer_act"], $rm);
						if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Нахальный бомж поймал шлюху на улице и затащил к подвал. Там они и провели всю ночь."; 
							else 
								{         
								mysql_query("update mafusers set creditsingame = creditsingame + 5 WHERE id = '".$bomj_id."'");  //Бомж действует, ему +5 очков
								$mmsg = $mmsg." Бомж ночью рылся в карманах у $wh!";
								$kto = get_role_by_id($a["gamer_act"], $rm);
								$mmsgtob = "$wh это $kto!";
								$tm = getmicrotime();
								$today=date ("H:i:s");
								$rnd = rand(0,99999999); 
								mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsgtob."', id='".$tm."', towhom='".$bomj_id."', gamemes='1'");   
								mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
								}
					}
			} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия жены комиссара
	$r = mysql_query("select * from $ringame WHERE role = 'жена комиссара'");
		if (mysql_affected_rows()!=0)
			{
			$a = mysql_fetch_array($r);
			$jena_id = $a["gamer_id"];  
			$state = $a["state"];
				if ($a["gamer_act"]!="")
					{
					$wh = get_name_by_id($a["gamer_act"], $rm);
						if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Шлюха сегодня направилась к жене комиссара. Камасутра отдыхает."; 
							else 
								{   
									if ($gor_id_in_game != $a["gamer_act"])
										{ //Если не горец
										mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$jena_id."'"); //За мщение получает 50 очков
										$kto = role_to_rpadej(get_role_by_id($a["gamer_act"], $rm));  
											if ($dok_act != $a["gamer_act"])
												{
												$mmsg = $mmsg." Жена комиссара отравила ночью $kto $wh, отомстив за смерть мужа.!";             
												$jena_kil = $a["gamer_act"];
												}
													else 
														{ //Вылечил доктор
														$mmsg = $mmsg." Жена комиссара почти зарезала $wh, но добрый док за небольшую плату все восстановил.";    
														$doknotact = true; //Тогда дальше не пишем сообщение о том, кого лечил доктор
														} 
                                        }
											else 
												{ //нарвались на горца
												$mmsg = $mmsg." Жена комиссара продырявила ножом горца, а он даже не заметил. Теперь ходит с ножом в жопе.";
                                                }
								}
					}
			} 
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия доктора
	$r = mysql_query("select * from $ringame WHERE role = 'доктор'");
		if (mysql_affected_rows()!=0)
			{  //РћРЅ РІ РёРіСЂРµ 
			$a = mysql_fetch_array($r);
			$dok_id = $a["gamer_id"];  
				if ($doknoact==true) mysql_query("update mafusers set creditsingame = creditsingame + 20 WHERE id = '".$dok_id."'");  //Док угадал, кого лечить, +20 очков
					else 
						if ($put_act!=$a["id_in_game"]) mysql_query("update mafusers set creditsingame = creditsingame + 5 WHERE id = '".$dok_id."'");  //Не угадал, +5 очков   
							if ($a["gamer_act"]!=""&&$doknotact===false)
								{ 
								$wh = get_name_by_id($a["gamer_act"], $rm);
									if ($put_act==$a["id_in_game"]) $mmsg = $mmsg." Доктор целую ночь прокувыркался с путаной, так никого и не вылечив";
										else
											{
												if ($a["gamer_id"]==$a["gamer_act"]) $mmsg = $mmsg." Наш доктор эгоистично лечил сам себя.";
													else $mmsg = $mmsg." Доктор накачал лекарствами $wh";
											}
								}
									//else $mmsg = $mmsg."";
			}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Действия клоуна
	$r = mysql_query("select * from $ringame WHERE role = 'клоун'");
		if (mysql_affected_rows()!=0)
			{  //РћРЅ РІ РёРіСЂРµ  
			$a = mysql_fetch_array($r);
			$state = $a["state"];
			$kloun_id = $a["gamer_id"];   
				if ($a["gamer_act"]!="")
					{ //Если он еще не выбирал, и выбрал кого-то в эту ночь
						list($g1,$g2) = explode (" ",$a["gamer_act"]); //кого меняем
						mysql_query("select gamer_id from $ringame WHERE (id_in_game = '".$g1."')or(id_in_game = '".$g2."')");
							if (mysql_affected_rows()==2)
								{ //Если оба игрока еще в игре 
								//mysql_query("update $ringame set state = '1' WHERE gamer_id = '".$kloun_id."'");
								$r = mysql_query("select gamer_id, role, state from $ringame WHERE id_in_game = '".$g1."'");
								$b = mysql_fetch_array($r);
								$gid1 = $b["gamer_id"];
								$role1 = $b["role"]; 
								$state1 = $b["state"];
								$r = mysql_query("select gamer_id, role, state from $ringame WHERE id_in_game = '".$g2."'");
								$b = mysql_fetch_array($r);
								$gid2 = $b["gamer_id"];
								$role2 = $b["role"]; 
								$state2 = $b["state"];
								$mmsg1 = "Ваша новая роль: $role2!"; 
								$mmsg2 = "Ваша новая роль: $role1!";
								$tm = getmicrotime();
								$today=date ("H:i:s");
								$rnd = rand(0,99999999); 
								mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg1."', id='".$tm."', towhom='".$gid1."', gamemes='1'");    
								mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
								$tm = getmicrotime();
								$today=date ("H:i:s");
								$rnd = rand(0,99999999); 
								mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg2."', id='".$tm."', towhom='".$gid2."', gamemes='1'");    
								mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");        
								mysql_query("update $ringame set role = '".$role2."', state = '".$state2."' WHERE id_in_game = '".$g1."'"); 
								mysql_query("update $ringame set role = '".$role1."', state = '".$state1."' WHERE id_in_game = '".$g2."'");//Меняем роли местами
								$mmsg = $mmsg." Жители! В городе завелся клоун, и этой ночью он поменял роли двух игроков!!!"; 
								$r = mysql_query("select cround from $rmafaction");
								$a = mysql_fetch_array($r);
								$sc = $a["cround"]*30;  
								mysql_query("update mafusers set creditsingame = creditsingame + '".$sc."' WHERE id = '".$kloun_id."'"); //+(30*раунд) очков клоуну    
								mysql_query("update $ringame set state = '1' WHERE role = 'клоун'");
								}
					} 

			}      
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Вывод
	$tm = getmicrotime();
	$today=date ("H:i:s");
	$rnd = rand(0,99999999); 
	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");    
	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");        
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Удаление, кого убили
	mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE ((id_in_game = '".$kom_kil."')or(id_in_game = '".$maf_kil."')or(id_in_game = '".$man_kil."')or(id_in_game = '".$jena_kil."'))and(mafusers.id = $ringame.gamer_id)");
	mysql_query ("delete from $ringame WHERE (id_in_game = '".$kom_kil."')or(id_in_game = '".$maf_kil."')or(id_in_game = '".$man_kil."')or(id_in_game='".$jena_kil."')");
	$vktr = false;
	//mysql_query("LOCK TABLES mafusers, ingame, scores WRITE, maf READ");
	$r = mysql_query("select count(*) as sm from $ringame");
	$a = mysql_fetch_array($r);
	$sm = $a["sm"];   //в $sm - число игроков 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Запись, сколько народу осталось
	$r = mysql_query("select current,prev,prevprev from $rmafaction");
	$a = mysql_fetch_array($r);
	$current = $a["current"];
	$prev = $a["prev"];
	//$prevprev = $a["prevprev"];
	$prevprev = $prev;
	$prev = $current;
	$current = $sm;
	mysql_query("update $rmafaction set prevprev = '".$prevprev."', prev = '".$prev."', current = '".$current."'");  
		if ($current == $prevprev)
			{ //Если 2 раунда никого не убили 
			//mysql_query ("LOCK TABLES mafaction,ingame, mafusers WRITE, maf READ");
			mysql_query ("update $rmafaction set action = 'nogame'");
			$vktr = true;  
			$mmsg = "Два раунда жители тормозят, и никто не умирает. Поэтому объявляется ничья! А роли были такие: "; 
			//Начисляем очки выжившим 
			$r = mysql_query("select gamer_id from $ringame");
				while (($a = mysql_fetch_array($r))!==false)
					{
					$gamer_id = $a["gamer_id"];
					mysql_query("update mafusers set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
					}
			//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 25 WHERE mafusers.id = ingame.gamer_id"); //выжившим +25
			$r = mysql_query("Select * from $ringame");
				while (($a = mysql_fetch_array($r))!==false)
					{  //Какие у кого роли
					$gnick = get_name_by_id($a["id_in_game"], $rm);
					$grole = get_role_by_id($a["id_in_game"], $rm);
					$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
					} 
			$mmsg = substr($mmsg,0,strlen($mmsg)-2); 
			//mysql_query("UNLOCK TABLES");
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
			mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
			mysql_query("delete from $ringame");  
			$mmsg = "За эту игру заработали столько очков: "; 
			$mmes = scores($rm); 
			$mmsg = $mmsg.$mmes;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
			//mysql_query ("UNLOCK TABLES");
			}
	mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
		if (mysql_affected_rows()==0&&$sm!=0&&$vktr!==true)
			{ //Убит главный маф, и еще есть игроки
			$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
				if (mysql_affected_rows()==0)
					{ //Мафов больше нет, победа мирных жителей    
					$vktr = true;
					//mysql_query ("LOCK TABLES mafaction WRITE, maf, ingame, mafusers READ");
					mysql_query ("update $rmafaction set action = 'nogame'"); 
					//mysql_query ("UNLOCK TABLES");  
			        //Мирным начисляем очки  
					$r = mysql_query("select role, gamer_id from $ringame");
						while (($a = mysql_fetch_array($r))!==false)
							{
							$role = $a["role"];
							$gamer_id = $a["gamer_id"];
								if ($role == "обыватель") mysql_query("update mafusers set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
									else mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
							}
					//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 100 WHERE (ingame.role = 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим обывателям +100
					//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (ingame.role != 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим другим +50
					$mmsg = "Р?РіСЂР° окончена, победа мирных жителей! Рђ роли были такие: "; 
					$r = mysql_query("Select * from $ringame");
						while (($a = mysql_fetch_array($r))!==false)
							{  //Какие у кого роли
							$gnick = get_name_by_id($a["id_in_game"], $rm);
							$grole = get_role_by_id($a["id_in_game"], $rm);
							$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
							} 
					$mmsg = substr($mmsg,0,strlen($mmsg)-2);  
					mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
					mysql_query ("delete from $ringame"); 
					//mysql_query ("UNLOCK TABLES");
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999); 
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
					$mmsg = "За эту игру заработали столько очков: "; 
					$mmes = scores($rm); 
					$mmsg = $mmsg.$mmes;
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999); 
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
					}
						else
							{ //Назначение нового главаря мафии
							$a = mysql_fetch_array($r);  
							$id_in_game = $a["id_in_game"];
							$gamer_id = $a["gamer_id"];
							mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
							$mmsg = "Теперь вы главарь мафии!"; 
							//mysql_query ("UNLOCK TABLES");
							$tm = getmicrotime();
							$today=date ("H:i:s");
							$rnd = rand(0,99999999); 
							mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1'");     
							mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
							}			
			} 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Проверка, победили ли Мафы или ничья
	if ($vktr!==true)
		{
		$r = mysql_query ("select count(*) as sm from $ringame");
		$a = mysql_fetch_array($r); 
			if ($a["sm"]==2)
				{
				mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')"); 
					if (mysql_affected_rows()==2) 
						$vk = "maf";
							if (mysql_affected_rows()==1)
								{ //1 маф
								mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
									if (mysql_affected_rows() != 0) 
										$vk = "ni4"; 
											else 
												$vk = "maf";

								}
				}
	if ($a["sm"]==1)
		{
		mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
			if (mysql_affected_rows() != 0) 
				$vk = "maf";
		}
	if ($a["sm"]==0) 
		$vk = "ni4"; 
		mysql_query("select * from $ringame");
		$nm = round(mysql_affected_rows()/2-0.5); //Большинство
		$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
		$a = mysql_fetch_array($r);
		$sm = $a["sm"];
			if ($sm>$nm) 
				$vk = "maf";
					if (isset($vk))
						{  //Р?РіСЂР° окончена
						$vktr = true;
							if ($vk == "ni4")
								{ //Ничья
								$vktr = true;
								//mysql_query ("LOCK TABLES mafaction WRITE, maf, ingame, mafusers READ");
								mysql_query ("update $rmafaction set action = 'nogame'");
								//mysql_query ("UNLOCK TABLES"); 
								//Начисляем очки выжившим 
								$r = mysql_query("select gamer_id from $ringame");
									while (($a = mysql_fetch_array($r))!==false)
										{
										$gamer_id = $a["gamer_id"];
										mysql_query("update mafusers set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
										}

								//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 25 WHERE mafusers.id = ingame.gamer_id"); //выжившим +25
								$mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
								$r = mysql_query("Select * from $ringame");
									while (($a = mysql_fetch_array($r))!==false)
										{  //Какие у кого роли
										$gnick = get_name_by_id($a["id_in_game"], $rm);
										$grole = get_role_by_id($a["id_in_game"], $rm);
										$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
										} 
								$mmsg = substr($mmsg,0,strlen($mmsg)-2);   
								mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
								mysql_query ("delete from $ringame"); 
								//mysql_query ("UNLOCK TABLES");
								$tm = getmicrotime();
								$today=date ("H:i:s");
								$rnd = rand(0,99999999); 
								mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");
								mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
								$mmsg = "За эту игру заработали столько очков: "; 
								$mmes = scores($rm); 
								$mmsg = $mmsg.$mmes;
								$tm = getmicrotime();
								$today=date ("H:i:s");
								$rnd = rand(0,99999999); 
								mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
								mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
								}
	if ($vk == "maf")
		{ 
		//mysql_query ("LOCK TABLES mafaction WRITE, maf, ingame, mafusers READ");
        $vktr = true;
        mysql_query ("update $rmafaction set action = 'nogame'"); 
        //mysql_query ("UNLOCK TABLES"); 
        //Начисляем очки мафам 
        $r = mysql_query("select role, gamer_id from $ringame");
			while (($a = mysql_fetch_array($r))!==false)
				{
				$role = $a["role"];
				$gamer_id = $a["gamer_id"];
					if ($role == "мафиози"||$role == "главарь мафии") 
						mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
				}	

        //mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (mafusers.id = ingame.gamer_id)and((ingame.role='мафиози')or(ingame.role='главарь мафии'))"); //Мафам +25
        $mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
        $r = mysql_query("Select * from $ringame");
			while (($a = mysql_fetch_array($r))!==false)
				{  //Какие у кого роли
				$gnick = get_name_by_id($a["id_in_game"], $rm);
				$grole = get_role_by_id($a["id_in_game"], $rm);
				$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
				} 

        $mmsg = substr($mmsg,0,strlen($mmsg)-2);    
        mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
        mysql_query ("delete from $ringame");
        //mysql_query ("UNLOCK TABLES");
        $tm = getmicrotime();
        $today=date ("H:i:s");
        $rnd = rand(0,99999999); 
        mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
		mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
		$mmsg = "За эту игру заработали столько очков: "; 
        $mmes = scores($rm); 
        $mmsg = $mmsg.$mmes;
        $tm = getmicrotime();
        $today=date ("H:i:s");
        $rnd = rand(0,99999999); 
        mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
        mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");

		}
						}   
		}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Конец if($vktr!==true) 
//mysql_query ("UNLOCK TABLES");
//Конец проверки 
//Линч 
	mysql_query ("update $ringame set gamer_act=''");    
		if ($vktr===false)
			{
			$mmsg = "Кого же залинчуем сегодня днем? День длится 3 минуты. Голосуем.(!номер) ";
			$r = mysql_query("select * from $ringame");
			$kol = mysql_affected_rows();
				for ($i=1;$i<=$kol;$i++)
					{
					$a = mysql_fetch_array($r);
					$gamer_id = $a["gamer_id"];
					$r2 = mysql_query ("select * from mafusers where id = '".$gamer_id."'");
					$b = mysql_fetch_array($r2);
					$gname = $b["user"];
					$id_in_game = $a["id_in_game"];
					$s = $s."<b>$id_in_game</b> - $gname, "; 
					} 
			$mmsg = $mmsg.$s;
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999); 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
			}   
	}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if ($action=="registration"&&$tm>$nexttime)
		{ //Регистрация кончилась, раздача ролей, если игроков больше 2
		mysql_query("select * from $ringame");
			if (mysql_affected_rows()<3)
				{      
				mysql_query ("update $rmafaction set action = 'nogame'");
				//mysql_query ("UNLOCK TABLES");
				$mmsg = "Р?РіСЂР° РЅРµ начнется, РїРѕРєР° РЅРµ будет хотя Р±С‹ 3 РёРіСЂРѕРєРѕРІ!";
				$tm = getmicrotime();
				$today=date ("H:i:s");
				$rnd = rand(0,99999999);
				mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
				mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
				mysql_query ("delete from $ringame");
				}
					else
						{
						mysql_query("delete from $rscores");                                                                     
						$tm = time()+25;
						mysql_query ("update $rmafaction set action = 'game_night', nexttime = '".$tm."', kiked = '1', cround = '0'");
						//mysql_query ("UNLOCK TABLES");
						$r = mysql_query ("select * from $ringame");
						$roles = array("обыватель","главарь мафии","комиссар катани"); 
							if (mysql_affected_rows()>3) 
								array_push ($roles,"доктор");
									if (mysql_affected_rows()>4) 
										array_push ($roles,"обыватель");
											if (mysql_affected_rows()>5) 	
												array_push ($roles,"мафиози");
													if (mysql_affected_rows()>6) 
														array_push ($roles,"маньяк");
															if (mysql_affected_rows()>7) 
																array_push ($roles,"путана");
																	if (mysql_affected_rows()>8) 
																		array_push ($roles,"обыватель");
																			if (mysql_affected_rows()>9) 
																				array_push ($roles,"мафиози");
							if (mysql_affected_rows()>10) 
								array_push ($roles,"Р±РѕРјР¶");   
									if (mysql_affected_rows()>11) 
										array_push ($roles,"мафиози"); 
											if (mysql_affected_rows()>12) 
												array_push ($roles,"горец"); 
													if (mysql_affected_rows()>13) 
														array_push ($roles,"клоун");  
															if (mysql_affected_rows()>14) 
																array_push ($roles,"мафиози"); 
																	if (mysql_affected_rows()>15) 
																		array_push ($roles,"жена комиссара");
							for ($i=1;$i<=((mysql_affected_rows()-15)/3);$i++) 
								array_push ($roles,"мафиози");     
								$j = count ($roles);
									for ($i=1;$i<=mysql_affected_rows()-$j;$i++) 
										array_push ($roles,"обыватель");
										mt_srand(time()*100000);
										shuffle($roles);
										$i = 0;
											while (($a = mysql_fetch_array($r))!==false)
												{
												$gamer_id = $a["gamer_id"]; 
												mysql_query("update mafusers set creditsingame = '0' WHERE id = '".$gamer_id."'");//Обнуляем очки, заработанные в прошлой игре
												$id_in_game = $i+1;           
												$role = $roles[$i];
												$mmsg = "Р’С‹ $role!"; 
												$tm = getmicrotime();
												$today=date ("H:i:s");
												$rnd = rand(0,99999999);
												mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1'"); 
												mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
												mysql_query("update $ringame set role = '".$role."', id_in_game = '".$id_in_game."' WHERE gamer_id = '".$gamer_id."'");
												$i++;
												} 
						$mmsg = "Раздача ролей окончена! Ночь начнется через 20 секунд!"; 
						$tm = getmicrotime();
						$today=date ("H:i:s");
						$rnd = rand(0,99999999);
						mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");
						mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
						mysql_query ("update $rmafaction set prevprev = '199', prev = '199', current = '200'");          
						//Конец раздачи ролей
						}


		}
	//mysql_query ("UNLOCK TABLES");
	$smthwr = 0; 
	$res = mysql_query ("Select * from $rmaf order by id desc LIMIT 100");
	$kol = mysql_affected_rows();   
	$lines = mysql_fetch_array ($res);
	@$topic = $lines["message"];
	$topic = str_replace("\n","",$topic); 
	@$msg = str_replace(chr("13"), " ", $msg);
	@$msg = str_replace(chr("10"), " ", $msg);
	@$msg = str_replace("\\n", " ", $msg);
	@$msg = trim(" $msg ");
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
		if(@$msg)                     
			{       
			$msg = ereg_replace(" +"," ",$msg);
			$msg=substr($msg,0,400);
			$msg = str_replace("$", "$$", $msg);     
			$msg = htmlspecialchars($msg); 
			$msg = str_replace("|", "&#0166;", $msg); 
			$msg = str_replace("'", "&#8216;", $msg); 
			$msg = str_replace("\\", "", $msg); 
				if (!isset($prvt)) 
					$prvt = 0;
					$str1="";
					$str2=$msg;
						if ($row["translit"]==1)
							{ 
							$r = mysql_query("select * from mafusers WHERE id = '".$towhom."'");
							$a = mysql_fetch_array($r);
								if (strpos($msg,$a["user"])===0)
									{
									$str1 = substr($msg,0,strlen($a["user"]));
									$str2 = substr($msg,strlen($a["user"]),strlen($msg)-strlen($a["user"])); 
									$msg = $str2;                                                      
									}
							}  
								if ($prvt == 0) 
									$towhom = "0";
										if (!isset($towhom)) 
											$towhom = "0";

//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Антифлуд
	$r = mysql_query("SELECT * FROM $rmaf WHERE usid = '".$id."' order by id desc LIMIT 1");
	$a = mysql_fetch_array($r);
		if ($a["message"] !== $msg)
			{
			$time = getmicrotime();
			$today=date ("H:i:s");
			$posts =  $row["posts"];
			$posts++;
			mysql_query ("Update mafusers set posts='".$posts."', onl='".$time."' where id ='".$id."'");
			$hid = $row["inv"];
			$kol++;   
			$rnd = rand(0,99999999);
			//$rnd = $id.$rnd; 
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='".$us."', message='".$msg."', id='".$time."', towhom='".$towhom."', hid='".$hid."', usid='".$id."', gamemes = '".$gmes."'");           
			$usmes["time"] = $today; 
			$usmes["who"] = $us;
			$usmes["usid"] = $id;
			$usmes["message"] = $msg; 
			$usmes["id"] = $time;
			$usmes["towhom"] = $towhom; 
			$usmes["gamemes"] = $gmes;
			$smthwr = 1;
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////			
//Что написал    
	//mysql_query ("LOCK TABLES mafaction WRITE, maf, $ringame, mafusers READ");  
	$r = mysql_query ("select * from $rmafaction");
	$a = mysql_fetch_array($r);     
	$action = $a["action"];     
		if ($action == "game_night"&&$gmes==1)
			{
			$s = str_replace("!","",$msg);
			$r = mysql_query("select * from $ringame WHERE id_in_game = '".$s."'"); 
				if (mysql_affected_rows()!==0)
					{ //Есть такой
					$a = mysql_fetch_array($r);
					$id_in_game = $a["id_in_game"];
					mysql_query ("update $ringame set gamer_act = '".$s."' WHERE gamer_id = '".$id."'");
					$wh = get_name_by_id($id_in_game, $rm);
					mysql_query("select * from $ringame WHERE gamer_act = '".$s."'");
					// $a = mysql_fetch_array($r);
					// $sm = $a["sm"]; //Сколько всего проголосовало за него
					$sm = mysql_affected_rows();
					$mmsg = "$us голосует за $wh!(<b>$sm</b>)"; 
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999);
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");       
					}
			//Проверка, есть ли у кого-нить более половины голосов
			mysql_query ("select * from $ringame");
			$nm = round(mysql_affected_rows()/3); //Большинство
			$r = mysql_query ("select *,count(gamer_act) from $ringame WHERE gamer_act != '' group by gamer_act having count(gamer_act)>'".$nm."'");
			$a = mysql_fetch_array($r); 
			//$w = $a["gamer_act"];
			//echo "$nm...$w";
				if (mysql_affected_rows() != 0)
					{
					$w = $a["gamer_act"]; //За кого проголосовали
					mysql_query ("update $rmafaction set action = 'dvote'"); //Голосуем
					//mysql_query ("UNLOCK TABLES");
					mysql_query ("update $ringame set dvote = '1' WHERE id_in_game = '".$w."'"); //Пометка, за кого идет голосование
					//$a = mysql_fetch_array($r);
					//echo "$w";
					$whk = get_name_by_id($w, $rm);
					$mmsg = "Жители, вы уверены, что хотите казнить $whk?(!да или !нет) $whk, у вас есть время оправдаться.";
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999);
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
					}
			} 
				if ($gmes==1&&$action == "dvote"&&($msg == "!da"||$msg == "!net"||$msg == "!да"||$msg == "!нет"))
					{ //Проголосовал за кого-то
					$r = mysql_query("select * from $ringame WHERE dvote = '1'");
					$a = mysql_fetch_array($r);
					$w = $a["id_in_game"];  
					//echo "$w";
					$whk = get_name_by_id($w, $rm); //За кого голосуем  
						if ($msg=="!da"||$msg == "!РґР°")
							{  //голосует за
							mysql_query("update $ringame set wholin = '1' WHERE gamer_id = '".$id."'");
							$mmsg = "$us голосует за казнь $whk!";
							}
								else 
									{
									mysql_query("update $ringame set wholin = '-1' WHERE gamer_id = '".$id."'"); 
									$mmsg = "$us голосует против казни $whk!";
									}
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999);
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");    
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
					//Есть ли большинство голосов за?
					mysql_query ("select * from $ringame");
					$nm = round(mysql_affected_rows()/2-0.5); //Большинство  
					mysql_query("select * from $ringame WHERE wholin = '1'");
						if (mysql_affected_rows()>$nm)
							{
							$tm = time();
							mysql_query("update $rmafaction set action = 'game_night', nexttime = '".$tm."', kiked = '1'"); //Ночь, отмечаем убийство
							$krole = get_role_by_id($w, $rm);
								if ($krole=="мафиози"||$krole=="главарь мафии")
									{ //Казнили Мафа         
									$krole = role_to_tpadej($krole);
									$mmsg = "Наконец-то мирные жители расправились с $krole $whk!!!";
									}
										else 
											{ //Казнили мирного       
											$krole = role_to_rpadej($krole);
											$mmsg = "Жители сами усложнили себе задачу, казнив ни в чем не повинного $krole $whk!";
											}   
					mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE (mafusers.id = $ringame.gamer_id)and(id_in_game = '".$w."')");    
					mysql_query ("delete from $ringame WHERE id_in_game = '".$w."'");
					$tm = getmicrotime();
					$today=date ("H:i:s");
					$rnd = rand(0,99999999);
					mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");
					mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
					//mysql_query ("UNLOCK TABLES");
					$vktr = false; 
					//mysql_query("LOCK TABLES mafusers, $ringame, scores WRITE, maf READ");
					$r = mysql_query("select count(*) as sm from $ringame");
					$a = mysql_fetch_array($r);
					$sm = $a["sm"];   //в $sm - число игроков
					mysql_query ("select * from $ringame WHERE role = 'главарь мафии'");
						if (mysql_affected_rows()==0&&$sm!=0)
							{ //Убит главный маф, и еще есть игроки
							$r = mysql_query ("select * from $ringame WHERE role = 'мафиози'");
								if (mysql_affected_rows()==0)
									{ //Мафов больше нет, победа мирных жителей
									$vktr = true;
									mysql_query ("update $rmafaction set action = 'nogame'");
									//mysql_query ("UNLOCK TABLES");
									//Мирным начисляем очки   
									$r = mysql_query("select role, gamer_id from $ringame");
										while (($a = mysql_fetch_array($r))!==false)
											{
											$role = $a["role"];
											$gamer_id = $a["gamer_id"];
											if ($role == "обыватель") mysql_query("update mafusers set creditsingame = creditsingame + 100 WHERE id = '".$gamer_id."'"); 
												else 
													mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'");
											}
									//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 100 WHERE (ingame.role = 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим обывателям +100
									//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (ingame.role != 'обыватель')and(mafusers.id = ingame.gamer_id)"); //выжившим другим +50
									$mmsg = "Р?РіСЂР° окончена, победа мирных жителей! Рђ роли были такие: "; 
									$r = mysql_query("Select * from $ringame");
										while (($a = mysql_fetch_array($r))!==false)
											{  //Какие у кого роли
											$gnick = get_name_by_id($a["id_in_game"], $rm);
											$grole = get_role_by_id($a["id_in_game"], $rm);
											$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
											} 
									$mmsg = substr($mmsg,0,strlen($mmsg)-2); 
									mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
									mysql_query ("delete from $ringame"); 
									//mysql_query ("UNLOCK TABLES");
									$tm = getmicrotime();
									$today=date ("H:i:s");
									$rnd = rand(0,99999999); 
									mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
									mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
									$mmsg = "За эту игру заработали столько очков: "; 
									$mmes = scores($rm); 
									$mmsg = $mmsg.$mmes;
									$tm = getmicrotime();
									$today=date ("H:i:s");
									$rnd = rand(0,99999999); 
									mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
									mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
									}
										else
											{ //Назначение нового главаря мафии
											$a = mysql_fetch_array($r);  
											$id_in_game = $a["id_in_game"];
											$gamer_id = $a["gamer_id"];
											mysql_query ("update $ringame set role = 'главарь мафии' WHERE id_in_game = '".$id_in_game."'");
											$mmsg = "Теперь вы главарь мафии!";
											$tm = getmicrotime(); 
											//mysql_query ("UNLOCK TABLES");
											$today=date ("H:i:s");
											$rnd = rand(0,99999999); 
											mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$gamer_id."', gamemes='1'"); 
											mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
											}
							} 
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////	
//Проверка, победили ли Мафы или ничья
	if ($vktr!==true)
		{
		$r = mysql_query ("select count(*) as sm from $ringame");
		$a = mysql_fetch_array($r);
			if ($a["sm"]==2)
				{
				mysql_query("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
					if (mysql_affected_rows()==2) 
						$vk = "maf";
							if (mysql_affected_rows()==1)
								{ //1 маф
								mysql_query("select * from $ringame WHERE (role = 'доктор')or(role = 'комиссар катани')or(role = 'путана')or(role = 'маньяк')");   
									if (mysql_affected_rows() != 0) 
										$vk = "ni4"; 
											else 
												$vk = "maf";
								}
				}
					if ($a["sm"]==1)
						{
						mysql_query ("select * from $ringame WHERE (role = 'главарь мафии')or(role = 'мафиози')");
							if (mysql_affected_rows() != 0) 
								$vk = "maf";
						}
							if ($a["sm"]==0) 
								$vk = "ni4"; 
								mysql_query("select * from $ringame");
								$nm = round(mysql_affected_rows()/2-0.5); //Большинство
								$r = mysql_query("Select count(*) as sm from $ringame WHERE (role='мафиози')or(role='главарь мафии')");
								$a = mysql_fetch_array($r);
								$sm = $a["sm"];
									if ($sm>$nm) 
										$vk = "maf";
											if (isset($vk))
												{  //Р?РіСЂР° окончена
													if ($vk == "ni4")
														{ //Ничья
														$vktr = true;
														mysql_query ("update $rmafaction set action = 'nogame'"); 
														//mysql_query ("UNLOCK TABLES");  
														//Начисляем очки выжившим   
														$r = mysql_query("select gamer_id from $ringame");
															while (($a = mysql_fetch_array($r))!==false)
																{
																$gamer_id = $a["gamer_id"];
																mysql_query("update mafusers set creditsingame = creditsingame + 25 WHERE id = '".$gamer_id."'"); 
																}
														//mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 25 WHERE mafusers.id = ingame.gamer_id"); //выжившим +25
														$mmsg = "Силы Мафии и мирных жителей равны, ничья! А роли были такие: "; 
														$r = mysql_query("Select * from $ringame");
															while (($a = mysql_fetch_array($r))!==false)
																{  //Какие у кого роли
																$gnick = get_name_by_id($a["id_in_game"], $rm);
																$grole = get_role_by_id($a["id_in_game"], $rm);
																$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
																}    
														mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
														mysql_query ("delete from $ringame");   
														//mysql_query ("UNLOCK TABLES");
														$mmsg = substr($mmsg,0,strlen($mmsg)-2);
														$tm = getmicrotime();
														$today=date ("H:i:s");
														$rnd = rand(0,99999999); 
														mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
														mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
														$mmsg = "За эту игру заработали столько очков: "; 
														$mmes = scores($rm); 
														$mmsg = $mmsg.$mmes;
														$tm = getmicrotime();
														$today=date ("H:i:s");
														$rnd = rand(0,99999999); 
														mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
														mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
														}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if ($vk == "maf")
		{
        $vktr = true;
        mysql_query ("update $rmafaction set action = 'nogame'");
        //mysql_query ("UNLOCK TABLES");  
        //Начисляем очки мафам   
        $r = mysql_query("select role, gamer_id from $ringame");
			while (($a = mysql_fetch_array($r))!==false)
				{
				$role = $a["role"];
				$gamer_id = $a["gamer_id"];
					if ($role == "мафиози"||$role == "главарь мафии") 
						mysql_query("update mafusers set creditsingame = creditsingame + 50 WHERE id = '".$gamer_id."'"); 
				}
        //mysql_query("update mafusers, ingame set mafusers.creditsingame = mafusers.creditsingame + 50 WHERE (mafusers.id = ingame.gamer_id)and((ingame.role='мафиози')or(ingame.role='главарь мафии'))"); //мафам +25
        $mmsg = "Всем хана, победа Мафов! А роли были такие: "; 
        $r = mysql_query("Select * from $ringame");
			while (($a = mysql_fetch_array($r))!==false)
				{  //Какие у кого роли
				$gnick = get_name_by_id($a["id_in_game"], $rm);
				$grole = get_role_by_id($a["id_in_game"], $rm);
				$mmsg = $mmsg."<b>$gnick</b> - $grole, ";
				} 
		$mmsg = substr($mmsg,0,strlen($mmsg)-2);   
        mysql_query("insert into $rscores select gamer_id, creditsingame from $ringame, mafusers WHERE mafusers.id = $ringame.gamer_id");
        mysql_query ("delete from $ringame"); 
        //mysql_query ("UNLOCK TABLES");
        $tm = getmicrotime();
		$today=date ("H:i:s");
        $rnd = rand(0,99999999); 
        mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
        mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
        $mmsg = "За эту игру заработали столько очков: "; 
        $mmes = scores($rm); 
        $mmsg = $mmsg.$mmes;
        $tm = getmicrotime();
        $today=date ("H:i:s");
        $rnd = rand(0,99999999); 
        mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");            
        mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
        }
												}	
		} 
		//конец if ($vktr!==true)
		//Конец проверки
							}
	mysql_query("select * from $ringame WHERE wholin = '-1'");
		if (mysql_affected_rows()>$nm)
			{ //Оправдан                 
			mysql_query("update $rmafaction set action = 'game_night'");
			//mysql_query ("UNLOCK TABLES");
			mysql_query("update $ringame set dvote = '0', wholin = '0', gamer_act = ''"); //Результаты сбрасываем
			$mmsg = "$whk оправдан!";
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999);
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid = '38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");          
			}
					}
						if ($gmes==1&&$action == "game_day"&&$towhom == "38601")
							{ //Ночные похождения
							$r = mysql_query("select * from $ringame WHERE gamer_id = '".$id."'");
							$a = mysql_fetch_array($r); 
							$role = $a ["role"];
							$gamer_act = $a["gamer_act"];   
							$state = $a["state"];
								if ($role!="обыватель"&&$role!="мафиози"&&$role!="клоун"&&$role!="жена комиссара")
									{ //Если это не обыватель и не мафиози
									$s = str_replace("!","",$msg);
									$r2 = mysql_query ("select * from $ringame WHERE id_in_game = '".$s."'");
										if (mysql_affected_rows()==0)
											{ //Нет такого юзера 
											$mmsg = "Что ж ты мне пишешь!?!?"; 
											$tm = getmicrotime();
											$today=date ("H:i:s");
											$rnd = rand(0,99999999);
											mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'"); 
											mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");          
											}
												else
													{ //Есть такой
														if ($gamer_act=="")
															{ //Заказ еще не сделан                      
															$b = mysql_fetch_array($r2);
															$hid = $b["gamer_id"];
															$r3 = mysql_query("select * from mafusers WHERE id = '".$hid."'");
															$c = mysql_fetch_array($r3);
															$gname = $c ["user"];
																unset ($c);
																	unset ($r3); // В $gname ник того, кого выбрали
																		if ($role == "главарь мафии") 
																			{
																			$mmsg = "Заказ на убийство $gname принят!";
																			$rnd = rand(1,3); 
																			$re = mysql_query("select night_act from mafia WHERE klu4 = '".$rnd."'"); 
																			$b = mysql_fetch_array($re); 
																			$mmsg1=$b["night_act"];
																			}
	if ($role == "комиссар катани"&&strpos($msg,"!!")!==false) 
		{
		$mmsg = "Заказ на убийство $gname принят!";
		$s="!".$s;
		$rnd = rand(1,3); 
		$re = mysql_query("select night_act from komissar WHERE klu4 = '".$rnd."'"); 
		$b = mysql_fetch_array($re); 
		$mmsg1=$b["night_act"];
		}
			if ($role == "комиссар катани"&&strpos($msg,"!!")===false) 
				{
				$mmsg = "Заказ на проверку $gname принят!";
				$rnd = rand(1,3); 
				$re = mysql_query("select night_act from komissar WHERE klu4 = '".$rnd."'"); 
				$b = mysql_fetch_array($re); 
				$mmsg1=$b["night_act"];
				}
					if ($role == "доктор") 
						{
						$mmsg = "Заказ на лечение $gname принят!";
						$rnd = rand(1,3); 
						$re = mysql_query("select night_act from doktor WHERE klu4 = '".$rnd."'"); 
						$b = mysql_fetch_array($re); 
						$mmsg1=$b["night_act"];
						}
							if ($role == "маньяк") 
								{
								$mmsg = "Р?знасилуем $gname =)";
								$rnd = rand(1,3); 
								$re = mysql_query("select night_act from maniac WHERE klu4 = '".$rnd."'"); 
								$b = mysql_fetch_array($re); 
								$mmsg1=$b["night_act"];
								}
									if ($role == "путана") 
										{
										$mmsg = "$gname сегодня ночью будет занят)";
										$rnd = rand(1,3); 
										$re = mysql_query("select night_act from wluha WHERE klu4 = '".$rnd."'"); 
										$b = mysql_fetch_array($re); 
										$mmsg1=$b["night_act"];
										}
											if ($role == "Р±РѕРјР¶") 
											{
											$mmsg = "Копаемся в карманах $gname";
											$rnd = rand(1,3); 
											$re = mysql_query("select night_act from bomj WHERE klu4 = '".$rnd."'"); 
											$b = mysql_fetch_array($re); 
											$mmsg1=$b["night_act"];
											}
															mysql_query ("update $ringame set gamer_act='".$s."' WHERE gamer_id = '".$id."'");
															$tm = getmicrotime();
															$today=date ("H:i:s");
															$rnd = rand(0,99999999);
															mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'");
															mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
															$tm = getmicrotime();
															$today=date ("H:i:s");
															$rnd = rand(0,99999999);
															mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1'");  
															mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");         
															}
																else 
																	{   //Заказ уже сделан
																	$mmsg = "Ты уже выбрал жертву!";
																	$tm = getmicrotime();
																	$today=date ("H:i:s");
																	$rnd = rand(0,99999999);
																	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'"); 
																	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");  
																	}
													}
									}
										else 
											if ($role=="клоун"&&$state==0)
												{ //Клоун, и еще не действовал
												$s = str_replace("!","",$msg);
													list($g1,$g2) = explode(" ",$s);
												mysql_query("select gamer_id from $ringame WHERE (id_in_game='".$g1."')or(id_in_game='".$g2."')"); 
													if (mysql_affected_rows()==2)
														{     //Правильно написал  
														mysql_query("update $ringame set gamer_act='".$s."' WHERE gamer_id = '".$id."'");
														$r = mysql_query("select id_in_game from $ringame WHERE id_in_game = '".$g1."'");
														$a = mysql_fetch_array($r);
														$gn1 = get_name_by_id($a["id_in_game"], $rm);
														$r = mysql_query("select id_in_game from $ringame WHERE id_in_game = '".$g2."'");
														$a = mysql_fetch_array($r);
														$gn2 = get_name_by_id($a["id_in_game"], $rm);
														$mmsg = "Меняем ролями $gn1 и $gn2!";
														$mmsg1 = "Клоун ходит ночью по улицам и запутывает и без того сложное дело...";
														$tm = getmicrotime();
														$today=date ("H:i:s");
														$rnd = rand(0,99999999);
														mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'");
														mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
														$tm = getmicrotime();
														$today=date ("H:i:s");
														$rnd = rand(0,99999999);
														mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1'");
														mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'"); 
														//mysql_query("update $ringame set state = '1' WHERE role = 'клоун'");
														}
															else 
																{  //Неправильно  
																$mmsg = "Что ж ты мне пишешь!?!?!?"; 
																$tm = getmicrotime();
																$today=date ("H:i:s");
																$rnd = rand(0,99999999);
																mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'");
																mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");    
																}
												}
													else 
														if ($role=="жена комиссара"&&$state==1)
															{ //Жена комиссара, еще не мстила
															$s = str_replace("!","",$msg);
															$r = mysql_query("select * from $ringame WHERE id_in_game = '".$s."'");
																if (mysql_affected_rows()!=0)
																	{ //Правильно написал    
																	mysql_query("update $ringame set state = '2', gamer_act = '".$s."' WHERE gamer_id = '".$id."'");
																	$a = mysql_fetch_array($r);
																	$gn = get_name_by_id($a["id_in_game"], $rm);
																	$mmsg = "$gn поплатится за смерть комиссара!";
																	$mmsg1 = "Жена комиссара вышла из дома мстить за смерть мужа...";
																	$tm = getmicrotime();
																	$today=date ("H:i:s");
																	$rnd = rand(0,99999999);
																	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'");
																	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");    
																	$tm = getmicrotime();
																	$today=date ("H:i:s");
																	$rnd = rand(0,99999999);
																	mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg1."', id='".$tm."', towhom='', gamemes='1'");
																	mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");    
																	}
																		else
																			{   //Неправильно
																			$mmsg = "Что ж ты мне пишешь!?!?!?"; 
																			$tm = getmicrotime();
																			$today=date ("H:i:s");
																			$rnd = rand(0,99999999);
																			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='".$id."', gamemes='1'");
																			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");             
																			}
															}
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
//Проверка, все ли проголосовали:
	$r = mysql_query ("select count(*) as nv from $ringame WHERE (role != 'обыватель')and(gamer_act='')");  
	$a = mysql_fetch_array($r);
		if ($a["nv"]==0)
			{  //Все уже сделали заказы
			mysql_query("update $rmafaction set action = 'allvoted'"); 
			//mysql_query ("UNLOCK TABLES");
			$mmsg = "Все, что могло свершиться ночью, свершилось.";
			//$tm = time();
			$tm = getmicrotime();
			$today=date ("H:i:s");
			$rnd = rand(0,99999999);
			mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'");  
			mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");      
			}
			//Конец проверки
							}
							
							
								if ($action == "nogame"&&($msg=="!start"||$msg=="!старт"))
									{
									$tm = time()+180;
									mysql_query ("update $rmafaction set action = 'registration', nexttime = '".$tm."'"); 
									//mysql_query ("UNLOCK TABLES");
									$mmsg = "Начинается игра \"Мафия\"! Набор игроков будет продолжаться 3 мин. Для участия введите !reg."; 
									$tm = getmicrotime();
									$today=date ("H:i:s");
									$rnd = rand(0,99999999);
									mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
									mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");          
									}
							
							
										if ($action == "registration"&&($msg=="!reg"||$msg=="!рег"))
											{ 
											//mysql_query ("UNLOCK TABLES");
											mysql_query ("select * from $ringame WHERE gamer_id = '".$id."'");
												if (mysql_affected_rows()==0)
													{
													$mmsg = "$us присоединяется к игре!"; 
													$rnd = rand(10000,99999999);
													$tm = time();
													mysql_query("insert into $ringame set gamer_id = '".$id."', onl = '".$tm."'");
													}
														else
															{
															$mmsg = "$us выходит из игры!";
															mysql_query("delete from $ringame WHERE gamer_id = '".$id."'");
															}
											$tm = getmicrotime();
											$today=date ("H:i:s");
											$rnd = rand(0,99999999);
											mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='1'"); 
											mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");           
											}

//Конец
			}
			}                     
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////
	if ($msg == "!stats"||$msg == "!статс")
		{ //Вывести кол-во очков игрока
		$r = mysql_query("select credits from mafusers WHERE id = '".$id."'");
		$a = mysql_fetch_array($r);
		$cr = $a["credits"];
		$mmsg = "$us, у вас на счету $cr кредитов";   
		$tm = getmicrotime();
		$today=date ("H:i:s");
		$rnd = rand(0,99999999);
		mysql_query ("Insert into $rmaf set klu4= '".$rnd."', time='".$today."', who='Маф', usid='38601', message='".$mmsg."', id='".$tm."', towhom='', gamemes='".$gmes."'");  
		mysql_query ("Update mafusers set posts = posts + 1 WHERE id = '38601'");
		}
	//mysql_query ("UNLOCK TABLES");
	$result = mysql_query ("Select * from mafusers where id_user='$user[id_user]'");    
	$row = mysql_fetch_array ($result);
	$max = $row["max"];    
	$avr = $row["avr"];    
	$time=date ("H:i:s");

		echo "<div class='rekl'>";
	if ($avr!==0) 
		echo "<center color='red'><font color='red'>$time</font></center><br/>\n";
			else 
				echo "<center><font color='red'>$time</font></center><br/>\n";
				echo "Если у вас не работает автообновление, не забывайте обновлять страницу вручную!<br/>";  
				echo "<a href='maf.php?rm=$rm&amp;ref=$ref'>[<font color='red'>Обновить</font>]</a> ";
				echo "<center>";
				echo "<div class='rekl'>";
			echo "<form method='post' action='maf.php?id=$id&amp;rm=$rm&amp;ref=$ref'>";
			echo "<input name=\"msg\" maxlength=\"200\" type=\"text\"/><br/>\n";
			echo "<input type='submit' value='Сказать'>\n";
			echo "</form>";
			echo "</div>";
								echo "</center>";
	echo "<p mode=\"menu\">\n";
		$so=mysql_query("SELECT * FROM $rmaf WHERE towhom = '0' ORDER by time DESC LIMIT 10");
	while ($mess=(mysql_fetch_array($so)))
	{ 
	$date = $mess["time"];
	$name = $mess["who"];
	$usid = $mess["usid"];
	$text = $mess['message'];
	echo "<div class = 'menu'>";
	echo "<br/><b><a href=\"inside.php?id=$id&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a></b>($date)";
	echo' '.vizual($mess['message']).'</div>';
	
	}
		
	$page = abs((int)$_GET['page']);
 
 if($page < 0 || $page > $so) $page = 0;
 
 if ($so < $page + 10) $end = $so;
 else $end = $so + 10;
strpage($page, 10, $so, '');	
 
$usmess=mysql_query("SELECT * FROM $rmaf ORDER by id DESC LIMIT $start, $max");
while ($usmes=(mysql_fetch_array($usmess)))
{
$kol = mysql_affected_rows();
$total=$kol-1;
$ignor = $row["ignor"];  
$i = 0;
		
		
		
		
		
		
	
	
		
		//$tm = getmicrotime();
		//echo "$tm";
		
		
				//Автоантифлуд                    
				$time = time()-30;
				mysql_query("select * from $rmaf WHERE usid = '".$id."'and id >'".$time."'");
					if (mysql_affected_rows()>5&&$row["level"]<4)
						{
						$kik = time()+60;
						$whokik = "[Система]";
						$whykik = "Флуд"; 
						mysql_query("update mafusers set kik = '".$kik."', whokik = '".$whokik."', whykik = '".$whykik."' WHERE id = '".$id."'");
						}
						//Конец автоантифлуда
				$i++;
				$date = $usmes["time"];
				$name = $usmes["who"];
				$usid = $usmes["usid"];
				$msg = $usmes["message"];     
				$time = $usmes["id"];
				$th = $usmes["towhom"];      
				$gm = $usmes["gamemes"];
				
					if ((strpos($ignor, $name."|") === false)&&($gmes==0||($gmes==1&&$gm==1)))
						{
							if ($th == "0") 
								{
								echo "<br/><b><a href=\"inside.php?id=$id&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a></b>($date)&gt;".trim(smiles($msg))."<hr/>\n";
								}
									else 
										if (($th == $id)||($id == $usid))
											{ 
											echo "<br/><b><a href=\"inside.php?id=$id&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a>[P!]</b>($date)&gt;<font color='red'>".trim(smiles($msg))."</font><hr/>\n";}
						}
						
				
				}
			 // Вывод страниц
				echo "<br/><a href='help.php?rm=$rm&amp;ref=$ref'>[Помощь]</a><br/>";
				echo "<a href='who.php?rm=$rm&amp;ref=$ref'>[Кто здесь?]</a><br/> ";
				echo "<a href='change.php?rm=$rm&amp;ref=$ref'>[Настройки]</a><br/> ";
				echo "<a href='index.php'>[Выход]</a> <hr/>";
	
	
echo "</div>";	
require"../system/foot.php";
?>