Ir ao conteúdo
  • Cadastre-se

Felipe Vendramini

Membro Júnior
  • Posts

    16
  • Cadastrado em

  • Última visita

  1. O ruim é que usa o banco de dados pra tudo. Não vou ter problemas em mostrar o código aqui, já que eu lancei o código do sistema no meu fórum. Esse é o SQL das tabelas. SET FOREIGN_KEY_CHECKS=0;DROP TABLE IF EXISTS `action`;CREATE TABLE `action` ( `id` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `id_next` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `id_nextfail` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `type` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `data` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `param` varchar(128) DEFAULT '', PRIMARY KEY (`id`), UNIQUE KEY `id` (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8;INSERT INTO `action` VALUES ('0000', '0000', '0000', '0000', '0000', null);INSERT INTO `action` VALUES ('1000', '1001', '0000', '0101', '0000', 'Bem-vindo ao Crims Age. Esta é a missão para iniciantes, você realizará pequenos trabalhos e ganhará alguns prêmios');INSERT INTO `action` VALUES ('1001', '1002', '0000', '0101', '0000', ' por completá-los. A sua primeira missão será roubar uma Velhinha do nível 1.');INSERT INTO `action` VALUES ('1002', '1003', '1010', '1003', '0044', '%user_id >= 1');INSERT INTO `action` VALUES ('1003', '0000', '0000', '0102', '0000', 'Pronto.~Qual~o~próximo~passo? 1100');INSERT INTO `action` VALUES ('1010', '0000', '0000', '0102', '0000', 'Vou~completar~a~missão. 0');INSERT INTO `action` VALUES ('1100', '1101', '1101', '1001', '0000', 'quest += 1 1110 0');INSERT INTO `action` VALUES ('1101', '1102', '1102', '1001', '0000', 'money += 200');INSERT INTO `action` VALUES ('1102', '1110', '1110', '1001', '0000', 'exp += 45');INSERT INTO `action` VALUES ('1110', '1111', '0000', '0101', '0000', 'Parabéns, você recebeu $200 e 45 pontos de experiência! Realize alguns roubos mais para conseguir status e dinheiro, ');INSERT INTO `action` VALUES ('1111', '1112', '0000', '0101', '0000', 'então compre 1 arma da Loja Premium ou do Negociante de Armas e equipe-a. Para equipar um item, basta clicar no ícone');INSERT INTO `action` VALUES ('1112', '1113', '0000', '0101', '0000', ' da maletinha na barra lá em cima da interface, do lado direito do Menu Suporte!');INSERT INTO `action` VALUES ('1113', '1114', '1120', '0511', '0001', '');INSERT INTO `action` VALUES ('1114', '0000', '0000', '0102', '0000', 'Pronto.~Consegui! 1200');INSERT INTO `action` VALUES ('1120', '0000', '0000', '0102', '0000', 'Estou~juntando~dinheiro. 0');DROP TABLE IF EXISTS `quests`;CREATE TABLE `quests` ( `id` int(4) unsigned zerofill NOT NULL AUTO_INCREMENT, `name` varchar(128) NOT NULL, `lookface` int(4) unsigned zerofill NOT NULL DEFAULT '1000', `req_class` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', `req_lev` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', `task0` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `description` text, PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;INSERT INTO `quests` VALUES ('0001', 'Missão de iniciante', '0000', '0', '1', '1000', 'Quest para iniciantes para ajudar no aprendizado do sistema.');DROP TABLE IF EXISTS `quests_trace`;CREATE TABLE `quests_trace` ( `id` bigint(9) unsigned zerofill NOT NULL AUTO_INCREMENT, `quest` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `userid` bigint(9) unsigned zerofill NOT NULL DEFAULT '000000000', `startdate` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `enddate` int(4) unsigned zerofill NOT NULL DEFAULT '0000', `flag` tinyint(1) unsigned zerofill NOT NULL DEFAULT '0', `id_next` int(4) unsigned zerofill NOT NULL DEFAULT '0000', PRIMARY KEY (`id`)) ENGINE=InnoDB DEFAULT CHARSET=utf8; Deixei as quests básicas. A tabela quests tem os "NPCs" do RPG. A tabela action tem as ações do jogo. Podem vir de um NPC ou ação dentro do jogo. quest_trace guarda os resultados. Os PHPs, o que executa as actions está comentado, vou comentando aqui agora na hora pra você os outros. Não é complicado e é uma boa estrutura para ações de jogos, principalmente em linguagens de programação de apps, q você pode usar dicionários e coisas de fácil acesso ao invés de buscar no banco de dados toda hora. Eis o missions.php, onde será mostrado para o usuário. <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Missões</h3> </div> <div class="panel-body" align="justify"> <p>As missões aparecem conforme seu respeito e moral crescem. A premiação delas variam, mas são ótimas para adquirir experiência, atributos, dinheiro e quem sabe créditos! Isso mesmo!<br> Esteja sempre atualizado e dê um <i>boost</i> em seus atributos sempre visualizando seu painel de missões.</p> <?php require_once("Include/GeneralMessage.php"); ?> <div id="NPCs"> <h4>Missões disponíveis</h4> <table class="table table-striped"> <thead> <tr> <th>Missão</th> <th>Iniciado</th> </tr> </thead> <tbody> <tr> <?php $GetQuest = $Database->query("SELECT * FROM quests WHERE req_lev<=" . $_SESSION["level"]); while ($Quest = $GetQuest->fetch(PDO::FETCH_BOTH)) { $IDNext = $Quest["task0"]; $Started = "Não"; $GetTrace = $Database->query("SELECT * FROM quests_trace WHERE quest=" . $Quest["id"] . " AND userid=" . $_SESSION["userid"] . " LIMIT 1"); if ($GetTrace->rowCount() > 0) { $Trace = $GetTrace->fetch(PDO::FETCH_BOTH); if ($Trace["id_next"] > 0) { $IDNext = $Trace["id_next"]; $Started = "Sim"; } } echo "<td><input type='button' id_next=\"" . $IDNext . "\" class='GameNPCOption btn btn-link' value='" . $Quest["name"] . "'></td><td>" . $Started . "</td>"; } ?> </tr> </tbody> </table> </div> </div> </div> <script> $(document).ready(function () { $(".GameNPCOption").click(function () { var element = $(this); var Id = element.attr("id_next"); var dataString = 'actionid=' + Id; alert(dataString); $.ajax({ type: "POST", url: "Ajax/ExecuteAction.php", data: dataString, cache: false, success: function (fdp) { $("#NPCs").html(fdp); } }); return false; }); }); </script> Eis o ExecuteAction.php. <?phpsession_start();require_once("../Config/Config.php");if(!isset($_SESSION["userid"])) die("Tá tentando enrolar o sistema parça?");if(isset($_POST["actionid"])){ $ActionID = CheckIfNegative($_POST["actionid"]); if(!CheckINT($ActionID)) die("Você preencheu errado o formulário."); require_once("../Config/Action.php"); $Action = new Actions(); $Action->Execute($ActionID, $_SESSION["userid"], $Database); die($_SESSION["returnmessage"]);}die("Ué?"); E o Action.php finalmente, onde as ações são executadas e contém os enums das funções. Aqui só vai ter os que estão no query que eu adicionei acima. <?phprequire_once("Class.Character.php");/* * Created by: Felipe Vieira Vendramini * Based on another script written by: ExodusBinaries (Conquer Online Private Server). * Project started on: September, 17, 2014 * Made to Crims Age. * * Action Classes * This Class has been done to execute tasks without the need of creating tons of * PHP files for each function. The actions are all stored on 'action' table on the * database. * id = The unique identification of the task. uint. * id_next = If the task executed on that action returns true, it will go for this. uint. * id_nextfail = If the task returns false, this will give the answer. uint. * type = The ActionType, the description will and use will be above the action. uint. * data = May be a requirement to give extra functions for the type. Not all types require * a data. uint. * param = If the type/data requires a param, it may be filled here. String. * The functions are at the class Actions. */class Actions{ /* * Essa função é responsável por executar os scripts. Ele faz o ExecuteTask que retorna se a ação foi verdadeira * ou falsa e então diz ao sistema se vai para o id_next ou para o id_nextfail. */ function Execute($ActionID, $UserID, PDO $Database) { $_SESSION["returnmessage"] = ""; again: $GetAction = $Database->query("SELECT * FROM `action` WHERE (`id`='" . $ActionID . "') LIMIT 1"); $Action = $GetAction->fetch(PDO::FETCH_BOTH); if (self::ExecuteTask($UserID, $Action["type"], $Action["data"], self::ReplaceVariable($Action["param"], $UserID, $Database), $Database)) { if ($Action["id_next"] > 0) { $ActionID = $Action["id_next"]; goto again; } } else { if ($Action["id_nextfail"] > 0) { $ActionID = $Action["id_nextfail"]; goto again; } } } function ExecuteTask($UserID, $Type, $Data, $Param, PDO $Database) { switch ($Type) { case ActionType::ACTION_DEFAULT: { return self::ACTIONDEFAULT(); } case ActionType::ACTION_SYSTEMDIALOG: { return self::ACTIONSYSTEMDIALOG($Param); } case ActionType::ACTION_SYSTEMOPTION: { return self::ACTIONSYSTEMOPTION($Param); } case ActionType::ACTION_SYSTEMCOMPARISON: { return self::ACTIONSYSTEMCOMPARISON($Param); } case ActionType::ACTION_USERCHECKATTR: { return self::ACTIONUSERCHECKATTR($Param, $UserID, $Database); } case ActionType::ACTION_USERCHECKROBBERY: { return self::ACTIONUSERCHECKROBBERY($Data, $Param, $Database); } default: return false; } } //The action definitions are listed below... /* * Action Type 0 = Does nothing. */ function ACTIONDEFAULT() { return true; } /* * Action Type 101 = Does a common dialog. The message can't exceed 128 characters. Always true. Doesn't require data. */ function ACTIONSYSTEMDIALOG($Param) { $_SESSION["returnmessage"] .= "<strong>" . $Param . "</strong>"; return true; } /* * Action Type 102 = Does a common link. Not done yet. Doesn't use spaces, the space will tell the Next reply. * Use the character '~' to spaces. Message~With~Space. 0 * Always true, doesn't require data. */ function ACTIONSYSTEMOPTION($Param) { $Params = explode(' ', $Param); $Message = str_replace('~', ' ', $Params[0]); $_SESSION["returnmessage"] .= "<br><input type='button' id_next='".$Params[1]."' class='GameNPCOption btn btn-link' value='".$Message."'>"; return true; } /* * Action Type 201 = Does a common comparison. Accept commands. Can be true or false. Doesn't require data. */ function ACTIONSYSTEMCOMPARISON($Param) { $Params = explode(' ', $Param); switch ($Params[1]) { case '==': { return $Params[0] == $Params[2]; } case '>=': { return $Params[0] >= $Params[2]; } case '<=': { return $Params[0] <= $Params[2]; } case '>': { return $Params[0] > $Params[2]; } case '<': { return $Params[0] < $Params[2]; } case '!=': { return $Params[0] != $Params[2]; } default: return false; } } /* * Action Type 1001 = This one is related to the User Character. Used to set or compare values. * Can be true or false. Set attr answer will be set on the function, requires a boolean function. * Doesn't require data. */ function ACTIONUSERCHECKATTR($Param, $UserID, PDO $Database) { if ($Param == null) return false; $Params = explode(' ', $Param); $GetCharacter = $Database->query("SELECT * FROM characters WHERE (`id`='" . $UserID . "') LIMIT 1"); $Character = $GetCharacter->fetch(PDO::FETCH_BOTH); $User = new Character(); switch ($Params[0]) { case "profession": { switch ($Params[1]) { case "<": { return $Character["profession"] < $Params[2]; } case "==": { return $Character["profession"] < $Params[2]; } case "set": { return $User->UpdateProfession($UserID, $Params[2], $Database); } default: return false; } } case "emoney": { switch ($Params[1]) { case "+=": { if ($Params[2] > 0) { return $User->AddCoins($Character["accountid"], $Params[2], $Database); } else { return $User->DeductCoins($Character["accountid"], CheckIfNegative($Params[2]), $Database); } } case ">=": { $GetAccount = $Database->query("SELECT * FROM account WHERE (`id`=" . $Character["accountid"] . ") LIMIT 1"); $Account = $GetAccount->fetch(PDO::FETCH_BOTH); return $Account["coins"] >= $Params[2]; } case "<": { $GetAccount = $Database->query("SELECT * FROM account WHERE (`id`=" . $Character["accountid"] . ") LIMIT 1"); $Account = $GetAccount->fetch(PDO::FETCH_BOTH); return $Account["coins"] < $Params[2]; } default: return false; } } case "money": { switch ($Params[1]) { case "+=": { if ($Params[2] > 0) { return $User->AddMoney($Character["accountid"], $Params[2], 1, $Database); } else { return $User->DeductMoney($Character["accountid"], CheckIfNegative($Params[2]), $Database); } } case ">=": { return $Character["money"] >= $Params[2]; } case "<": { return $Character["money"] < $Params[2]; } default: return false; } } case "exp": { switch ($Params[1]) { case "+=": { return $User->UpdateExp($Character["id"], $Params[2], $Database); } case ">=": { return $Character["exp"] >= $Params[2]; } case "<": { return $Character["exp"] < $Params[2]; } default: return false; } } case "quest": { /* * Attention, for this kind (quest) we have 4 or 5 indexes required. * quest opt questid status * quest = required * opt +=, == or set * questid = the quest you're looking for * id_next = the next id to continue the quest * status = 0 means Working and 1 means Finished * If the quest isn't started will return false automatically. * id_next is required on set and +=, they will have 5 indexes * == have only 4 excluding id_next */ switch ($Params[1]) { case "+=": { $GetQuest = $Database->query("SELECT * FROM quests_trace WHERE (quest=" . $Params[2] . " AND userid=" . $_SESSION["userid"] . ") LIMIT 1"); $QNum = $GetQuest->rowCount(); if ($QNum > 0) { $Update = $Database->prepare("UPDATE quests_trace SET id_next=" . $Params[3] . ", enddate=" . strtotime('now') . ", `flag`=" . $Params[4] . " WHERE (quest=" . $Params[2] . " AND userid=" . $_SESSION["userid"] . ") LIMIT 1"); return $Update->execute(); } else { $Insert = $Database->prepare("INSERT INTO quests_trace (`quest`,`userid`,`startdate`,`enddate`,`flag`,`id_next`) VALUES ('" . $Params[2] . "','" . $_SESSION["userid"] . "','" . strtotime('now') . "','" . strtotime('now') . "','" . $Params[4] . "','" . $Params[3] . "')"); return $Insert->execute(); } } case "==": { $GetQuest = $Database->query("SELECT * FROM quests_trace WHERE (quest=" . $Params[2] . " AND userid=" . $_SESSION["userid"] . ") LIMIT 1"); $QNum = $GetQuest->rowCount(); if ($QNum > 0) { $Quest = $GetQuest->fetch(PDO::FETCH_BOTH); return $Quest["status"] == $Params[3]; } else { return false; } } case "set": { $GetQuest = $Database->query("SELECT * FROM quests_trace WHERE (quest=" . $Params[2] . " AND userid=" . $_SESSION["userid"] . ") LIMIT 1"); $QNum = $GetQuest->rowCount(); if ($QNum > 0) { $Update = $Database->prepare("UPDATE quests_trace SET id_next=" . $Params[3] . ", enddate=" . strtotime('now') . ", `flag`=" . $Params[4] . " WHERE (quest=" . $Params[2] . " AND userid=" . $_SESSION["userid"] . ") LIMIT 1"); return $Update->execute(); } else { $Insert = $Database->prepare("INSERT INTO quests_trace (`quest`,`userid`,`startdate`,`enddate`,`flag`,`id_next`) VALUES ('" . $Params[2] . "','" . $_SESSION["userid"] . "','" . strtotime('now') . "','" . strtotime('now') . "','" . $Params[4] . "','" . $Params[3] . "')"); return $Insert->execute(); } } default: return false; } } default: return false; } } /* * Action Type 1003 = Used to Check how many times the user has done that robbery. * Data = The Robbery ID * Param = UserID Opt Amount * UserID is the ID of the user youre looking for. * Opt >=, <, == * Amount is the number of times youre looking for. */ function ACTIONUSERCHECKROBBERY($Data, $Param, PDO $Database) { $Params = explode(' ', $Param); $UserID = $Params[0]; $Opt = $Params[1]; $Amount = $Params[2]; $Robbery = $Data; $GetInfos = $Database->query("SELECT * FROM crimes WHERE robbery_id=" . $Robbery . " AND user_id=" . $UserID); $Num = $GetInfos->rowCount(); switch ($Opt) { case ">=": { return $Num >= $Amount; } case "<": { return $Num < $Amount; } case "==": { return $Num == $Amount; } default: return false; } } function ReplaceVariable($String, $TargetID, PDO $Database) { $GetChar = $Database->query("SELECT * FROM characters WHERE (`id`='" . $TargetID . "') LIMIT 1"); $Character = $GetChar->fetch(PDO::FETCH_BOTH); $String = str_replace('%user_id', $Character["id"], $String); $String = str_replace('%user_name', $Character["name"], $String); $String = str_replace('%user_lev', $Character["level"], $String); $String = str_replace('%user_exp', $Character["exp"], $String); $String = str_replace('%user_profession', $Character["profession"], $String); $String = str_replace('%user_accountid', $Character["accountid"], $String); $String = str_replace('%user_respect', $Character["respect"], $String); $String = str_replace('%user_int', $Character["inteligence"], $String); $String = str_replace('%user_str', $Character["strenght"], $String); $String = str_replace('%user_cha', $Character["charisma"], $String); $String = str_replace('%user_res', $Character["resistence"], $String); $String = str_replace('%user_money', $Character["money"], $String); $String = str_replace('%user_emoney', $Character["dexterity"], $String); $String = str_replace('%user_stamina', $Character["stamina"], $String); $String = str_replace('%user_kill', $Character["kills"], $String); $String = str_replace('%user_death', $Character["deaths"], $String); $String = str_replace('%user_status', $Character["status"], $String); $String = str_replace('%user_statusreason', $Character["status_reason"], $String); $String = str_replace('%user_moneysaved', $Character["money_saved"], $String); $String = str_replace('%user_tickets', $Character["tickets"], $String); return $String; }}/* * Just the enum of each function. */class ActionType{ const __default = self::ACTION_DEFAULT; const ACTION_DEFAULT = 0; const ACTION_SYSTEMDIALOG = 101; const ACTION_SYSTEMOPTION = 102; const ACTION_SYSTEMCOMPARISON = 201; const ACTION_USERCHECKATTR = 1001; const ACTION_USERCHECKROBBERY = 1003;} O Class.Character.php não é necessário, as funções dele podem ser substituidas por outras boolean qualquer. Ele tem os sistemas de alteração de dados de personagem. kkkk Bom, ficou grandinho, eu não consegui usar aquela coisa. Mas esses são os códigos que compõem as missões.
  2. Obrigado, tentei fazer o Console, mas ele não acusa erro depois de clicar, apenas que foi executado o POST é o último Tentei refazer umas 3x já kkkkkkkk Acho que vou ter que fazer um $_GET ou sei lá
  3. Ninguém? Eu tirei uma folga e então eu nem tentei ainda, vou ver se consigo fazer sem precisar mudar muita coisa, se souberem, por favor
  4. Boa madruga galera, estou com um problema básico que faz 3 horas que estou sem conseguir resolver, deve ser o sono, estudar e fazer essa budega tá me matando, mas vamos lá... Tenho um código no meu joguinho PHP e pãns, ele mostra as Quests que o usuário pode pegar e que ainda não foram finalizadas, até ai, tudo bem! Após eu clicar na Quest para iniciar a mesma, ele vai normal, numa boa, atualiza a div, porém, a div pode retornar outras opções, fiz de maneira dinâmica os eventos, usando uma coisa que chamo de ActionTypes. Vou mostrar aqui uns exemplos. Observem: Maravilha, listou a missão. Maravilha, ele mostrou a primeira mensagem. Executei o que a missão pediu Posso prosseguir então... Só que nessa segunda parte, após eu escolher a missão novamente, quando eu clico na opção ela não chama a próxima função... Se eu clicar no "Pronto. Qual o próximo passo?" ele nem chama o JQuery de novo. Vou postar um exemplo de código e aliás, eu uso bootstrap hahah, não sou um bom designer. <div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Missões</h3> </div> <div class="panel-body" align="justify"> <p>As missões aparecem conforme seu respeito e moral crescem. A premiação delas variam, mas são ótimas para adquirir experiência, atributos, dinheiro e quem sabe créditos! Isso mesmo!<br> Esteja sempre atualizado e dê um <i>boost</i> em seus atributos sempre visualizando seu painel de missões.</p> <?php require_once("Include/GeneralMessage.php"); ?> <div id="NPCs"> <h4>Missões disponíveis</h4> <table class="table table-striped"> <thead> <tr> <th>Missão</th> <th>Iniciado</th> </tr> </thead> <tbody> <tr> <?php $GetQuest = $Database->query("SELECT * FROM quests WHERE req_lev<=" . $_SESSION["level"]); while ($Quest = $GetQuest->fetch(PDO::FETCH_BOTH)) { $IDNext = $Quest["task0"]; $Started = "Não"; $GetTrace = $Database->query("SELECT * FROM quests_trace WHERE quest=" . $Quest["id"] . " AND userid=" . $_SESSION["userid"] . " LIMIT 1"); if ($GetTrace->rowCount() > 0) { $Trace = $GetTrace->fetch(PDO::FETCH_BOTH); if ($Trace["id_next"] > 0) { $IDNext = $Trace["id_next"]; $Started = "Sim"; } } echo "<td><input type='button' id_next=\"" . $IDNext . "\" class='GameNPCOption btn btn-link' value='" . $Quest["name"] . "'></td><td>" . $Started . "</td>"; } ?> </tr> </tbody> </table> </div> </div> </div> <script> $(document).ready(function () { $(".GameNPCOption").click(function () { var element = $(this); var Id = element.attr("id_next"); var dataString = 'actionid=' + Id; alert(dataString); $.ajax({ type: "POST", url: "Ajax/ExecuteAction.php", data: dataString, cache: false, success: function (resultado) { $("#NPCs").html(resultado); } }); return false; }); }); </script> Os eventos são armazenados dessa maneira. Se puderem me ajudar por favor. Quando clico no NPC, ele executa a primeira action que é a 1000, continua até a 1003. Quando é chamada a 1100, na verdade deveria ser chamada, o que não acontece, ela deveria executar o arquivo novamente, mas ele nem dá o popup do alert. O sistema de actions está funcionando perfeitamente! Já testei ele em um arquivo separado. Agradeço desde já.
  5. Bem, estou sem VS aqui e não tenho nenhum código pronto acessível sobre isso também, mas dei uma olhada no google e espero que algum desses possa lhe ajudar. http://stackoverflow.com/questions/304337/post-data-to-a-php-page-from-c-sharp-winform http://www.softwareandfinance.com/PHP/PostRequest_CSharp_php.html
  6. Boa tarde, meu problema é o seguinte. Estou montando um jogo com conexão Async em C#. O Socket entre meu Cliente e o Servidor estão OK. Se não trata o MySql tenho um tempo de resposta instantaneo, porém, quando executo algo que precisa do banco de dados esse tempo sobe para >1000 ms dependendo do Query. Uso Dicionários para guardar os dados no servidor para que fiquem de acesso rápido, até ai tudo bem. Porém por segurança eu já executo o Query de Update, Delete, Insert na hora em que faço a modificação no Dicionário, que é para caso o Servidor quebre ou disconecte o usuário os dados não sejam perdidos. Eu poderia fazer o servidor Salvar o personagem ao desconectar, mas são muitos os erros que podem ocasionar um desligamento no servidor, então, prefiro assim. Minha primeira pergunta é, posso fazer o MySql executar Queries em um Thread diferente? Como? Eu desativei o Pool do meu Mysql temporariamente, pois estava quebrando dizendo que eu havia excedido o limite do Pool, o problema é que é no servidor de testes, ainda nem lancei uma versão Beta nem nada, ou seja, só tinha 2 personagens online (eu e eu mesmo). Com o pool, os queries não aumentavam o tempo de resposta, era coisa de 10-20 ms, sem o Pool aumenta de 800-1200 ms. Mas se eu ativo o Pool ele quebra o servidor depois de um tempo. Li que o Pool desativa as conexões automaticamente após certo tempo, porém, digamos que quando o usuário loga ele executa vários queries para buscar as informações, Inventário, Equipamento, Informações do Personagem, Ranking, Guilda, Clan, Magias, Habilidades e etc que ficam em tabelas diferentes, então ao logar um terceiro usuário eu já quebro o servidor. Vou postar meu código do "MySql Base". Primeiro e menos importante "CommandType.cs" using System;using System.Collections.Generic;using System.Linq;using System.Text; namespace Game_Server{ public enum CommandType { SELECT, INSERT, DELETE, UPDATE }} O "MySqlCommand.cs" using System;using System.Collections.Generic;using System.Linq;using System.Text;using MySql.Data.MySqlClient;namespace Game_Server{ public class MysqlCommand : MySqlBase { private CommandType Type; private string Command; public MysqlCommand(CommandType _cmdtype) { Type = _cmdtype; switch (_cmdtype) { case CommandType.SELECT: Command = "SELECT <V> FROM <T> "; break; case CommandType.UPDATE: Command = "UPDATE <R> SET "; break; case CommandType.INSERT: Command = "INSERT INTO <T> (<F>) VALUES (<V>)"; break; case CommandType.DELETE: Command = "DELETE FROM <T> WHERE <C>=<V> "; break; } } #region Properties public MysqlCommand Select(string Value, string Table) { Command = Command.Replace("<V>", "" + Value + ""); Command = Command.Replace("<T>", "`" + Table + "`"); return this; } public object Read(string Section) { object Val = DataReader[Section]; return Val; } public MysqlCommand Where(string Column, object Value) { Command = Command + "WHERE `" + Column + "`='" + Value.ToString() + "' "; return this; } public MysqlCommand And(string Column, object Value) { Command = Command + "AND `" + Column + "`='" + Value.ToString() + "' "; return this; } public MysqlCommand And(string Column, string Opt, object Value) { Command = Command + "AND `" + Column + "`" + Opt + "'" + Value.ToString() + "' "; return this; } public MysqlCommand Delete(string Table, string Column, object Value) { Command = Command.Replace("<T>", "`" + Table + "`"); Command = Command.Replace("<C>", "`" + Column + "`"); Command = Command.Replace("<V>", "'" + Value.ToString() + "'"); return this; } public MysqlCommand Update(string Table) { Command = Command.Replace("<R>", "`" + Table + "`"); return this; } public MysqlCommand Set(string Column, object Value, bool Multiple) { if (Multiple) { Command = Command + ", `" + Column + "`='" + Value.ToString() + "' "; } else { Command = Command + "`" + Column + "`='" + Value.ToString() + "' "; } return this; } public MysqlCommand OrderBy(string Column, string Mode) { Command = Command + "ORDER BY " + Column + " " + Mode + " "; return this; } public MysqlCommand Insert(string Table, string Columns, string Values) { Command = Command.Replace("<T>", "`"+Table+"`"); Command = Command.Replace("<F>", Columns); Command = Command.Replace("<V>", Values); return this; } public MysqlCommand Limit(uint Amount) { Command = Command + " LIMIT " + Amount; return this; } public void Done() { Execute(Command, Type); } public void Abort() { End(); } public MySqlDataReader DataReader { get { return _DataReader; } } #endregion }} E o "MySqlBase.cs" using System;using System.Collections.Generic;using System.Linq;using System.Text; using MySql.Data.MySqlClient;using System.Data;namespace Game_Server{ public class MySqlBase { MySqlConnection _mysqlConnection; bool Executed = false; MySqlCommand MySqlCmd; MySqlDataReader _dr; public MySqlBase() { _mysqlConnection = new MySqlConnection("Server=" + CQServer.Server + ";Database='" + CQServer.Database + "';Username='" + CQServer.Username + "';Password='" + CQServer.Password + "';Pooling=false;"); _mysqlConnection.Open(); } #region Properties public ConnectionState State() { return _mysqlConnection.State; } public MySqlConnection CurrentConnection { get { if (!Executed) { _mysqlConnection.Open(); Executed = true; _mysqlConnection.StateChange += new StateChangeEventHandler(MySql_Invoked); } return _mysqlConnection; } } private void MySql_Invoked(object Sender, System.Data.StateChangeEventArgs e) { switch (e.CurrentState) { case ConnectionState.Closed: case ConnectionState.Broken: { _mysqlConnection.Dispose(); _mysqlConnection = new MySqlConnection("Server=" + CQServer.Server + ";Database='" + CQServer.Database + "';Username='" + CQServer.Username + "';Password='" + CQServer.Password + "';"); _mysqlConnection.Open(); _mysqlConnection.StateChange += new StateChangeEventHandler(MySql_Invoked); break; } } } public void Execute(string Command, CommandType Type) { switch (Type) { #region Select case CommandType.SELECT: { MySqlCmd = new MySqlCommand(Command, this._mysqlConnection); _dr = MySqlCmd.ExecuteReader(); break; } #endregion #region Insert case CommandType.INSERT: { MySqlCmd = new MySqlCommand(Command, this._mysqlConnection); MySqlCmd.ExecuteNonQuery(); break; } #endregion #region Update case CommandType.UPDATE: { MySqlCmd = new MySqlCommand(Command, this._mysqlConnection); MySqlCmd.ExecuteNonQuery(); MySqlCmd.Connection.Close(); MySqlCmd.Connection.Dispose(); MySqlCmd.Dispose(); break; } #endregion #region Delete case CommandType.DELETE: { MySqlCmd = new MySqlCommand(Command, this._mysqlConnection); MySqlCmd.ExecuteNonQuery(); break; } #endregion } } public void End() { _mysqlConnection.Dispose(); _mysqlConnection.Close(); } public MySqlDataReader _DataReader { get { return this._dr; } } #endregion }} O pool funcionava até um tempo atrás, não sei se eu usei algum Query de forma errada, mas ontem começou a passar o limite. Um exemplo de Query MysqlCommand cmd = new MysqlCommand(CommandType.SELECT); cmd.Select("*", "cq_item").Where("player_id", Client.Entity.UID).And("position", 0).Limit(40); cmd.Done(); while (cmd.DataReader.Read()) { // Faz o Handle de enviar os itens para o Inventário } Eu estou esquecendo de algo? Devo usar o "cmd.End();"? Obrigado
  7. Resolvi, só reescrevi o meio, o erro tava no if else do while lol
  8. Bem galera, eu estava com o código perfeitinho usando mysql_* Então migrei o site todo e estou reconstruindo em PDO, estou de início reconstruindo apenas as queries e conexões, afinal, é tudo o que mudou lol Mas o problema é que... Eu migrei do AppServ para o Wampserver e, no AppServ ele não me retornava erro nenhum e funcionava perfeitamente, assim como na hospedagem... e agora ele me retorna essa benção... Maravilha -.- o Código antigo <?phpif(isset($_SESSION["userid"])){?><script>jQuery(document).ready(function(){ jQuery('#changeTheFuckingAvatar').submit(function(){ var dados = jQuery( this ).serialize(); $("#submit").attr("disabled","disabled"); jQuery.ajax({ type: "POST", url: "Ajax/ChangeAvatar.php", data: dados, success: function( data ) { if(data) { $("#general_message").css("visibility","visible"); $("#general_message").attr("class", "alert alert-danger"); $("#general_message").html("<span class='glyphicon glyphicon-remove'></span>" + data); }else{ setTimeout(function(){window.location.href = 'index.php?id=<?=$_GET["id"]?>'}, 0); } } }); return false; }); }); </script><div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Mudar Avatar</h3> </div> <div class="panel-body"> <p>Escolha um avatar de sua preferência.</p> <form action="" method="post" target="_self" id="changeTheFuckingAvatar"> <p> <?php $GetAvatar = mysql_query("SELECT * FROM avatar ORDER BY rand() LIMIT 21"); $i = 0; while($Avatar = mysql_fetch_array($GetAvatar)) { if($i < 2) { ?> <input name="avatar" type="radio" id="radio" value="<?=$Avatar["id"]?>"><img src="<?=$Avatar["link"]?>" width="100" height="100" alt="<?=$Avatar["name"]?>" title="<?=$Avatar["name"]?>"> <?php $i++; }else{ ?> <input name="avatar" type="radio" id="radio" value="<?=$Avatar["id"]?>"><img src="<?=$Avatar["link"]?>" width="100" height="100" alt="<?=$Avatar["name"]?>" title="<?=$Avatar["name"]?>"></p><p> <? $i = 0; } } ?> </p> <input id="submit" name="submit" type="submit" class="btn btn-default" value="Mudar Aparência"> </form> <div id="general_message"></div></div></div><?php}else{ require_once("notonline.php");}?> e o código novo <?phpif(isset($_SESSION["userid"])){?><script>jQuery(document).ready(function(){ jQuery('#changeTheFuckingAvatar').submit(function(){ var dados = jQuery( this ).serialize(); $("#submit").attr("disabled","disabled"); jQuery.ajax({ type: "POST", url: "Ajax/ChangeAvatar.php", data: dados, success: function( data ) { if(!data || data === null || data == " ") { setTimeout(function(){window.location.href = 'index.php?id=<?=$_GET["id"]?>'}, 0); }else{ $("#general_message").css("visibility","visible"); $("#general_message").attr("class", "alert alert-danger"); $("#general_message").html("<span class='glyphicon glyphicon-remove'></span>" + data); } } }); return false; }); }); </script><div class="panel panel-default"> <div class="panel-heading"> <h3 class="panel-title">Mudar Avatar</h3> </div> <div class="panel-body"> <p>Escolha um avatar de sua preferência.</p> <form action="" method="post" target="_self" id="changeTheFuckingAvatar"> <p> <?php $i = 0; $GetAvatar = $Database->query("SELECT * FROM avatar ORDER BY rand() LIMIT 21"); while($Avatar = $GetAvatar->fetch(PDO::FETCH_ASSOC)) { if($i < 2) { ?> <input name="avatar" type="radio" id="radio" value="<?=$Avatar["id"]?>"><img src="<?=$Avatar["link"]?>" width="100" height="100" alt="<?=$Avatar["name"]?>" title="<?=$Avatar["name"]?>"> <?php $i++; }elseif($i >= 2){ ?> <input name="avatar" type="radio" id="radio" value="<?=$Avatar["id"]?>"><img src="<?=$Avatar["link"]?>" width="100" height="100" alt="<?=$Avatar["name"]?>" title="<?=$Avatar["name"]?>"></p><p> <? $i = 0; } } ?> </p> <input id="submit" name="submit" type="submit" class="btn btn-default" value="Mudar Aparência"> </form> <div id="general_message"></div></div></div><?php}else{ require_once("notonline.php");}?> Enfim, eu preciso ir buscar meu irmão na escola e já volto pra ver se tem algo a mais. Obrigado...
  9. Eu uso o 2.5.10, mas não instalo o MySql, o MySql baixei do site oficial
  10. Eu uso o AppServ e não tenho do que reclamar também u-u
  11. Eu uso no meu site e não tenho problemas '-' e ainda uso 1 pra cada parte kkk <?php echo '<div class="sidebar1">'; require_once("Include/LeftSide.php"); echo '</div>'; if(isset($_GET["id"])) { if(is_numeric($_GET["id"])) { $Page = $_GET["id"]; if($Page == 0 || $Page == NULL) { if(isset($_SESSION["userid"])) { require_once("start.php"); }else{ require_once("notonline.php"); } }else{ if(isset($_SESSION["userid"])) { $SelectPage = mysql_query("SELECT * FROM pages WHERE id=".$Page." LIMIT 1"); $objPage = mysql_fetch_array($SelectPage); if($_SESSION["status"] == 1) { if($objPage["jail"] == 1) { require_once($objPage["link"]); }else{ require_once("jail.php"); } }elseif($_SESSION["status"] == 2){ if($objPage["hospital"] == 1) { require_once($objPage["link"]); }else{ require_once("hospital.php"); } }else{ $Count = mysql_num_rows($SelectPage); if($objPage["id"] != 13) { $LeaveNF = mysql_query("UPDATE clubs_visitors SET club_id=0 WHERE (`user_id`='".$_SESSION["userid"]."') LIMIT 1"); } require_once($objPage["link"]); } }else{ if($Page == 18) { require_once("register.php"); }elseif($Page == 19) { require_once("forgotpw.php"); }elseif(isset($_SESSION["accountid"])) { require_once("newplayer.php"); }else{ require_once("notonline.php"); } } } } }else{ if(isset($_SESSION["userid"])) { require_once("start.php"); }else{ require_once("notonline.php"); } } echo '<div class="sidebar2">'; require_once("Include/RightSide.php"); echo '</div>'; ?>
  12. o Wamp dá dois status né? Apache e Mysql... Você tinha alguma instância do MySql instalada antes na máquina? Se tinha pode estar ai o problema... Eu recomendo que você instale o MySql a parte ao invés de usar o que vem junto com Wampserver, AppServ e etc.. Qualquer coisa, finaliza o Wampserver, procura no Gerenciador de Tarefas lá o mysqld, mysql-nt, não sei qual o nome do serviço que vai estar (Se estiver executando), então vá no C:\Windows e apague o My.ini (Depois de finalizar o Mysql) e então tenta executar o serviço de novo ou reinstala o aplicativo. Nunca configurei o MySql por Wamp, mas se apagar o My.ini provavelmente vai ter que reinstalar o Wamp. '-'
  13. Bem, eu já procurei (e muito) por ai, tentei várias gambiarras, escrevi e reescrevi essa coisa e só apanho. Bem, é aquele problema, tenho meu site com link http://site.com/index.php?id=123&nome=Nome-Da-Pagina Legal, quero mostrar ele como http://site.com/123/Nome-Da-Pagina/'>http://site.com/123/Nome-Da-Pagina/ Em partes, consegui Eu faço ele mostrar http://site.com/123 Maaaaaas.... Se eu coloco alguma barra depois do 123, ele bagunça todo o meu site... D: Bem, os exemplos, vamos lá... Options +FollowSymLinks -MultiViewsRewriteEngine OnRewriteBase /crims/RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php|)\?id=([^\s]+) [NC]RewriteRule ^ /%1? [R=301,L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-lRewriteRule ^(.+?)/?$ /index.php?id=$1 [L,QSA] Hummm, até ai, beleza Agora o jeito que eu gostaria que estivesse... Options +FollowSymLinks -MultiViewsRewriteEngine OnRewriteBase /crims/RewriteCond %{THE_REQUEST} ^[A-Z]{3,}\s/+(?:index\.php|)\?id=([^\s]+)&name=Como-Jogar [NC]RewriteRule ^ /%1/%2? [R=301,L]RewriteCond %{REQUEST_FILENAME} !-fRewriteCond %{REQUEST_FILENAME} !-dRewriteCond %{REQUEST_FILENAME} !-lRewriteRule ^(.+?)/(.+?)/?$ /index.php?id=$1&name=$2 [L,QSA] Será que alguém poderia me ajudar? Além de quê, o id, name não são os unicos atributos que podem aparecer, pode ter também o type e o userid e username :/ Eu tinha conseguido trabalhar com o userid, mas daí o name não ia... Trágico
  14. Tenta fazer um Ajax pra fazer o POST 2x '-' Se você fizer um PHP, o script pra redirecionar é fácil O problema é reenviar o POST pra ele fazer o login na outra página né .. '-' <meta http-equiv="refresh" content="0;url=URL_DA_PAGINA"> O 0 é o tempo que espera pra redirecionar..

Sobre o Clube do Hardware

No ar desde 1996, o Clube do Hardware é uma das maiores, mais antigas e mais respeitadas comunidades sobre tecnologia do Brasil. Leia mais

Direitos autorais

Não permitimos a cópia ou reprodução do conteúdo do nosso site, fórum, newsletters e redes sociais, mesmo citando-se a fonte. Leia mais

×
×
  • Criar novo...