Просмотр файла maf.php

Размер файла: 111.15Kb
<?

$phphp="d2FwbWFmaWEuY29tDQo=";

$phphp_b=base64_decode($phphp);

$ip = getenv('HTTP_HOST');

header("Cache-Control: no-cache");

header("Content-type:text/vnd.wap.wml");  

$ref=rand(10000,1000000);

require("inc.php");



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

{ 

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

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

}



$link = @mysql_pconnect ($MySQL_Hostname, $MySQL_Username, $MySQL_Password)

                or die ("<wml>

<card id=\"error\" title=\"error\">

<do type=\"prev\" label=\"Back\"><prev/></do><p align=\"center\">Can not connect to MySQL</p>

</card>

</wml>");

     

     @mysql_select_db($MySQLDatabasename) or die ("<wml>

<card id=\"error\" title=\"error\">

<do type=\"prev\" label=\"Back\"><prev/></do><p align=\"center\">error select the database...</p>

</card>

</wml>");



if(isset($us)){

$us=trim($us);       

if($us==""){          

          echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<card id=\"error\" title=\"error\" ontimer=\"index.php?ref=$ref\"><timer value=\"15\"/>\n";

echo "<p align=\"center\">\n";

echo "User was not found\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close ($link);

exit;          

}

}       

       



  if(isset($id)){

        $result = @mysql_query ("Select * from mafusers where id='".$id."'");    

        } else {

                 function rus_to_k($str){

                $str = str_replace("Р°","a",$str); 

                $str = str_replace("Р±","b",$str);

                $str = str_replace("РІ","v",$str);

                $str = str_replace("Рі","g",$str);

                $str = str_replace("Рґ","d",$str);

                $str = str_replace("Рµ","e",$str); 

                $str = str_replace("С‘","e",$str); 

                $str = str_replace("Р¶","j",$str);

                $str = str_replace("Р·","z",$str);

                $str = str_replace("Рё","i",$str);

                $str = str_replace("Р№","y",$str);

                $str = str_replace("Рє","k",$str);

                $str = str_replace("Р»","l",$str); 

                $str = str_replace("Рј","m",$str);

                $str = str_replace("РЅ","n",$str);

                $str = str_replace("Рѕ","o",$str);

                $str = str_replace("Рї","p",$str);

                $str = str_replace("СЂ","r",$str);

                $str = str_replace("СЃ","s",$str); 

                $str = str_replace("С‚","t",$str);

                $str = str_replace("Сѓ","u",$str);

                $str = str_replace("С„","f",$str);

                $str = str_replace("С…","h",$str);

                $str = str_replace("С‡","c",$str);

                $str = str_replace("С†","q",$str);//ч 

                $str = str_replace("С€","w",$str);

                $str = str_replace("С‰",">",$str);//щ

                $str = str_replace("СЊ","<",$str);//ъ

                $str = str_replace("С‹","x",$str);//ы

                $str = str_replace("СЉ",".",$str);//ь

                $str = str_replace("СЌ",":",$str);//э 

                $str = str_replace("СЋ",";",$str);//ю

                $str = str_replace("СЏ","}",$str);//я

                $str = str_replace("Рђ","a",$str);

                $str = str_replace("Р‘","b",$str);

                $str = str_replace("Р’","v",$str);

                $str = str_replace("Р“","g",$str); 

                $str = str_replace("Р”","d",$str);

                $str = str_replace("Р•","e",$str);

                $str = str_replace("РЃ","e",$str);

                $str = str_replace("Р–","j",$str);

                $str = str_replace("Р—","z",$str);

                $str = str_replace("Р?","i",$str); 

                $str = str_replace("Р™","y",$str);

                $str = str_replace("Рљ","k",$str);

                $str = str_replace("Р›","l",$str);

                $str = str_replace("Рњ","m",$str);

                $str = str_replace("Рќ","n",$str);

                $str = str_replace("Рћ","o",$str); 

                $str = str_replace("Рџ","p",$str);

                $str = str_replace("Р ","r",$str);

                $str = str_replace("РЎ","s",$str);

                $str = str_replace("Рў","t",$str);

                $str = str_replace("РЈ","u",$str);

                $str = str_replace("Р¤","f",$str);

                $str = str_replace("РҐ","h",$str);

                $str = str_replace("Р§","c",$str);

                $str = str_replace("Р¦","q",$str);

                $str = str_replace("РЁ","w",$str); 

                $str = str_replace("Р©",">",$str);

                $str = str_replace("Р¬","<",$str);

                $str = str_replace("Р«","x",$str);

                $str = str_replace("РЄ",".",$str);

                $str = str_replace("Р­",":",$str);

                $str = str_replace("Р®",";",$str);

                $str = str_replace("РЇ","}",$str);

                return $str;

                }

        

    $latuser=strtolower($us);

    $ruser = rus_to_k($us);

    if($ruser==$us){

   $result = mysql_query ("Select * from mafusers where latuser = '".$latuser."'"); 

    } else {

   $result = mysql_query ("select * from mafusers where ruser = '".$ruser."'");

    }

    }      



         

         if (mysql_affected_rows() == 0) {

          echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<card id=\"error\" title=\"&#x041E;&#x0448;&#x0438;&#x0431;&#x043A;&#x0430;\" ontimer=\"index.php?ref=$ref\"><timer value=\"15\"/>\n";

echo "<p align=\"center\">\n";

echo "User was not found\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close($link);

exit;

}

                

$row = mysql_fetch_array ($result);

$id = $row["id"];

if ($ps !== $row["pass"]){

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<card id=\"error\" title=\"&#x041E;&#x0448;&#x0438;&#x0431;&#x043A;&#x0430;\" ontimer=\"index.php?ref=$ref\"><timer value=\"15\"/>\n";

echo "<p align=\"center\">\n";

echo "Your login failed\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close($link);   

exit;

}           

$us=$row["user"];

$smset = $row["smiles"];  



if ($row["kik"]==20){

mysql_query ("UPDATE mafusers SET kik = '0' WHERE id = '".$id."'");

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>\n";

echo "<card id=\"pwel\" title=\"Простите, но...\">\n";

$nick = $row["whokik"];

echo "<p align =\"center\">Сисадмин $nick<br/><br/>\n";

echo "<img src=\"smile/sysadm.gif\" alt=\"wait...\"/>\n";

echo "<br/>не любит глупые вопросы...\n";

echo "<br/><a href=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\">&#x0412; &#x0447;&#x0430;&#x0442;</a><br/>\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close($link);

exit;

}

 



   if ($row["user_soft"]!==$HTTP_USER_AGENT){ 

  mysql_query ("Update mafusers set user_soft='".$HTTP_USER_AGENT."', user_ip = '".$REMOTE_ADDR."' WHERE id = '".$id."'");

                                             }



  mysql_query ("Select * from bannlist WHERE (ip = '".$REMOTE_ADDR."')and(soft = '".$HTTP_USER_AGENT."')");

  if (mysql_affected_rows()!=0) {

  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>\n";

echo "<card id=\"ban\" title=\"Стоп!\" ontimer=\"index.php?ref=$ref\"><timer value=\"300\"/>\n";

echo "<p align=\"center\">\n";

echo "Вы забанены по связке ip+soft!!!<br/>\n";

echo "Р? доступ вам разрешен только РІ  <a href=\"chat.php?id=$id&amp;ps=$ps&amp;rm=9&amp;rul=9&amp;ref=$ref\">Сортир</a>\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close($link);

exit;

}   



     if (time()<$row["kik"]){

  echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

echo "<head><meta http-equiv=\"Cache-Control\" content=\"no-cache\" forua=\"true\"/></head>\n";

echo "<card id=\"vypnut\" title=\"Стоп!\" ontimer=\"index.php?ref=$ref\"><timer value=\"300\"/>\n";

echo "<p align=\"center\">\n";

$tleft = $row["kik"] - time();

$whokik = $row["whokik"];

$whykik = $row["whykik"];

echo "$whokik выпнул вас из игры. Разбан через $tleft (сек)<br/>\n";

echo "Причина: $whykik<br/>\n";

//echo "А пока вам разрешен доступ только в <a href=\"chat.php?id=$id&amp;ps=$ps&amp;rm=9&amp;rul=9&amp;ref=$ref\">Сортир</a>\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n";

mysql_close($link);

exit;

}   

if ($rm!=1&&$rm!=2&&$rm!=3) $rm = 1; 

$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");

   $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");

        $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");

        $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");

           $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");

        $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");

        $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");

        $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");

        $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");

$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");

        $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");

$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");

$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");

$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");

$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");

$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");

$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");

$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");

$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");

                                                                                                                                                                                             $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");

//$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");

           $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");

       $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");

       $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");

$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");

   $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");

   $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");

        $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");

        $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");

           $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");

        $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");

        $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");

        $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");

        $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");

$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");

$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");

$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");

$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 = str_replace("", "", $msg);

$msg = str_replace("", "", $msg); 

$msg = str_replace("", "", $msg); 

$msg = str_replace("", "", $msg); 

$msg = str_replace("", "", $msg); 

$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 = "";

if (!isset($towhom)) $towhom = "";



require("smile.php");



//$msg_wosm = $msg;

//$msg_woasm = $msg;

   

$minpos = 500; $nm = 500;

for ($j=0;$j<=count($smiles)-1;$j++){   

$tmpp = strpos($msg,$smiles[$j]);

if (($tmpp < $minpos)&&($tmpp !== false)){ 

$minpos = $tmpp; $nm = $j;};

                     };         

if ($minpos !=500){

if ($row["translit"]!=1){

$st1 = substr($msg,0,$minpos+strlen($smiles[$nm]));

$st2 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1));

$st1_wosm = $st1; 

$st1 = str_replace($smiles[$nm],$replaces[$nm],$st1);

if (strpos($replaces[$nm],"smilean/")!==false) $st1_woasm = $st1_wosm; else $st1_woasm = $st1;     

$msg_woasm = $st1.$st2;  

$msg_wosm = $st1_wosm.$st2; 

$msg = $st1_woasm.$st2;

} else {

$st1 = substr($msg,0,$minpos);

$st2 = substr($msg,$minpos, strlen($smiles[$nm]));

$st3 = substr($msg,$minpos+strlen($smiles[$nm]),strlen($msg)-strlen($st1)-strlen($st2));

$st1 = trun_to_rus($st1);

$st2_wosm = $st2;

$st2 = $replaces[$nm];    



if (strpos($replaces[$nm],"smilean/")!==false) $st2_woasm = $st2_wosm; else $st2_woasm = $st2;



$st3 = trun_to_rus($st3);

$msg = $st1.$st2_woasm.$st3;

$msg_wosm = $st1.$st2_wosm.$st3; 

$msg_woasm = $st1.$st2.$st3;

}

} 

