Advertisement
KeplerBR

[Plugin 4fun] Adedonha (PT-BR)

Feb 19th, 2013
251
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 12.51 KB | None | 0 0
  1. # Plugin para jogar adedonha no Ragnarok
  2. # by KeplerBR
  3.  
  4. package adedonha;
  5.     use strict;
  6.     use warnings;
  7.     use Plugins;
  8.     use Globals;
  9.     use Skill;
  10.     use Misc qw(look center);
  11.     use Log qw(message);
  12.     use Commands;
  13.     use DBI;
  14.    
  15.     # Register Plugin and Hooks
  16.     Plugins::register("adedonha", "Adedonha no Ragnarok!", \&on_unload);
  17.         my $hooks = Plugins::addHooks(
  18.             ['start3', \&start],
  19.             ['packet/received_sync', \&inform],
  20.             ['packet_privMsg', \&informPM],
  21.             ['packet/map_loaded', \&startGame],
  22.             #['packet_pubMsg', \&analyzeResponse],
  23.         );
  24.  
  25.     my $commandAdedonha = Commands::register(
  26.         ["inform", "Informa o placar e respostas recentementes usadas", \&commandInform]
  27.     );
  28.  
  29. my $currentLetter;
  30. my $inform = 0;
  31. my $alert = 0;
  32. my $gameType = 0;
  33. my @listGameType = ('ITEM', 'SKILL', 'MONSTRO');
  34. my (@recentLetters, @monsterList, @skillList, %scoreboard, %listItens, %recentAnswers, %nickListTime, %alphabet);
  35.  
  36. # Database info
  37. my $hostname= "127.0.0.1";
  38. my $port = 3306;
  39. my $user = "ragnarok";
  40. my $password = "ragnarok";
  41. my $database = "ragna4fun";
  42. my $dsn = "DBI:mysql:database=$database;host=$hostname;port=$port;mysql_enable_utf8=1";
  43. my $dbh = DBI->connect($dsn, $user, $password); # Connect to the database
  44. my $datadir = $Plugins::current_plugin_folder;
  45.  
  46.     ################################
  47.     #On Unload code
  48.     sub on_unload {
  49.         Plugins::delHooks($hooks);
  50.         Commands::unregister($commandAdedonha);
  51.     }
  52.  
  53.     ################################
  54.     # Carregar lista de palavras e placar
  55.     sub start {
  56.         # Carregar palavras
  57.         for (keys %items_lut) {
  58.             $items_lut{$_} = lc($items_lut{$_});
  59.         }
  60.         %listItens = reverse %items_lut;
  61.  
  62.         open my $fileListMonster,"<" . $datadir . '\listMonster.txt' or die $!;
  63.             while (<$fileListMonster>) {
  64.                 my $line = $_;
  65.                 $line =~ s/\R//g;
  66.                 push (@monsterList, lc($line));
  67.             }
  68.         close $fileListMonster;
  69.  
  70.         open my $fileListSkill,"<" . $datadir . '\listSkill.txt' or die $!;
  71.             while (<$fileListSkill>) {
  72.                 my $line = $_;
  73.                 $line =~ s/\R//g;
  74.                 push (@skillList, lc($line));
  75.             }
  76.         close $fileListSkill;
  77.  
  78.         # Listar alfabeto
  79.         if ($config{alphabet}) {
  80.             %alphabet = (
  81.                 0  => 'a',  1  => 'b',  2  => 'c',  3  => 'd',  4  => 'e',  5  => 'f',  6  => 'g',  7  => 'h', 8  => 'i',
  82.                 9  => 'j',  10 => 'l',  11 => 'm',  12 => 'n',  13 => 'o',  14 => 'p',  15 => 'q',  16 => 'r', 17 => 's',
  83.                 18 => 't',  19 => 'u',  20 => 'v',  21 => 'z',
  84.             );
  85.         } else {
  86.             %alphabet = (
  87.                 0  => 'a',  1  => 'b',  2  => 'c',  3  => 'd',  4  => 'e',  5  => 'f',  6  => 'g',  7  => 'h', 8  => 'i',
  88.                 9  => 'j',  10 => 'k',  11 => 'l',  12 => 'm',  13 => 'n',  14 => 'o',  15 => 'p',  16 => 'q', 17 => 'r',
  89.                 18 => 's',  19 => 't',  20 => 'u',  21 => 'v',  22 => 'x',  23 => 'w',  24 => 'y',  25 => 'z',
  90.             );
  91.         }      
  92.        
  93.         # Carregar placar
  94.         my $sth = $dbh->prepare("SELECT * FROM $config{table}");
  95.         $sth->execute();
  96.         while (my $ref = $sth->fetchrow_hashref()) {
  97.             $scoreboard{$ref->{nick}} = $ref->{points};
  98.         }
  99.         $sth->finish();
  100.     }
  101.  
  102.     ################################
  103.     # Iniciar partida de adedonha
  104.     sub startGame {
  105.         look(3, 2);
  106.        
  107.         # Anti-bug
  108.         return if ($currentLetter);
  109.        
  110.         randLetter:
  111.         # Pegar letra
  112.         my $alphabetCount = scalar keys %alphabet;
  113.         my $chooseLetter = int(rand($alphabetCount));
  114.         $currentLetter = $alphabet{$chooseLetter};
  115.  
  116.         # Evitar usar letras que tenham sido usadas recentementes
  117.         if ($currentLetter ~~ @recentLetters) {
  118.             goto randLetter;
  119.         } else {
  120.             @recentLetters = () if (scalar @recentLetters == $alphabetCount - 1);
  121.             push (@recentLetters, $currentLetter);
  122.            
  123.             # Selecionar tipo de jogo
  124.             $gameType++;
  125.             $gameType = 0 if ($gameType >= scalar @listGameType);
  126.             $recentAnswers{$gameType}{$currentLetter} = '' if (!exists $recentAnswers{$gameType}{$currentLetter});
  127.  
  128.             # Adicionar hook
  129.             $hooks = Plugins::addHooks(
  130.                 ['packet_pubMsg', \&analyzeResponse],
  131.             );
  132.                    
  133.             # Informar
  134.             Commands::run("c Letra do adedonha: '" . uc($currentLetter) . "' ! Envie PM para ver o placar e como jogar!");
  135.             Commands::run("c Informe um(a) " . $listGameType[$gameType] . " do Ragnarok que comece com a letra '" . uc($currentLetter) . "' !");
  136.             Commands::run("e heh") if $config{sendEmoticon};
  137.         }
  138.     }
  139.  
  140.     ################################
  141.     # Verificar se mensagem global corresponde a adedonha
  142.     sub analyzeResponse {
  143.         my $hookname = shift;
  144.         my $args = shift;
  145.  
  146.         # Verificar se resposta esta certa
  147.         my $nickPlayer = $args->{pubMsgUser};
  148.         my $chatMessage = lc($args->{Msg});
  149.         my $initialLetter = substr($chatMessage, 0, 1);
  150.  
  151.         if ($chatMessage eq "jogo") {
  152.             Commands::run("c Informe um(a) " . $listGameType[$gameType] . " que comece com a letra " . uc($currentLetter) . "!");
  153.             $inform = 0;
  154.             return;
  155.         }
  156.        
  157.         my $currentAnalysis = $currentLetter;
  158.         $currentAnalysis = "/ã|á|à|â|a|/i" if ($currentLetter eq 'a');  $currentAnalysis = "/é|è|ê|e|/i" if ($currentLetter eq 'e');
  159.         $currentAnalysis = "/í|ì|î|i|/i" if ($currentLetter eq 'i'); $currentAnalysis = "/õ|ó|ò|ô|o|/i" if ($currentLetter eq 'o');
  160.         $currentAnalysis = "/ú|ù|ô|u|/i" if ($currentLetter eq 'u');
  161.         if ($initialLetter =~ $currentAnalysis) {
  162.             if (($listGameType[$gameType] eq "ITEM" && exists $listItens{$chatMessage}) ||
  163.                 ($listGameType[$gameType] eq "SKILL" &&  $chatMessage ~~ @skillList) ||
  164.                 ($listGameType[$gameType] eq "MONSTRO" && $chatMessage ~~ @monsterList)) {
  165.                 if ($recentAnswers{$gameType}{$currentLetter} ne $chatMessage) {
  166.                     # Acertou
  167.                     &saveScores($nickPlayer, 2);
  168.                                        
  169.                     Commands::run("c Parabéns, $nickPlayer! Acertou! Sua pontuação é de $scoreboard{$nickPlayer} pontos!");
  170.                     Commands::run("e e11") if $config{sendEmoticon};
  171.                     $recentAnswers{$gameType}{$currentLetter} = $chatMessage;
  172.  
  173.                     # Iniciar nova partida
  174.                     undef $currentLetter;
  175.                     Plugins::delHook('packet_pubMsg', $hooks);
  176.                     unless ($taskManager->countTasksByName('pluginAdedonhaRecomeçar')) {
  177.                         $taskManager->add(Task::Timeout->new(
  178.                         name => 'pluginAdedonhaRecomeçar',
  179.                         inGame => 1,
  180.                         function => sub {&startGame;},
  181.                         seconds => 4,
  182.                         ));
  183.                     }
  184.                 } else {
  185.                     # Resposta repetida
  186.                     Commands::run("c '$chatMessage' já foi usado! Não pode repetir a mesma palavrava 2x seguidas!");
  187.                     Commands::run("e ??") if $config{sendEmoticon};
  188.                 }
  189.             } else {
  190.                 # Repetiu a palavra
  191.                 exists $scoreboard{$nickPlayer} ?
  192.                     Commands::run("c $nickPlayer, '$chatMessage' não é um(a) $listGameType[$gameType]! (Você tem $scoreboard{$nickPlayer} pontos)") :
  193.                     Commands::run("c $nickPlayer, '$chatMessage' não é um(a) $listGameType[$gameType]!");
  194.                 Commands::run("e ??") if $config{sendEmoticon};
  195.             }
  196.             $inform = 0;
  197.         } else {
  198.             # Errou a letra inicial
  199.             $alert++;
  200.             if ($alert == 3) { # Evitar flood
  201.                 Commands::run("c O(A) $listGameType[$gameType] deve começar com a letra '" . uc($currentLetter) . "'!");
  202.                 Commands::run("e !") if $config{sendEmoticon};
  203.                 $alert = 0;
  204.                 $inform = 0;
  205.             }
  206.         }
  207.     }
  208.  
  209.     ################################
  210.     # Misc: Salvar pontos dos players
  211.     sub saveScores {
  212.         my ($nickPlayer, $pointsEarned) = @_;
  213.  
  214.         if (exists $scoreboard{$nickPlayer}) {
  215.             # Atualizar placar
  216.             $scoreboard{$nickPlayer} += $pointsEarned;
  217.            
  218.             my $sth = $dbh->prepare("UPDATE $config{table} SET points = ? WHERE nick = ?")
  219.                 or die "Couldn't prepare statement";
  220.             $sth->execute($scoreboard{$nickPlayer}, $nickPlayer)
  221.                 or die "Couldn't execute the query";
  222.             $sth->finish;
  223.         } else {
  224.             # Adicionar player
  225.             $scoreboard{$nickPlayer} = $pointsEarned;
  226.            
  227.             my $sth = $dbh->prepare("INSERT into $config{table}(nick, points) values(?,?)")
  228.                 or die "Couldn't prepare statement";
  229.             $sth->execute($nickPlayer, $scoreboard{$nickPlayer})
  230.                 or die "Couldn't execute the query";
  231.             $sth->finish;
  232.         }
  233.     }
  234.    
  235.     ################################
  236.     # Informar da partida de adedonha
  237.     sub inform {
  238.         $inform++;
  239.         if ($inform == 3) { # Evitar flood
  240.             Commands::run("c Jogue adedonha no Ragnarok! Mande PM para mim para ver o placar ou instruções!");
  241.             Commands::run("c Informe, pelo chat público, um(a) " . $listGameType[$gameType] . " do Ragnarok que comece com '" . uc($currentLetter) . "'!");
  242.             $inform = 0;
  243.             }
  244.     }
  245.    
  246.     ################################
  247.     # Ao receber uma PM, irá da umas infos
  248.     sub informPM {
  249.         my $hookname = shift;
  250.         my $args = shift;
  251.         my $nick = $args->{privMsgUser};
  252.         my $message = $args->{privMsg};
  253.        
  254.         # Anti-Spam
  255.         if ((time - $nickListTime{$nick}) < 10) {
  256.             Commands::run("pm \"$nick\" Desculpe-me, você mandou PM a pouco tempo! Tente daqui a 10s!");
  257.             return;
  258.         }
  259.         $nickListTime{$nick} = time;
  260.  
  261.         # Analisando PM
  262.         if ($message =~ /placar completo/i) {
  263.             my $i = 0;
  264.             for ( sort {$scoreboard{$b} <=> $scoreboard{$a}} keys %scoreboard) {
  265.                 $i++;
  266.                 last if (!$_);
  267.                 Commands::run("pm \"$nick\" * $i° - $_ - $scoreboard{$_} pontos");
  268.                 last if ($i == 100);
  269.             }
  270.         } elsif ($message =~ /comentário:/i || $message =~ /comentario:/i) {
  271.             # Anti-flood
  272.             my $sth = $dbh->prepare("SELECT * FROM adedonha_comment WHERE nick = ?")
  273.                 or die "Couldn't prepare statement";
  274.             $sth->execute($nick)
  275.                 or die "Couldn't execute the query";
  276.             $sth->finish;
  277.            
  278.             if ($sth->rows < 2) {
  279.                 $message =~ s/comentário://i;
  280.                 my $sth = $dbh->prepare("INSERT into adedonha_comment(server, nick, comment) value(?,?,?)")
  281.                     or die "Couldn't prepare statement";
  282.                 $sth->execute($config{master}, $nick, $message)
  283.                     or die "Couldn't execute the query";
  284.                 $sth->finish;
  285.                
  286.                 Commands::run("pm \"$nick\" Obrigado, $nick! Seu comentário foi enviado com sucesso! Irei lê-lo depois.");
  287.             } else {
  288.                 Commands::run("pm \"$nick\" Desculpe, $nick, mas não é possível enviar mais que 2 comentários por personagem...");
  289.             }
  290.         } elsif ($scoreboard{$message}) {
  291.             my $i = 0;
  292.             for (sort {$scoreboard{$b} <=> $scoreboard{$a}} keys %scoreboard) {
  293.                 $i++;
  294.                 last if ($_ eq $message);
  295.             }
  296.             Commands::run("pm \"$nick\" $message tem $scoreboard{$message} pontos e esta em $i° lugar!");
  297.         } else {
  298.             Commands::run("pm \"$nick\" Para participar da adedonha, basta você mandar MENSAGEM PÚBLICA (NÃO por PM, é por MENSAGEM PÚBLICA) com um nome do que é pedido!");
  299.             Commands::run("pm \"$nick\" Pode ser uma skill, um item ou um montro! Atualmente é " . $listGameType[$gameType] . " que comece com a letra informada '" . uc($currentLetter) . "'!");
  300.             Commands::run("pm \"$nick\" -------------------");
  301.             Commands::run("pm \"$nick\" Dica: Envie, pelo chat público (NÃO por PM):");
  302.             Commands::run("pm \"$nick\" * 'jogo' -> para exibir a letra inicial do que deve dizer");
  303.             Commands::run("pm \"$nick\" -------------------");
  304.             Commands::run("pm \"$nick\" Placar dos 15 primeiros lugares:");
  305.  
  306.             my $i = 0;
  307.             for ( sort {$scoreboard{$b} <=> $scoreboard{$a}} keys %scoreboard) {
  308.                 $i++;
  309.                 last if (!$_);
  310.                 Commands::run("pm \"$nick\" * $i° - $_ - $scoreboard{$_} pontos");
  311.                 last if ($i == 15);
  312.             }
  313.            
  314.             Commands::run("pm \"$nick\" Total de jogadores: " . scalar (keys %scoreboard));
  315.             Commands::run("pm \"$nick\" -------------------");
  316.             Commands::run("pm \"$nick\" Se quiser me enviar um comentário, mande PM com o texto e escrito 'Comentário:'");
  317.             Commands::run("pm \"$nick\" Exemplo: 'Comentário: Adedonha é muito legal =)'");
  318.             Commands::run("pm \"$nick\" -------------------");
  319.             Commands::run("pm \"$nick\" Para visualizar a pontuação específica de um jogador, envie, por PM, o nick dele");
  320.             Commands::run("pm \"$nick\" Para visualizar os 100 primeiros lugares, envie, por PM, 'placar completo'!");
  321.         }
  322.     }
  323.  
  324.     ################################
  325.     # Função do comando "inform"
  326.     sub commandInform {
  327.         my $message;
  328.  
  329.         $message = center('Placar atual', 50, '-') . "\n";
  330.        
  331.         my $i = 0;
  332.         for ( sort {$scoreboard{$b} <=> $scoreboard{$a}} keys %scoreboard) {
  333.             $i++;
  334.             $message .= "* $i° - $_ - $scoreboard{$_} pontos\n";
  335.             last if ($i == 50);
  336.         }
  337.  
  338.         $message .= "Total: " . scalar (keys %scoreboard) . "\n";
  339.  
  340.         $message .= center('Informações da Adedonha atual', 50, '-') . "\n";
  341.  
  342.         $message .= "Respostas recentementes usadas:\n";
  343.         for (my $i = 0; $i < scalar @listGameType; $i++) {
  344.             $message .= center($listGameType[$i], 10, '-') . "\n";
  345.             my $size = $recentAnswers{$i};
  346.             for (my $i2 = 0; $i2 < scalar (keys %alphabet); $i2++) {
  347.                 next if (!$recentAnswers{$i}{$alphabet{$i2}});
  348.                 $message .= "* $alphabet{$i2} - $recentAnswers{$i}{$alphabet{$i2}}\n";
  349.             }
  350.         }
  351.  
  352.         $message .= "Jogo Atual: " . $currentLetter . " - " . $listGameType[$gameType] . "\n";
  353.  
  354.         message $message, "list";
  355.     }
  356. 1;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement