<?php
/*
* Alliances Manager (Gestionador de Alianzas) - Travian
* Copyright (C) 2008-12 Viva Mayer, Francisco Mesías <hide@address.com>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
class ModeloTropas extends ModeloBase
{
private function modificacion()
{
$sql = "UPDATE `".$this->config->get('PREFIX')."usuario` SET `last_change_tropa` = NOW( ) WHERE nombre=\"".$_SESSION['usuario']."\"";
mysql_query($sql, $this->db) or die(mysql_error($this->db));
}
public function propias(&$en_aldea, &$refuerzos, &$aldeas = false )
{
// ###---> EXTRACCIÓN DE TODAS LAS ALDEAS DEL JUGADOR <----###
$sql = "SELECT `nombre`, `x`, `y` FROM `".$this->config->get('PREFIX')."aldea` WHERE `usuario_nombre`=\"".$_SESSION['usuario']."\" ORDER BY `nombre` ASC";
$sql_aldeas = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$contador = 0; // para el arreglo $en_aldea
$contador2 = 0; // para el arreglo $refuerzos
while ( $aldea = mysql_fetch_assoc($sql_aldeas) )
{
$aldeas = true;
// ###---> COMENZADOS CON LAS TROPAS EN ESTA ALDEA <----###
$sql = "SELECT `idtropa`, `cantidad` FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`=".$aldea['x']." AND `oy`=".$aldea['y']." ORDER BY `idtropa` ASC";
$sql_tropas_en = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$en_aldea[$contador] = array(
'aldea'=> $aldea['nombre'],
'x'=> $aldea['x'],
'y'=> $aldea['y'],
't0'=> 0, 't1'=> 0, 't2'=> 0, 't3'=> 0, 't4'=> 0,
't5'=> 0, 't6'=> 0, 't7'=> 0, 't8'=> 0, 't9'=> 0
);
while ( $aux = mysql_fetch_assoc($sql_tropas_en) )
{
$it = $aux['idtropa'] - (int) ($aux['idtropa']/10) * 10;
$en_aldea[$contador]['t'.$it] = $aux['cantidad']; // Ingresamos la cantidad pertinente al tipo de tropa
}
// ###----> AHORA LAS TROPAS DE REFUERSO DE ESTA ALDEA EN OTRA ALDEA <----###
$sql = "SELECT `idtropa`, `dx`, `dy`, `cantidad` FROM `".$this->config->get('PREFIX')."refuerzos` WHERE `ox`=".$aldea['x']." AND `oy`=".$aldea['y']." ORDER BY `dx` ASC , `dy` ASC";
$sql_tropas_ref = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$num = mysql_num_rows($sql_tropas_ref); $j = 0;
$aux = mysql_fetch_assoc($sql_tropas_ref);
while ( $j < $num )
{
$refuerzos[$contador2] = array(
'aldea'=> $aldea['nombre'], 'ox'=> $aldea['x'], 'oy'=> $aldea['y'],
'dx'=> $aux['dx'], 'dy'=> $aux['dy'],
't0'=> 0, 't1'=> 0, 't2'=> 0, 't3'=> 0, 't4'=> 0, 't5'=> 0, 't6'=> 0, 't7'=> 0, 't8'=> 0, 't9'=> 0
);
$aux_x = $aux['dx']; $aux_y = $aux['dy']; // aplicamos corte de control
while ( ($aux_x == $aux['dx']) and ($aux_y == $aux['dy']) )
{
$it = $aux['idtropa'] - ((int) ($aux['idtropa']/10)) * 10;
$refuerzos[$contador2]['t'.$it] = $aux['cantidad']; // Ingresamos la cantidad pertinente al tipo de tropa
$aux = mysql_fetch_assoc($sql_tropas_ref);
$j+=1;
}
$contador2++;
} // fin while interno (refuerzos)
$contador++;
} // fin while principal
unset($sql_tropas_ref, $sql_tropas_en, $aux);
} // Fin Función: propias ...
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
public function datosaldea(&$aldea)
{
$aux = explode('|', $_POST['aldea']); // Extracción de las coordenadas
$x = (int) $aux[0];
$y = (int) $aux[1];
$sql = "SELECT `nombre`, `x`, `y` FROM `".$this->config->get('PREFIX')."aldea` WHERE `usuario_nombre` = '".$_SESSION['usuario']."' and (`x`=".$x." and `y`=".$y.")";
$sql_aldeas = mysql_query($sql, $this->db) or die(mysql_error($this->db));
if (mysql_num_rows($sql_aldeas) == 0) { return 'EPT05'; } // Verificación de existencia de
// la aldea
$aux = mysql_fetch_assoc($sql_aldeas);
mysql_free_result($sql_aldeas);
$aldea = array('nombre'=> $aux['nombre'], 'x'=>$aux['x'] , 'y'=>$aux['y'] );
if (!isset($_POST['refuerzo'])) {
$sql = "SELECT `idtropa` FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`=".$x." and `oy`=".$y;
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
if (mysql_num_rows($resultado) != 0) { return 'EPT06'; } // Verificación de existencia de
// tropas en esta aldea
mysql_free_result($resultado);
}
return '';
}
//------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------
public function cargar()
{
$ox = (int) $_POST['ox'];
$oy = (int) $_POST['oy'];
$flag = false;
$codigos = array_keys(self::$texto->get($_SESSION['raza']));
$sql = ""; $concat = "";
if (empty($_POST['rx']) and empty($_POST['ry']))
{
$sql = "SELECT `idtropa` FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`=".$ox." and `oy`=".$oy;
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
if (mysql_num_rows($resultado) != 0) { return 'EPT06'; }
$bandera = false; // por si todos los campos vienen en 0
foreach ($codigos as $id)
{
if ($_POST[$id] != 0)
{
if ($flag) $concat .= ", (".$id.",".$ox.",".$oy.",".$_POST[$id].")";
else {
$concat .= "(".$id.",".$ox.",".$oy.",".$_POST[$id].")";
$flag = true;
}
$bandera = true;
}
}
if ($bandera) $sql = "INSERT INTO `".$this->config->get('PREFIX')."tropas_aldea` (`idtropa`,`ox`,`oy`,`cantidad`) VALUES ".$concat."";
else return 'EPT07';
}
else
{
foreach ($codigos as $id)
{
if ($_POST[$id] != 0)
{
if ($flag) $concat .= ", (".$id.",".$ox.",".$oy.",".$_POST['rx'].",".$_POST['ry'].",".$_POST[$id].")";
else {
$concat .= "(".$id.",".$ox.",".$oy.",".$_POST['rx'].",".$_POST['ry'].",".$_POST[$id].")";
$flag = true;
}
}
}
$sql = "INSERT INTO `".$this->config->get('PREFIX')."refuerzos` (`idtropa`,`ox`,`oy`,`dx`,`dy`,`cantidad`) VALUES ".$concat."";
}
mysql_query($sql, $this->db) or die(mysql_error($this->db));
$this->modificacion();
header("Location: index.php?ctrl=Tropas&mod=tropas");
}
//--------- verunidades -----------------------------------------------------------------
//
// Devuelve dos arreglos:
// 1.- $aldea con los siguientes datos:
// nombre -> nombre de la aldea
// x e y -> coordenadas de la aldea
// rx y ry -> coordenadas de la aldea de refuerzo (si existe)
// 2.- $tropas, que contine las tropas cargadas o cero (0) si no hay tropas. Todas ellas ordenadas
// por su id de tropa correspondiente a la raza del usuario.
//---------------------------------------------------------------------------------------
public function verunidades(array &$aldea, array &$tropas, &$tot_aldeas)
{
$x = (int) $_GET['x'];
$y = (int) $_GET['y'];
$sql = "SELECT `nombre`, `x`, `y` FROM `".$this->config->get('PREFIX')."aldea` WHERE `usuario_nombre`='".$_SESSION['usuario']."' and (`x`=".$x." and `y`=".$y.")";
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$aux = mysql_fetch_assoc($resultado);
$aldea['nombre'] = $aux['nombre'];
$aldea['x'] = $aux['x'];
$aldea['y'] = $aux['y'];
$tot_aldeas = true;
$id_tropas = array_keys(self::$texto->get($_SESSION['raza']));
if (isset($_GET['rx']) and isset($_GET['ry'])) {
$sql = "SELECT `idtropa`, `cantidad` FROM `".$this->config->get('PREFIX')."refuerzos` WHERE (`ox`=".$x." and `oy`=".$y.") and (`dx`=".$_GET['rx']." and `dy`=".$_GET['ry'].")";
$aldea['rx'] = $_GET['rx'];
$aldea['ry'] = $_GET['ry'];
} else {
$sql = "SELECT `idtropa`, `cantidad` FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`=".$x." and `oy`=".$y."";
}
$aux = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$registro = mysql_fetch_assoc($aux); $i = 0;
while ($i<10) {
if ($registro['idtropa']==$id_tropas[$i]) {
$tropas[$id_tropas[$i]] = $registro['cantidad'];
$registro = mysql_fetch_assoc($aux);
} else $tropas[$id_tropas[$i]] = 0;
++$i;
}
}
//---------------------------------------------------------------------------------------
// no devuelve nada (por ahora)
//---------------------------------------------------------------------------------------
public function actualizar()
{
// sacamos las claves de las tropas
$id_tropas = array_keys(self::$texto->get($_SESSION['raza']));
$ox = (int) $_POST['ox'];
$oy = (int) $_POST['oy'];
if (empty($_POST['rx']) and empty($_POST['ry'])) // Edición de las tropas en la aldea.
{
$sql = "SELECT `idtropa`, `cantidad` FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`= ".$ox." and `oy`= ".$oy." ORDER BY `idtropa` ASC";
$datos_cargados = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$tropas_visitadas = array();
while ($un_dato = mysql_fetch_assoc($datos_cargados)) // Buscamos y actualizamos todos las tropas ya cargadas
{
foreach ($id_tropas as $id)
{
if ($un_dato['idtropa'] == $id) // Encontramos una tropa cargada ...
{
if ( $un_dato['cantidad'] != $_POST[$id] ) // La cantidad ha sido modificada ...
{
if ($_POST[$id] == 0 or empty($_POST[$id])) // a cero o borrada de la tabla sin ingresar cantidad ...
{
$sql = "DELETE FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `idtropa` = ".$id." AND `ox`=".$ox." AND `oy`=".$oy."";
} else { // o a algún otro valor ...
$sql = "UPDATE `".$this->config->get('PREFIX')."tropas_aldea` SET `cantidad` = ".$_POST[$id]." WHERE `ox`=".$ox." AND `oy`=".$oy." AND `idtropa` =".$id;
}
mysql_query($sql, $this->db) or die(mysql_error($this->db)); // Actualizamos o Borramos según el condicional anterior.
}
$tropas_visitadas[] = $id; // Registramos las tropas que se encuentran cargadas.
break; // Salimos del FOREACH, ya que para que seguir si ya hubo coincidencia.
}
} // FIN FOR
} // FIN WHILE
foreach ($id_tropas as $id) // Ahora verificamos aquellas tropas que
{ // no se encuentran cargadas.
if (!in_array($id,$tropas_visitadas) and ($_POST[$id]!=0)) // Si la tropa no se encuentra cargada en la BD
{ // y la cantidad es distinta de cero ...
$sql = "INSERT INTO `".$this->config->get('PREFIX')."tropas_aldea` (`idtropa`,`ox`,`oy`,`cantidad`) VALUES (".$id.",".$ox.",".$oy.",".$_POST[$id].")";
mysql_query($sql, $this->db) or die(mysql_error($this->db)); // Insertamos la nueva información.
}
} // FIN FOR
}
else // Edición de las tropas en otras aldeas, proceso parecido al anterior pero trabajando sobre la tabla refuerzos
{
$dx = $_POST['rx'];
$dy = $_POST['ry'];
$tropas_visitadas = array();
$sql = "SELECT `idtropa`, `cantidad` FROM `".$this->config->get('PREFIX')."refuerzos` WHERE `ox`= ".$ox." AND `oy`= ".$oy." AND `dx`= ".$dx." AND `dy`= ".$dy." ORDER BY `idtropa` ASC";
$datos_cargados = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ($un_dato = mysql_fetch_assoc($datos_cargados)) // Buscamos y actualizamos todos las tropas ya cargadas
{
foreach ($id_tropas as $id)
{
if ($un_dato['idtropa'] == $id) // Encontramos una tropa cargada ...
{
if (($un_dato['cant'] != $_POST[$id])) // La cantidad ha sido modificada ...
{
if ($_POST[$id] == 0 or empty($_POST[$id])) // a cero o borrada de la tabla sin ingresar cantidad ...
{
$sql = "DELETE FROM `".$this->config->get('PREFIX')."refuerzos` WHERE `idtropa` = ".$id." AND `ox`= ".$ox." AND `oy`= ".$oy." AND `dx`= ".$dx." AND `dy`= ".$dy;
} else { // o a algún otro valor ...
$sql = "UPDATE `".$this->config->get('PREFIX')."refuerzos` SET `cantidad` = ".$_POST[$id]." WHERE `idtropa` = ".$id." AND `ox`= ".$ox." AND `oy`= ".$oy." AND `dx`= ".$dx." AND `dy`= ".$dy;
}
mysql_query($sql, $this->db) or die(mysql_error($this->db)); // Actualizamos o Borramos según el condicional anterior.
}
$tropas_visitadas[] = $id; // Registramos las tropas que se encuentran cargadas.
break; // Salimos del FOR, ya que para que seguir si ya hubo coincidencia.
}
} // FIN FOR
} // FIN WHILE
foreach ($id_tropas as $id) // Ahora verificamos aquellas tropas que
{ // no se encuentran cargadas.
if (!in_array($id,$tropas_visitadas) and ($_POST[$id]!=0)) // Si la tropa no se encuentra cargada en la BD y la cantidad
{ // es distinta de cero ...
$sql = "INSERT INTO `".$this->config->get('PREFIX')."refuerzos` (`idtropa`,`ox`,`oy`,`dx`,`dy`,`cantidad`) VALUES (".$id.",".$ox.",".$oy.",".$dx.",".$dy.",".$_POST[$id].")";
mysql_query($sql, $this->db) or die(mysql_error($this->db)); // Insertamos la nueva información.
}
} // FIN FOR
}
$this->modificacion();
header("Location: index.php?ctrl=Tropas&mod=tropas");
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
public function borrando()
{
if ( isset($_GET['x']) and isset($_GET['y']) )
{
$x = (int) $_GET['x']; $y = (int) $_GET['y'];
$sql = "";
if (!isset($_GET['rx']) and !isset($_GET['ry']))
{
$sql = "DELETE FROM `".$this->config->get('PREFIX')."tropas_aldea` WHERE `ox`= ".$x." AND `oy`= ".$y;
} else {
$rx = (int) $_GET['rx']; $ry = (int) $_GET['ry'];
$sql = "DELETE FROM `".$this->config->get('PREFIX')."refuerzos` WHERE `ox`= ".$x." AND `oy`= ".$y." AND `dx`= ".$rx." AND `dy`= ".$ry;
}
mysql_query($sql, $this->db) or die(mysql_error($this->db));
$this->modificacion();
header("Location: index.php?crtl=Tropas&mod=tropas");
} else return 'EPT04';
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
public function todas()
{
$arreglo = array();
// primero obtenemos los datos de todos los usuarios activos
$sql = "SELECT `nombre`, `raza` FROM `".$this->config->get('PREFIX')."usuario` WHERE `estado`='Activo' ORDER BY `nombre` ASC";
$jugadores = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$cont = 0;
while ( $player = mysql_fetch_assoc($jugadores) )
{
$arreglo[$cont] = array(
'player'=> $player['nombre'],
'raza'=> $player['raza'],
't0'=> 0, 't1'=> 0, 't2'=> 0, 't3'=> 0, 't4'=> 0,
't5'=> 0, 't6'=> 0, 't7'=> 0, 't8'=> 0, 't9'=> 0
);
$sql = "SELECT
`idtropa`,
`cantidad`
FROM `".$this->config->get('PREFIX')."tropas_aldea`
WHERE (`ox` , `oy`) IN (
SELECT `x` , `y`
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre` = '".$player['nombre']."' )";
$sql_en = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $aux = mysql_fetch_assoc($sql_en) )
{
$it = $aux['idtropa'] - (int) ($aux['idtropa']/10) * 10;
$arreglo[$cont]['t'.$it] += $aux['cantidad'];
}
$sql = "SELECT
`idtropa`,
`cantidad`
FROM `".$this->config->get('PREFIX')."refuerzos`
WHERE (`ox` , `oy`) IN (
SELECT `x` , `y`
FROM `".$this->config->get('PREFIX')."aldea`
WHERE `usuario_nombre` = '".$player['nombre']."' )";
$sql_ref = mysql_query($sql, $this->db) or die(mysql_error($this->db));
while ( $aux = mysql_fetch_assoc($sql_ref) )
{
$it = $aux['idtropa'] - (int) ($aux['idtropa']/10) * 10;
$arreglo[$cont]['t'.$it] += $aux['cantidad'];
}
mysql_free_result( $sql_en ); mysql_free_result( $sql_ref );
$cont++;
}
return $arreglo;
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
// devulve la velocidad de determinada tropa
private function DimeVelocidad($codtropa)
{
// Arreglo con los tiempos
$velocidad = array();
$velocidad[0] = 99;
// Romanos // Germanos // Galos
$velocidad[10] = 6; $velocidad[20] = 7; $velocidad[30] = 7;
$velocidad[11] = 5; $velocidad[21] = 7; $velocidad[31] = 6;
$velocidad[12] = 7; $velocidad[22] = 6; $velocidad[32] = 17;
$velocidad[13] = 16; $velocidad[23] = 9; $velocidad[33] = 19;
$velocidad[14] = 14; $velocidad[24] = 10; $velocidad[34] = 16;
$velocidad[15] = 10; $velocidad[25] = 9; $velocidad[35] = 13;
$velocidad[16] = 4; $velocidad[26] = 4; $velocidad[36] = 4;
$velocidad[17] = 3; $velocidad[27] = 3; $velocidad[37] = 3;
$velocidad[18] = 4; $velocidad[28] = 4; $velocidad[38] = 5;
$velocidad[19] = 5; $velocidad[29] = 5; $velocidad[39] = 5;
return $velocidad[$codtropa];
}
// devuelve la clasificación de determinada tropa según el tipo de busqueda que se este haciendo
private function ComoSeClasifica ($codtropa, $estilo)
{
switch ($estilo)
{
case 'general':
$ofensivas = array(12,14,15,16,17,20,22,25,26,27,31,33,35,36,37);
$defensivas = array(10,11,21,24,30,34);
if (in_array($codtropa,$ofensivas)) return 'off';
elseif (in_array($codtropa,$defensivas)) return 'def';
elseif (in_array($codtropa,array(13,23,32))) return 'spy';
break;
case 'off':
if (in_array($codtropa,array(12,20,22,31))) return 'inf'; // infanteria
elseif (in_array($codtropa,array(14,15,25,33,35))) return 'cab'; // caballeria
elseif (in_array($codtropa,array(16,26,36))) return 'ari'; // arietes
elseif (in_array($codtropa,array(17,27,37))) return 'cat'; // catapultas
break;
case 'def':
if (in_array($codtropa,array(11,24,34))) return 'inf'; // contra infanteria
elseif (in_array($codtropa,array(10,21,30))) return 'cab'; // contra caballeria
break;
}
}
// calcula la distancia entre dos puntos, en donde x1, y1 origen | x2, y2 destino
private function CalcularDistancia ($x1, $y1, $x2, $y2)
{
$dx = $x1 - $x2;
$dy = $y1 - $y2;
$aux = ($dx * $dx) + ($dy * $dy);
return sqrt($aux);
}
// devuelve el tiempo que tarda determinada tropa en recorrer cierta distancia
private function CalcularTiempo ($codtropa, $distancia)
{
$tiempo = $distancia / $this->DimeVelocidad($codtropa);
$horas = (int) $tiempo; // Horas del Tiempo
$aux = $tiempo * 60; // Tiempo en Minutos
$minutos = $aux%60; // Minutos del Tiempo
$aux = $tiempo * 3600; // Tiempo en Segundos
$segundos = (int) ($aux - $horas*3600 - $minutos*60); // Segundos del Tiempo
if ($horas<100)
if ($horas<10) $AdHoras = "00";
else $AdHoras = "0";
else $AdHoras = "";
if ($minutos<10) $AdMinutos = "0";
else $AdMinutos = "";
if ($segundos<10) $AdSegundos = "0";
else $AdSegundos = "";
return $AdHoras.$horas." : ".$AdMinutos.$minutos." : ".$AdSegundos.$segundos;
}
// algoritmo de ordenación por inserción del arreglo a retonar: DEVOLVER
private function ordenacion_insercion(&$A, $N)
{
for ($p = 1; $p < $N; $p++)
{
$tmp = $A[$p];
$j = $p - 1;
while (($j >= 0) and ($tmp['tiempo'] < $A[$j]['tiempo']))
{
$A[$j + 1] = $A[$j];
$j--;
}
$A[$j + 1] = $tmp;
}
}
// ESTA ES LA FUNCIÓN LLAMADA POR EL CONTROLADOR
public function Buscar(&$error)
{
// |||| Inicializacion de las variables necesarias |||||
$DEVOLDER = array(); // Matriz que devuelve la función
$ObjX = (int) $_POST['x']; // coordenada x del objetivo
$ObjY = (int) $_POST['y']; // coordenada y del objetivo
$TipoBusqueda = $_POST['tipo'];
if ($_POST['tipo'] == 'Elegir...') { $error = 'EPB1'; return true; }
/* El siguiente arreglo es usado para realizar el filtrado de las tropas en base a los
* comodines u la cantidades mínimas que puede ingresar el usuario a la hora de realizar
* la busqueda. Contiene FALSE cuando el minimo es comodin y TRUE cuando se especifica
* un valor */
$vacios = array();
if ( isset($_POST['inf']) and !empty($_POST['inf']) and ((int) $_POST['inf'] > 0) )
$vacios['inf'] = true;
else $vacios['inf'] = false;
if ( isset($_POST['cab']) and !empty($_POST['cab']) and ((int) $_POST['cab'] > 0) )
$vacios['cab'] = true;
else $vacios['cab'] = false;
if ( isset($_POST['ari']) and !empty($_POST['ari']) and ((int) $_POST['ari'] > 0) )
$vacios['ari'] = true;
else $vacios['ari'] = false;
if ( isset($_POST['cat']) and !empty($_POST['cat']) and ((int) $_POST['cat'] > 0) )
$vacios['cat'] = true;
else $vacios['cat'] = false;
// ||||| Comenzamos con el proceso de búsqueda ||||||
$sql = "SELECT
A.`usuario_nombre`, TA.`ox`, TA.`oy`, TA.`idtropa`, TA.`cantidad`
FROM
`".$this->config->get('PREFIX')."tropas_aldea` AS TA,
`".$this->config->get('PREFIX')."aldea` AS A
WHERE
TA.`ox` = A.`x` AND TA.`oy` = A.`y`
ORDER BY
A.`usuario_nombre` ASC, TA.`ox` ASC, TA.`oy` ASC, TA.`idtropa` ASC";
$resultado = mysql_query($sql, $this->db) or die(mysql_error($this->db));
$indice = 0; $TotalRegistros = mysql_num_rows($resultado);
$row = mysql_fetch_assoc($resultado);
while ( $indice < $TotalRegistros )
{
$jugador = $row['usuario_nombre'];
$ori_X = $row['ox'];
$ori_Y = $row['oy'];
$tiempo = ""; // variable auxiliar que guarda el tiempo más corto
$tropas = array();
$UltimaTropa = 0;
while ($jugador == $row['usuario_nombre'] and
$ori_X == $row['ox'] and
$ori_Y == $row['oy'] )
{
// Atendemos sólo tropas del tipo pedido
if ($this->ComoSeClasifica($row['idtropa'],'general') == $TipoBusqueda)
{
if ($TipoBusqueda == 'spy') $NN = 'spy';
else $NN = $this->ComoSeClasifica($row['idtropa'],$TipoBusqueda);
if ($row['cantidad'] >= (int) $_POST[$NN])
{
// El tiempo se calcula en base a la tropa más lenta.
$vel_ul = $this->DimeVelocidad($UltimaTropa);
$vel_nu = $this->DimeVelocidad($row['idtropa']);
if ( $vel_ul > $vel_nu )
{
$tiempo = $this->CalcularTiempo($row['idtropa'],
$this->CalcularDistancia($ori_X, $ori_Y, $ObjX, $ObjY));
$UltimaTropa = $row['idtropa'];
}
$tropas[] = array('id'=>$row['idtropa'], 'cant'=>$row['cantidad']);
}
} // FIN IF de TipoBusqueda
$indice+=1;
$row = mysql_fetch_assoc($resultado);
} // FIN WHILE lvl 1
/* ### COMIENZA EL CHEQUEO POR LOS MÍNIMOS Y LOS COMODINES
* se ha de verificar que, si se ingresó al menos una cantidad mínima en alguno de
* los tipos, la lista de tropas debe contener el tipo indicado. De lo contrario
* se da de baja la lista de las tropas
*/
reset($vacios); // reiniciamos los punteros internos para el while
/* Este arreglo sólo contiene TRUE si se encontró una tropa de la cual se ha especificado
* un valor concreto como mínimo */
$pasando = array('inf'=>false,'cab'=>false,'ari'=>false,'cat'=>false);
while( list( $key, $valor ) = each( $vacios ) )
{
if ($valor)
{ // comprobamos que halla tropas de ese tipo en el arreglo
reset($tropas); $i = 0;
while( list(, $aux ) = each( $tropas ) )
{
if ($this->ComoSeClasifica($aux['id'], $TipoBusqueda) == $key)
{
$pasando[$key] = true; // se encontre una tropa del mínimo solicitado
break;
}
++$i;
}
}
}
reset($vacios); reset($pasando); $i = 0;
while ( $i < 5 )
{
list($key1, $aux ) = each( $vacios );
list($key2, $aux2 ) = each( $pasando );
if ($aux != $aux2)
{
unset($tropas);
break;
}
++$i;
}
/* TERMINA EL CHEQUEO #### */
if (!empty($tropas)) // Registramos si contiene las tropas solicitadas
$DEVOLVER[] = array(
'player' => $jugador,
'ox' => $ori_X,
'oy' => $ori_Y,
'tropas' => $tropas,
'tiempo' => $tiempo
);
} // FIN WHILE lvl 0
mysql_free_result($resultado);
unset($tropas,$pasando,$vacios,$aux,$jugador);
if (empty($DEVOLVER)) { $error = 'EPB2'; return true; }
else
{
$this->ordenacion_insercion($DEVOLVER, count($DEVOLVER));
return $DEVOLVER;
}
}
} // Fin clase ...
?>