else if ($row["translit"]==1) $msg = trun_to_rus($msg);          

Unset($smiles);

unset($replaces);   



if ($row["translit"]==0) $msg = eregi_replace("((http://))((([a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z;]{2,3}))|(([0-9]{1,3}\.){3}([0-9]{1,3})))((/|\?)[a-z0-9~#%&'_\+=:;\?\.-]*)*)", "<a href=\"\\0\">\\3</a>", $msg);

$msg = $str1.$msg;

if ($msg_wosm!="") $msg_wosm = $str1.$msg_wosm;

if ($msg_woasm!="") $msg_woasm = $str1.$msg_woasm;

//Антифлуд

$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");

$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."', messagewosm = '".$msg_wosm."', messagewoasm = '".$msg_woasm."', id='".$time."', towhom='".$towhom."', hid='".$hid."', usid='".$id."', gamemes = '".$gmes."'");           

$usmes["time"] = $today; 

$usmes["who"] = $us;

$usmes["usid"] = $id;

$usmes["message"] = $msg; 

$usmes["messagewosm"] = $msg_wosm;

$usmes["messagewoasm"] = $msg_woasm;

$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");

   $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");

$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");

$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");

$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");

        $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");

        $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");

           $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");

        $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");

        $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");

        $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");

        $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");

$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");

$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");

$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");

$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");

        $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");

    $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");

    $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");

           $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");

           $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");

           $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");

                 $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");

   $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");

$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");

$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");

 $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");

$max = $row["max"];    

$avr = $row["avr"];    

$time=date ("H:i");

echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";

echo "<!DOCTYPE wml PUBLIC \"-//WAPFORUM//DTD WML 1.2//EN\" \"http://www.wapforum.org/DTD/wml12.dtd\">\n";

echo "<wml>\n";

if ($avr!==0) echo "<card id=\"maf\" title=\"$topic-$time\" ontimer=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\"><timer value=\"$avr\"/>\n";

else echo "<card id=\"maf\" title=\"$topic-$time\" >\n";

echo "<do type=\"options\" name=\"refresh\" label=\"Обновить\"><go href=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\"/></do>\n";

echo "<do type=\"options\" name=\"add\" label=\"Сказать\"><go href=\"#add\"/></do>\n";  

if ($row["level"]>5) echo "<do type=\"options\" name=\"topic\" label=\"РўРѕРїРёРє\"><go href=\"topic.php?id=$id&amp;ps=$ps&amp;rm=$rm\"/></do>\n"; 

echo "<do type=\"options\" name=\"help\" label=\"Помощь!!!\"><go href=\"help.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\"/></do>\n";

echo "<do type=\"options\" name=\"who\" label=\"Кто здесь?\"><go href=\"who.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\"/></do>\n";

echo "<do type=\"options\" name=\"nastr\" label=\"Настройки\"><go href=\"nastr.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\"/></do>\n";

echo "<do type=\"options\" name=\"exit\" label=\"Выйти\"><go href=\"enter.php?id=$id&amp;ps=$ps&amp;ref=$ref\"/></do>\n";

echo "<p mode=\"wrap\">\n";

echo "<a href=\"#add\">Сказать</a><br/>\n";

echo "<a href=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\">Обновить</a>\n";

 

@$total=$kol-1;

$ignor = $row["ignor"];  

$mread = 0;

$i = 0;



//$tm = getmicrotime();

//echo "$tm";



if ($smthwr != 0){



 //Автоантифлуд                  

 $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"];     

 if ($smset==0&&$usmes["messagewosm"]!="") $msg = $usmes["messagewosm"];

 if ($smset==2&&$usmes["messagewoasm"]!="") $msg = $usmes["messagewoasm"];

 $time = $usmes["id"];

 $th = $usmes["towhom"];      

 $gm = $usmes["gamemes"];

 if ((strpos($ignor, $name."|") === false)&&($gmes==0||($gmes==1&&$gm==1))){

 if ($th == "") {

 echo "<br/><b><a href=\"inside.php?id=$id&amp;ps=$ps&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a></b>($date)&gt;$msg\n"; $mread++;}

else if (($th == $id)||($id == $usid)){ 

echo "<br/><b><a href=\"inside.php?id=$id&amp;ps=$ps&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a>[P!]</b>($date)&gt;$msg\n";$mread++;}

                                                          }    



 }

 

while (($mread < $max)&&($i<$total)){

$lines = mysql_fetch_array ($res);



$date = $lines["time"];

$name = $lines["who"];

$usid = $lines["usid"];

$msg = $lines["message"];

$gm = $lines["gamemes"];

if ($smset==0&&$lines["messagewosm"]!="") $msg = $lines["messagewosm"];

if ($smset==2&&$lines["messagewoasm"]!="") $msg = $lines["messagewoasm"];

$time = $lines["id"];

$th = $lines["towhom"]; 

$hid = $lines["hid"];

$i++;

if ((strpos($ignor, $name."|") === false)&&(($hid != 2)||($id == $usid))&&($gmes==0||($gmes==1&&$gm==1))){

if ($th == "") {

echo "<br/><b><a href=\"inside.php?id=$id&amp;ps=$ps&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a></b>($date)&gt;$msg\n"; $mread++;}

else if (($th == $id)||($id == $usid)){ 

echo "<br/><b><a href=\"inside.php?id=$id&amp;ps=$ps&amp;nk=$usid&amp;rm=$rm&amp;ref=$ref\">$name</a>[P!]</b>($date)&gt;$msg\n";$mread++;}

}    

}

mysql_close ($link);

$page_next = $max;

if ($max < $total)

{

echo "<br/><a href=\"mafhist.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;num=$page_next\">Р?стория</a>\n";

} 

echo "<br/><a href=\"enter.php?id=$id&amp;ps=$ps&amp;ref=$ref\">Выйти</a><br/>\n";

echo "</p>\n";

echo "</card>\n";

echo "<card id=\"add\" title=\"&#x041D;&#x0430;&#x043F;&#x0438;&#x0441;&#x0430;&#x0442;&#x044C;\">\n";

echo "<p mode=\"wrap\">\n"; 

echo "<input name=\"msg$ref\" maxlength=\"200\" title=\"Text\"/><br/>\n";

echo "<anchor title=\"send\">Сказать<go href=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\" method=\"post\">\n";

echo "<postfield name=\"msg\" value=\"$(msg$ref)\"/>\n";

echo "</go></anchor>\n";

echo "<br/>\n";

echo "<a href=\"maf.php?id=$id&amp;ps=$ps&amp;rm=$rm&amp;ref=$ref\">К мафу</a>\n";

echo "</p>\n";

echo "</card>\n";

echo "</wml>\n"; 



?>