Version 1.14a

This commit is contained in:
nemunaire 2020-11-15 16:12:32 +01:00
commit dc48225dc9
1094 changed files with 189052 additions and 13889 deletions

View file

@ -0,0 +1,210 @@
<?php
require_once("Class/Donnees/interface.php");
class dAlliancesBatiments implements Donnees
{
public static function metal($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$metal = ceil(pow(1.5, $niveau)*68);
break;
case 1:
$metal = ceil(pow(1.6, $niveau)*53);
break;
case 2:
$metal = ceil(pow(1.5, $niveau)*242);
break;
case 3:
$metal = ceil(pow(1.5, $niveau)*92);
break;
case 4:
$metal = ceil(pow(1.73, $niveau)*800);
break;
case 5:
$metal = ceil(pow(2, $niveau)*750);
break;
default:
trigger_error("Batiment d'alliance ".$id." introuvable dans les données", E_USER_ERROR);
}
return $metal;
}
public static function cristal($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$cristal = ceil(pow(1.5, $niveau)*17);
break;
case 1:
$cristal = ceil(pow(1.6, $niveau)*27);
break;
case 2:
$cristal = ceil(pow(1.5, $niveau)*72);
break;
case 3:
$cristal = ceil(pow(1.5, $niveau)*37);
break;
case 4:
$cristal = ceil(pow(1.73, $niveau)*420);
break;
case 5:
$cristal = ceil(pow(2, $niveau)*500);
break;
default:
trigger_error("Batiment d'alliance ".$id." introuvable dans les données", E_USER_ERROR);
}
return $cristal;
}
public static function hydrogene($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$hydrogene = 0;
break;
case 1:
$hydrogene = 0;
break;
case 2:
$hydrogene = 0;
break;
case 3:
$hydrogene = 0;
break;
case 4:
$hydrogene = ceil(pow(1.68, $niveau)*285);
break;
case 5:
$hydrogene = 0;
break;
default:
trigger_error("Batiment d'alliance ".$id." introuvable dans les données", E_USER_ERROR);
}
return $hydrogene;
}
public static function credits($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$credits = ceil(pow(1.68, $niveau)*25);
break;
case 1:
$credits = ceil(pow(1.68, $niveau)*85);
break;
case 2:
$credits = ceil(pow(1.68, $niveau)*185);
break;
case 3:
$credits = ceil(pow(1.68, $niveau)*285);
break;
case 4:
$credits = ceil(pow(1.68, $niveau)*385);
break;
case 5:
$credits = ceil(pow(1.68, $niveau)*485);
break;
default:
trigger_error("Batiment d'alliance ".$id." introuvable dans les données", E_USER_ERROR);
}
return $credits;
}
public static function temps($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$sec = pow(1.5, $niveau)*6;
break;
case 1:
$sec = pow(1.55, $niveau)*6;
break;
case 2:
$sec = pow(1.624, $niveau)*6;
break;
case 3:
$sec = pow(1.597, $niveau)*6;
break;
case 4:
$sec = pow(1.7, $niveau)*6;
break;
case 5:
$sec = ceil(pow(2, $niveau)*720);
break;
default:
trigger_error("Batiment d'alliance ".$id." introuvable dans les données", E_USER_ERROR);
}
//Accélération du temps de construction
$sec /= VITESSE;
return $sec;
}
public static function image($id, surface $planete)
{
if ($planete->race == "covenant")
{
switch($id)
{
case 0:
//return "batimentcovieux4.jpg";
break;
}
return Donnees::image_covenant_default;
}
elseif ($planete->race == "humain")
{
switch($id)
{
case 0:
//return "batimentcovieux4.jpg";
break;
}
return Donnees::image_humain_default;
}
else
trigger_error("Impossible de trouver la race pour ".$planete->race, E_USER_ERROR);
}
public static function needed($id, surface $planete, $print = false)
{
$neededAlliancesBatiments =
array(
0,
array(
array('batiments', 0, 1)
),
array(
array('batiments', 0, 3)
),
array(
array('batiments', 0, 5)
),
array(
array('batiments', 0, 4)
),
array(
array('batiments', 0, 2)
)
);
if ($print)
return dDonnees::print_neededCheck($neededAlliancesBatiments[$id], $planete);
else
return dDonnees::neededCheck($neededAlliancesBatiments[$id], $planete);
}
}
?>

View file

@ -0,0 +1,517 @@
<?php
require_once("Class/Donnees/interface.php");
class dBatiments implements Donnees
{
public static function metal($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$metal = ceil(pow(1.5, $niveau)*68);
break;
case 1:
$metal = ceil(pow(1.6, $niveau)*53);
break;
case 2:
$metal = ceil(pow(1.5, $niveau)*242);
break;
case 3:
$metal = ceil(pow(1.5, $niveau)*92);
break;
case 4:
//$metal = ceil(pow(1.73, $niveau)*800);
$metal = ceil(pow(3, $niveau)*5000);
break;
case 5:
$metal = ceil(pow(2, $niveau)*750);
break;
case 6:
$metal = ceil(pow(2, $niveau)*200);
break;
case 7:
$metal = ceil(pow(2, $niveau)*520);
break;
case 8:
$metal = ceil(pow(2, $niveau)*600);
break;
case 9:
$metal = ceil(pow(2, $niveau)*200);
break;
case 10:
$metal = ceil(pow(2, $niveau)*400);
break;
case 11:
$metal = ceil(pow(1.7, $niveau)*600);
break;
case 12:
$metal = ceil(pow($niveau, 2.075)*1000+1500);
break;
case 13:
$metal = ceil(pow($niveau,2.8)*1000+299000);
break;
case 14:
$metal = ceil(pow($niveau, 2)*1200+140000);
break;
case 15:
$metal = ceil(pow($niveau, 2)*1000+80000);
break;
case 16:
$metal = ceil(pow($niveau, 2)*850+60000);
break;
case 17:
$metal = ceil(pow($niveau, 2.5)*500 -300);
break;
default:
trigger_error("Batiment ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
//Bonus technologique pour les mines
if ($id <= 3)
{
if ($planete->technologies[0] &262144)
{
$metal *= 0.85;
}
elseif ($planete->technologies[0] &131072)
{
$metal *= 0.9;
}
elseif ($planete->technologies[0] &65536)
{
$metal *= 0.95;
}
}
return $metal;
}
public static function cristal($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$cristal = ceil(pow(1.5, $niveau)*17);
break;
case 1:
$cristal = ceil(pow(1.6, $niveau)*27);
break;
case 2:
$cristal = ceil(pow(1.5, $niveau)*72);
break;
case 3:
$cristal = ceil(pow(1.5, $niveau)*37);
break;
case 4:
//$cristal = ceil(pow(1.73, $niveau)*420);
$cristal = ceil(pow(3, $niveau)*3000);
break;
case 5:
$cristal = ceil(pow(2, $niveau)*500);
break;
case 6:
$cristal = ceil(pow(2, $niveau)*150);
break;
case 7:
$cristal = ceil(pow(2, $niveau)*380);
break;
case 8:
$cristal = ceil(pow(2, $niveau)*450);
break;
case 9:
$cristal = ceil(pow(2, $niveau)*100);
break;
case 10:
$cristal = ceil(pow(2, $niveau)*260);
break;
case 11:
$cristal = ceil(pow(1.7, $niveau)*420);
break;
case 12:
$cristal = ceil(pow($niveau, 1.8)*1000+1000);
break;
case 13:
$cristal = ceil(pow($niveau,2.5)*1000+149000);
break;
case 14:
$cristal = ceil(pow($niveau, 2)*900+99000);
break;
case 15:
$cristal = ceil(pow($niveau, 2)*750+65000);
break;
case 16:
$cristal = ceil(pow($niveau, 2)*650+50000);
break;
case 17:
$cristal = ceil(pow($niveau, 2.4)*400-250);
break;
default:
trigger_error("Batiment ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
//Bonus technologique pour les mines
if ($id <= 3)
{
if ($planete->technologies[0] &262144)
{
$cristal *= 0.85;
}
elseif ($planete->technologies[0] &131072)
{
$cristal *= 0.9;
}
elseif ($planete->technologies[0] &65536)
{
$cristal *= 0.95;
}
}
return $cristal;
}
public static function hydrogene($id, $niveau, surface $planete)
{
switch($id)
{
case 0:
$hydrogene = 0;
break;
case 1:
$hydrogene = 0;
break;
case 2:
$hydrogene = 0;
break;
case 3:
$hydrogene = 0;
break;
case 4:
//$hydrogene = ceil(pow(1.68, $niveau)*285);
$hydrogene = 0;
break;
case 5:
$hydrogene = 0;
break;
case 6:
$hydrogene = 0;
break;
case 7:
$hydrogene = 0;
break;
case 8:
$hydrogene = 0;
break;
case 9:
$hydrogene = 0;
break;
case 10:
$hydrogene = 0;
break;
case 11:
$hydrogene = ceil(pow(1.7, $niveau)*100);
break;
case 12:
$hydrogene = 0;
break;
case 13:
$hydrogene = 0;
break;
case 14:
$hydrogene = ceil(pow($niveau, 2)*500+30000);
break;
case 15:
$hydrogene = 0;
break;
case 16:
$hydrogene = 0;
break;
case 17:
$hydrogene = 0;
break;
default:
trigger_error("Batiment ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
//Bonus technologique pour les mines
if ($id <= 3)
{
if ($planete->technologies[0] &262144)
{
$hydrogene *= 0.85;
}
elseif ($planete->technologies[0] &131072)
{
$hydrogene *= 0.9;
}
elseif ($planete->technologies[0] &65536)
{
$hydrogene *= 0.95;
}
}
return $hydrogene;
}
public static function credits($id, $niveau, surface $planete)
{
return 0;
}
public static function temps($id, $niveau, surface $planete, $demolition = false)
{
switch($id)
{
case 0:
$sec = pow(1.5, $niveau)*6;
break;
case 1:
$sec = pow(1.55, $niveau)*6;
break;
case 2:
$sec = pow(1.624, $niveau)*6;
break;
case 3:
$sec = pow(1.597, $niveau)*6;
break;
case 4:
$sec = pow(1.7, $niveau)*6;
break;
case 5:
$sec = ceil(pow(2, $niveau)*720);
break;
case 6:
$sec = ceil(pow(2, $niveau)*720);
break;
case 7:
$sec = ceil(pow(2, $niveau)*420);
break;
case 8:
$sec = ceil(pow(2, $niveau)*600);
break;
case 9:
$sec = ceil(pow(2, $niveau)*300);
break;
case 10:
$sec = ceil(pow(2, $niveau)*1200);
break;
case 11:
$sec = ceil((pow(1.9, $niveau)*800));
break;
case 12:
$sec = ceil(pow($niveau, 2.5)*60+4)*60;
break;
case 13:
$sec = ceil(pow($niveau, 1.6)*60+60)*60;
break;
case 14:
$sec = ceil(pow($niveau, 2)*5+3)*60;
break;
case 15:
$sec = pow($niveau, 2)*240;
break;
case 16:
$sec = pow($niveau, 2)*180;
break;
case 17:
$sec = pow($niveau, 1.65)*3600;
break;
default:
trigger_error("Batiment ".$id." introuvable dans les données", E_USER_ERROR);
}
//On applique le bonus de temps des ingénieurs et des centrales informatiques
if ($id == 11 && $planete->casernes[7])
$sec /= (1.0025 * $planete->casernes[7]);
elseif ($id != 11 && ($planete->casernes[7] || $planete->batiments[11]))
$sec /= (pow(1.23, $planete->batiments[11]) + 1.0025 * $planete->casernes[7]);
//Accélération du temps de construction
$sec /= VITESSE;
if ($demolition)
return $sec * Donnees::coeff_demolition;
else
return $sec;
}
public static function type($id)
{
switch($id)
{
case 0:
case 1:
case 2:
case 3:
case 4:
return 1;
case 6:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
return 2;
case 5:
case 7:
case 8:
case 9:
return 4;
return 6;
default:
trigger_error("Bâtiment ".$id." introuvable dans les données", E_USER_ERROR);
}
}
public static function image($id, surface $planete)
{
if ($planete->race == "covenant")
{
switch($id)
{
case 0:
return "batimentcovieux4.jpg";
break;
case 1:
return "cristaloo3.png";
break;
case 2:
return "powersupplycoviejq1.jpg";
break;
case 3:
return "solaire.jpg";
break;
case 4:
return "sanstitrevi7.jpg";
break;
case 5:
return "oeilduprophetewj6.jpg";
break;
case 6:
return "covielabocn5.jpg";
break;
case 7:
return "chantierterrestrehg1.jpg";
break;
case 8:
return "sanstitretruecolor09zn6.jpg";
break;
case 9:
return "caserncov0ry.jpg";
break;
case 10:
return "stockagebasement1cs10bl.jpg";
break;
case 11:
return "ordianteur_hologramme.jpg";
break;
}
return Donnees::image_covenant_default;
}
elseif ($planete->race == "humain")
{
switch($id)
{
case 0:
return "mine_m.jpg";
break;
case 1:
return "mine_c.png";
break;
case 2:
return "synchroniseur.jpg";
break;
case 3:
return "centrale solaire.jpg";
break;
case 4:
return "centrale electrique.jpg";
break;
case 5:
return "baseradardl3.jpg";
break;
case 6:
return "recherches.jpg";
break;
case 7:
return "chantierterrestrecopybj8.jpg";
break;
case 8:
return "chantier spatial.jpg";
break;
case 9:
return "ecole militaire.jpg";
break;
case 10:
return "stockage.jpg";
break;
case 11:
return "search0yp.jpg";
break;
}
return Donnees::image_humain_default;
}
else
trigger_error("Impossible de trouver la race pour ".$planete->race, E_USER_ERROR);
}
public static function needed($id, surface $planete, $print = false)
{
$neededBatiments =
array (
0,
0,
0,
0,
array(
array("batiments", 3, 12),
array("batiments_max", 4, 4)
),
0,
0,
array(
array("technologies", 2,3, 9)
),
array(
array("technologies", 2,4, 17)
),
0,
0,
array(
array("technologies", 1,12, 4096)
),
0,
array(
array("technologies", 3,8, 256)
),
array(
array("technologies", 7,12, 4096)
),
array(
array("technologies", 3,6, 64)
),
array(
array("technologies", 3,7, 128)
),
0
);
if ($print)
return dDonnees::print_neededCheck($neededBatiments[$id], $planete);
else
return dDonnees::neededCheck($neededBatiments[$id], $planete);
}
}
?>

View file

@ -0,0 +1,301 @@
<?php
require_once("Class/Donnees/interface.php");
class dCaserne implements Donnees
{
public static function metal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$metal = 80;
break;
case 1:
$metal = 110;
break;
case 2:
$metal = 150;
break;
case 3:
$metal = 220;
break;
case 4:
$metal = 180;
break;
case 5:
$metal = 25000;
break;
case 6:
$metal = 100;
break;
case 7:
$metal = 90;
break;
case 8:
$metal = 300;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$metal *= 0.9;
return $metal * $nombre;
}
public static function cristal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$cristal = 45;
break;
case 1:
$cristal = 90;
break;
case 2:
$cristal = 105;
break;
case 3:
$cristal = 150;
break;
case 4:
$cristal = 100;
break;
case 5:
$cristal = 10000;
break;
case 6:
$cristal = 100;
break;
case 7:
$cristal = 105;
break;
case 8:
$cristal = 250;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$cristal *= 0.9;
return $cristal * $nombre;
}
public static function hydrogene($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$hydrogene = 0;
break;
case 1:
$hydrogene = 0;
break;
case 2:
$hydrogene = 20;
break;
case 3:
$hydrogene = 0;
break;
case 4:
$hydrogene = 0;
break;
case 5:
$hydrogene = 0;
break;
case 6:
$hydrogene = 0;
break;
case 7:
$hydrogene = 0;
break;
case 8:
$hydrogene = 0;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$hydrogene *= 0.9;
return $hydrogene * $nombre;
}
public static function credits($id, $nombre, surface $planete)
{
return 0;
}
public static function temps($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$temps = 60;
$moins = 1;
break;
case 1:
$temps = 240;
$moins = 2;
break;
case 2:
$temps = 240;
$moins = 3;
break;
case 3:
$temps = 720;
$moins = 5;
break;
case 4:
$temps = 300;
$moins = 3;
break;
case 5:
$temps = 29700;
$moins = 10;
break;
case 6:
$temps = 90;
$moins = 2;
break;
case 7:
$temps = 90;
$moins = 2;
break;
case 8:
$temps = 900;
$moins = 5;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte de la vitesse
$temps /= VITESSE;
//On tient compte des bonus
return ceil($temps/pow(1.25, ($planete->batiments[9] - $moins))) * $nombre;
}
public static function image($id, surface $planete)
{
if ($planete->race == "covenant")
{
array('','','','','','','','','');
switch($id)
{
case 0:
return "grunt1.jpg";
break;
case 1:
return "jackal.jpg";
break;
case 2:
return "94990342wb4.jpg";
break;
case 3:
return "98004530fx3.jpg";
break;
case 4:
return "88091275ja8.jpg";
break;
case 5:
return "hunter1.jpg";
break;
case 6:
return "81770345oo4.jpg";
break;
case 7:
return "88218731ts1.jpg";
break;
case 8:
return "72188202fg9.jpg";
break;
}
return Donnees::image_covenant_default;
}
elseif ($planete->race == "humain")
{
switch($id)
{
case 0:
return "marines.jpg";
break;
case 1:
return "marinehf0.jpg";
break;
case 2:
return "grenadier.jpg";
break;
case 3:
return "TCAO2.jpg";
break;
case 4:
return "sniper.jpg";
break;
case 5:
return "spartan.jpg";
break;
case 6:
return "ingenieurs.jpg";
break;
case 7:
return "exosquelettehbpb2.jpg";
break;
}
return Donnees::image_humain_default;
}
else
trigger_error("Impossible de trouver la race pour ".$planete->race, E_USER_ERROR);
}
public static function needed($id, surface $planete, $print = false)
{
$neededCaserne =
array(
array(
array('batiments', 9, 1)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 3)
),
array(
array('batiments', 9, 5)
),
array(
array('batiments', 9, 3)
),
array(
array('batiments', 9, 10)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 2)
),
array(
array('batiments', 9, 5)
)
);
if ($print)
return dDonnees::print_neededCheck($neededCaserne[$id], $planete);
else
return dDonnees::neededCheck($neededCaserne[$id], $planete);
}
}
?>

View file

@ -0,0 +1,202 @@
<?php
if(!defined('ONYX')) exit;
interface Donnees
{
const image_covenant_default = "../covenant_na.jpg";
const image_humain_default = "../humain_na.jpg";
const coeff_demolition = 0.6;
public static function metal($id, $niveau, surface $planete);
public static function cristal($id, $niveau, surface $planete);
public static function hydrogene($id, $niveau, surface $planete);
public static function credits($id, $niveau, surface $planete);
public static function temps($id, $niveau, surface $planete);
public static function image($id, surface $planete);
public static function needed($id, surface $planete, $print = false);
}
class dDonnees{
static function tailleFile(surface $planete)
{
//On calcul la taille maximale de la file d'attente
if (!empty($planete->technologies[1]))
{
if (($planete->technologies[1] &131072) == 131072) return 5;
elseif (($planete->technologies[1] &65536) == 65536) return 4;
elseif (($planete->technologies[1] &32768) == 32768) return 3;
else return 2;
}
else return 3; //Au cas où il n'y ait pas de technologie sur le lieu, on fixe la taille de la file d'attente
}
static function neededCheck($tableau, surface $planete)
{
if (!is_array($tableau)) return true;
else
{
foreach ($tableau as $need)
{
switch($need[0])
{
case 'batiments':
if (get_class($planete) == "Planete" && $planete->batiments[$need[1]] < $need[2])
return false;
break;
case 'batiments_max':
if (get_class($planete) == "Planete" && $planete->batiments[$need[1]] > $need[2])
return false;
break;
case 'technologies':
if (((int)$planete->technologies[$need[1]]& $need[3]) != $need[3])
return false;
break;
case 'casernes':
if ($planete->casernes[$need[1]] < $need[2])
return false;
break;
case 'terrestres':
if ($planete->terrestres[$need[1]] < $need[2])
return false;
break;
case 'vaisseaux':
if ($planete->vaisseaux[$need[1]] < $need[2])
return false;
break;
default:
return false;
}
}
return true;
}
}
static function print_neededCheck($tableau, surface $planete)
{
global $LANG;
$race = $planete->race;
if (!is_array($tableau)) return 'Débloqué';
else
{
$return = '';
foreach ($tableau as $need)
{
switch($need[0])
{
case 'batiments':
if ($planete->batiments[$need[1]] < $need[2])
$return .= '<span class="lack">'.ucfirst($LANG[$race]["batiments"]["noms_sing"][$need[1]]).' niveau '.$need[2].' (batiment)</span><br />';
else
$return .= ucfirst($LANG[$race]["batiments"]["noms_sing"][$need[1]]).' niveau '.$need[2].' (batiment)<br />';
break;
case 'batiments_max':
if ($planete->batiments[$need[1]] > $need[2])
$return .= '<span class="lack">'.ucfirst($LANG[$race]["batiments"]["noms_sing"][$need[1]]).' < niveau '.($need[2]+1).' (batiment)</span><br />';
else
$return .= ucfirst($LANG[$race]["batiments"]["noms_sing"][$need[1]]).' < niveau '.($need[2]+1).' (batiment)<br />';
break;
case 'technologies':
if (((int)$planete->technologies[$need[1]]& $need[3]) != $need[3])
$return .= '<span class="lack">'.$LANG[$race]["technologies"]["noms_sing"][$need[1]][$need[2]].' (technologie)</span><br />';
else
$return .= $LANG[$race]["technologies"]["noms_sing"][$need[1]][$need[2]].' (technologie)<br />';
break;
case 'casernes':
if ($planete->casernes[$need[1]] < $need[2])
$return .= '<span class="lack">'.$need[2].' '.$LANG[$race]["caserne"]["noms_pluriel"][$need[1]].' (unité de la caserne)</span><br />';
else
$return .= $need[2].' '.$LANG[$race]["caserne"]["noms_pluriel"][$need[1]].' (unité de la caserne)<br />';
break;
case 'terrestres':
if ($planete->terrestres[$need[1]] < $need[2])
$return .= '<span class="lack">'.$need[2].' '.$LANG[$race]["terrestre"]["noms_pluriel"][$need[1]].' (unité du chantier terrestre)</span><br />';
else
$return .= $need[2].' '.$LANG[$race]["terrestre"]["noms_pluriel"][$need[1]].' (unité du chantier terrestre)<br />';
break;
case 'vaisseaux':
if ($planete->vaisseaux[$need[1]] < $need[2])
$return .= '<span class="lack">'.$need[2].' '.$LANG[$race]["vaisseaux"]["noms_pluriel"][$need[1]].' (unité du chantier spatial)</span><br />';
else
$return .= $need[2].' '.$LANG[$race]["vaisseaux"]["noms_pluriel"][$need[1]].' (unité du chantier spatial)<br />';
break;
}
}
return $return;
}
}
static function nameVAR($name)
{
if ($name == "alli_batiments")
return "alli_batiments";
elseif ($name == "batiments")
return "batiments";
elseif ($name == "technologies")
return "technologies";
elseif ($name == "casernes")
return "caserne";
elseif ($name == "terrestres")
return "terrestre";
elseif ($name == "vaisseaux")
return "spatial";
elseif ($name == "coeff_bat")
return "coeff";
}
static function capaciteVilles(surface $planete)
{
return $planete->cases * pow($planete->batiments[17], -3) + 10;
}
static function nameVilles($level)
{
switch ($level)
{
case 0:
case 1:
case 2:
return "Poste d'observation taille ".($level+1);
break;
case 3:
case 4:
case 5:
return "Poste avancé taille ".($level-2);
break;
case 6:
case 7:
case 8:
return "Colonie taille ".($level-5);
break;
case 9:
case 10:
case 11:
case 12:
return "Ville taille ".($level-8);
break;
case 13:
case 14:
case 15:
return "Cité taille ".($level-12);
break;
case 16:
case 17:
case 18:
return "Grande cité taille ".($level-15);
break;
case 19:
return "Mégapole";
break;
case 20:
return "Mégalopole";
break;
default:
trigger_error("Taille de ville incorrect !");
}
}
}
?>

View file

@ -0,0 +1,631 @@
<?php
require_once("Class/Donnees/interface.php");
class dSpatial implements Donnees
{
public static function metal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$metal = 1000;
break;
case 1:
$metal = 4000;
break;
case 2:
$metal = 4000;
break;
case 3:
$metal = 9000;
break;
case 4:
$metal = 9000;
break;
case 5:
$metal = 1000;
break;
case 6:
$metal = 15000;
break;
case 7:
$metal = 1800;
break;
case 8:
$metal = 2550;
break;
case 9:
$metal = 12950;
break;
case 10:
$metal = 26000;
break;
case 11:
$metal = 60000;
break;
case 12:
$metal = 500000;
break;
case 13:
$metal = 500000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$metal *= 0.9;
return $metal * $nombre;
}
public static function cristal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$cristal = 800;
break;
case 1:
$cristal = 3000;
break;
case 2:
$cristal = 3000;
break;
case 3:
$cristal = 9000;
break;
case 4:
$cristal = 9000;
break;
case 5:
$cristal = 1200;
break;
case 6:
$cristal = 9000;
break;
case 7:
$cristal = 1000;
break;
case 8:
$cristal = 1350;
break;
case 9:
$cristal = 16400;
break;
case 10:
$cristal = 6900;
break;
case 11:
$cristal = 40000;
break;
case 12:
$cristal = 400000;
break;
case 13:
$cristal = 400000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$cristal *= 0.9;
return $cristal * $nombre;
}
public static function hydrogene($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$hydrogene = 0;
break;
case 1:
$hydrogene = 0;
break;
case 2:
$hydrogene = 0;
break;
case 3:
$hydrogene = 1000;
break;
case 4:
$hydrogene = 1000;
break;
case 5:
$hydrogene = 100;
break;
case 6:
$hydrogene = 1000;
break;
case 7:
$hydrogene = 0;
break;
case 8:
$hydrogene = 65;
break;
case 9:
$hydrogene = 100;
break;
case 10:
$hydrogene = 1600;
break;
case 11:
$hydrogene = 3000;
break;
case 12:
$hydrogene = 250000;
break;
case 13:
$hydrogene = 250000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$hydrogene *= 0.9;
return $hydrogene * $nombre;
}
public static function credits($id, $nombre, surface $planete)
{
return 0;
}
public static function temps($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$temps = 1080;
$moins = 1;
break;
case 1:
$temps = 6300;
$moins = 5;
break;
case 2:
$temps = 6300;
$moins = 5;
break;
case 3:
$temps = 8280;
$moins = 5;
break;
case 4:
$temps = 8280;
$moins = 5;
break;
case 5:
$temps = 1440;
$moins = 3;
break;
case 6:
$temps = 7380;
$moins = 5;
break;
case 7:
$temps = 1200;
$moins = 1;
break;
case 8:
$temps = 4680;
$moins = 3;
break;
case 9:
$temps = 16800;
$moins = 6;
break;
case 10:
$temps = 16800;
$moins = 6;
break;
case 11:
$temps = 32400;
$moins = 8;
break;
case 12:
$temps = 117000;
$moins = 12;
break;
case 13:
$temps = 117000;
$moins = 12;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte de la vitesse
$temps /= VITESSE;
//On tient compte des bonus
if (SURFACE == "planete")
return ceil($temps/pow(1.25, ($planete->batiments[8] - $moins))) * $nombre;
else
return ($temps * $nombre);
}
public static function image($id, surface $planete)
{
if ($planete->race == "covenant")
{
switch($id)
{
case 0:
return "cargo2pb6.jpg";
break;
case 1:
return "sanstitre2copiegw9.jpg";
break;
case 2:
return "colocopiers4.jpg";
break;
case 3:
return "sonde_despionnage1.jpg";
break;
case 4:
return "chasseurlourd7id.jpg";
break;
case 5:
return "contactharvestbynameleszk3.jpg";
break;
case 6:
return "vaisseauuu0.jpg";
break;
case 7:
return "vaisseaudebataille9na.jpg";
break;
case 8:
return "pv.jpg";
break;
case 9:
return "stationorbitalezt7.jpg";
break;
case 10:
return "citecovenant.jpg";
break;
}
return Donnees::image_covenant_default;
}
elseif ($planete->race == "humain")
{
switch($id)
{
case 0:
return "csnucargoparabola2mc9.jpg";
break;
case 1:
return "csnucargoladen2al8.jpg";
break;
case 2:
return "colonisation.jpg";
break;
case 3:
//return "";
break;
case 4:
return "longsworduf9.jpg";
break;
case 5:
//return "";
break;
case 6:
//return "";
break;
case 7:
return "frgatecopiegw1.jpg";
break;
case 8:
//return "";
break;
case 9:
return "halcyo15.jpg";
break;
case 10:
return "qsu169.jpg";
break;
}
return Donnees::image_humain_default;
}
else
trigger_error("Impossible de trouver la race pour ".$planete->race, E_USER_ERROR);
}
public static function needed($id, surface $planete, $print = false)
{
$neededSpatial =
array(
array(
array('batiments', 8, 1),
array('technologies', 0,3, 8)
),
array(
array('batiments', 8, 5),
array('technologies', 0,3, 8),
array('technologies', 1,6, 64)
),
array(
array('batiments', 8, 5),
array('technologies', 8,0, 1)
),
array(
array('batiments', 8, 5),
array('technologies', 7,4, 16)
),
array(
array('batiments', 8, 5),
array('technologies', 7,0, 1)
),
array(
array('batiments', 8, 3),
array('technologies', 7,1, 2)
),
array(
array('batiments', 8, 5),
array('technologies', 7,2, 4)
),
array(
array('batiments', 8, 1),
array('technologies', 7,3, 8)
),
array(
array('batiments', 8, 3),
array('technologies', 7,5, 32)
),
array(
array('batiments', 8, 6),
array('technologies', 7,6, 64)
),
array(
array('batiments', 8, 6),
array('technologies', 7,1, 128)
),
array(
array('batiments', 8, 8),
array('technologies', 7,8, 256)
),
array(
array('batiments', 8, 10),
array('technologies', 7,9, 512)
),
array(
array('batiments', 8, 10),
array('technologies', 7,10, 1024)
)
);
if ($print)
return dDonnees::print_neededCheck($neededSpatial[$id], $planete);
else
return dDonnees::neededCheck($neededSpatial[$id], $planete);
}
public static function tailleCales($id)
{
switch($id)
{
case 0:
$vitesse = 10000;
break;
case 1:
$vitesse = 50000;
break;
case 2:
$vitesse = 25000;
break;
case 3:
$vitesse = 25000;
break;
case 4:
$vitesse = 100;
break;
case 5:
$vitesse = 50;
break;
case 6:
$vitesse = 200;
break;
case 7:
$vitesse = 400;
break;
case 8:
$vitesse = 800;
break;
case 9:
$vitesse = 1000;
break;
case 10:
$vitesse = 1500;
break;
case 11:
$vitesse = 50000;
break;
case 12:
$vitesse = 100000;
break;
case 13:
$vitesse = 500;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
return $vitesse;
}
public static function vitesseP($id)
{
switch($id)
{
case 0:
$vitesse = 1080;
break;
case 1:
$vitesse = 6300;
break;
case 2:
$vitesse = 6300;
break;
case 3:
$vitesse = 8280;
break;
case 4:
$vitesse = 8280;
break;
case 5:
$vitesse = 1440;
break;
case 6:
$vitesse = 7380;
break;
case 7:
$vitesse = 1200;
break;
case 8:
$vitesse = 4680;
break;
case 9:
$vitesse = 16800;
break;
case 10:
$vitesse = 16800;
break;
case 11:
$vitesse = 32400;
break;
case 12:
$vitesse = 117000;
break;
case 13:
$vitesse = 117000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
return $vitesse;
}
public static function vitesseS($id)
{
switch($id)
{
case 0:
$vitesse = 1080;
break;
case 1:
$vitesse = 6300;
break;
case 2:
$vitesse = 6300;
break;
case 3:
$vitesse = 8280;
break;
case 4:
$vitesse = 8280;
break;
case 5:
$vitesse = 1440;
break;
case 6:
$vitesse = 7380;
break;
case 7:
$vitesse = 1200;
break;
case 8:
$vitesse = 4680;
break;
case 9:
$vitesse = 16800;
break;
case 10:
$vitesse = 16800;
break;
case 11:
$vitesse = 32400;
break;
case 12:
$vitesse = 117000;
break;
case 13:
$vitesse = 117000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
return $vitesse;
}
public static function vitesseG($id)
{
switch($id)
{
case 0:
$vitesse = 1080;
break;
case 1:
$vitesse = 6300;
break;
case 2:
$vitesse = 6300;
break;
case 3:
$vitesse = 8280;
break;
case 4:
$vitesse = 8280;
break;
case 5:
$vitesse = 1440;
break;
case 6:
$vitesse = 7380;
break;
case 7:
$vitesse = 1200;
break;
case 8:
$vitesse = 4680;
break;
case 9:
$vitesse = 16800;
break;
case 10:
$vitesse = 16800;
break;
case 11:
$vitesse = 32400;
break;
case 12:
$vitesse = 117000;
break;
case 13:
$vitesse = 117000;
break;
default:
trigger_error("Vaisseau ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
return $vitesse;
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,477 @@
<?php
require_once("Class/Donnees/interface.php");
class dTerrestre implements Donnees
{
public static function metal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$cristal = 300;
break;
case 1:
$cristal = 420;
break;
case 2:
$cristal = 600;
break;
case 3:
$cristal = 950;
break;
case 4:
$cristal = 240;
break;
case 5:
$cristal = 260;
break;
case 6:
$cristal = 420;
break;
case 7:
$cristal = 500;
break;
case 8:
$cristal = 230;
break;
case 9:
$cristal = 650;
break;
case 10:
$cristal = 1750;
break;
case 11:
$cristal = 3750;
break;
case 12:
$cristal = 9500;
break;
case 13:
$cristal = 9500;
break;
case 14:
$cristal = 9500;
break;
case 15:
$cristal = 9500;
break;
default:
trigger_error("Unité ".$unite." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$cristal *= 0.9;
return $cristal * $nombre;
}
public static function cristal($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$cristal = 300;
break;
case 1:
$cristal = 420;
break;
case 2:
$cristal = 600;
break;
case 3:
$cristal = 950;
break;
case 4:
$cristal = 240;
break;
case 5:
$cristal = 260;
break;
case 6:
$cristal = 420;
break;
case 7:
$cristal = 500;
break;
case 8:
$cristal = 230;
break;
case 9:
$cristal = 650;
break;
case 10:
$cristal = 1750;
break;
case 11:
$cristal = 3750;
break;
case 12:
$cristal = 9500;
break;
case 13:
$cristal = 9500;
break;
case 14:
$cristal = 9500;
break;
case 15:
$cristal = 9500;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$cristal *= 0.9;
return $cristal * $nombre;
}
public static function hydrogene($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$hydrogene = 0;
break;
case 1:
$hydrogene = 0;
break;
case 2:
$hydrogene = 0;
break;
case 3:
$hydrogene = 0;
break;
case 4:
$hydrogene = 0;
break;
case 5:
$hydrogene = 0;
break;
case 6:
$hydrogene = 0;
break;
case 7:
$hydrogene = 0;
break;
case 8:
$hydrogene = 0;
break;
case 9:
$hydrogene = 80;
break;
case 10:
$hydrogene = 100;
break;
case 11:
$hydrogene = 120;
break;
case 12:
$hydrogene = 1500;
break;
case 13:
$hydrogene = 1500;
break;
case 14:
$hydrogene = 1500;
break;
case 15:
$hydrogene = 1500;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte des bonus
if (isset($planete->politique) && $planete->politique == 1)
$hydrogene *= 0.9;
return $hydrogene * $nombre;
}
public static function credits($id, $nombre, surface $planete)
{
return 0;
}
public static function temps($id, $nombre, surface $planete)
{
switch($id)
{
case 0:
$temps = 720;
$moins = 1;
break;
case 1:
$temps = 2040;
$moins = 3;
break;
case 2:
$temps = 7200;
$moins = 4;
break;
case 3:
$temps = 3960;
$moins = 6;
break;
case 4:
$temps = 600;
$moins = 1;
break;
case 5:
$temps = 1080;
$moins = 2;
break;
case 6:
$temps = 2160;
$moins = 3;
break;
case 7:
$temps = 4680;
$moins = 5;
break;
case 8:
$temps = 1080;
$moins = 1;
break;
case 9:
$temps = 2040;
$moins = 3;
break;
case 10:
$temps = 7200;
$moins = 4;
break;
case 11:
$temps = 3960;
$moins = 7;
break;
case 12:
$temps = 3960;
$moins = 9;
break;
case 13:
$temps = 3960;
$moins = 9;
break;
case 14:
$temps = 3960;
$moins = 9;
break;
case 15:
$temps = 3960;
$moins = 9;
break;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
//On tient compte de la vitesse
$temps /= VITESSE;
//On tient compte des bonus
return ceil($temps/pow(1.25, ($planete->batiments[7] - $moins))) * $nombre;
}
public static function type($id)
{
switch($id)
{
case 0:
case 1:
case 2:
case 3:
case 4:
case 5:
case 6:
case 7:
return true;
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
return false;
default:
trigger_error("Unité ".$id." introuvable dans les données", E_USER_ERROR);
}
}
public static function image($id, surface $planete)
{
if ($planete->race == "covenant")
{
switch($id)
{
//Unités terrestres
case 0:
return "bansheeqp0.jpg";
break;
case 1:
return "spirit1.jpg";
break;
case 2:
return "phantomfu2.jpg";
break;
case 3:
return "boardingcraft.jpg";
break;
case 4:
return "ghostic1.jpg";
break;
case 5:
return "shadow.jpg";
break;
case 6:
return "spectre.jpg";
break;
case 7:
return "wraith.jpg";
break;
//Défenses
case 8:
return "shade.jpg";
break;
case 9:
return "defcovie.jpg";
break;
case 10:
return "tourellebarreau.jpg";
break;
case 11:
return "tourelle.jpg";
break;
case 12:
return "lanceur_torpilles.jpg";
break;
}
return Donnees::image_covenant_default;
}
elseif ($planete->race == "humain")
{
switch($id)
{
//Unités terrestres
case 0:
return "csnusparrowhawkkp4.jpg";
break;
case 1:
return "pelican.jpg";
break;
case 2:
return "csnushortswordad3.jpg";
break;
case 3:
return "albatross.jpg";
break;
case 4:
return "warthog-vrl.jpg";
break;
case 5:
return "M12G1_LAAV_Warthog.jpg";
break;
case 6:
return "M12A1_LAAV_Warthog.jpg";
break;
case 7:
return "scorpionN.jpg";
break;
//Défenses
case 8:
//return "";
break;
case 9:
//return "";
break;
case 10:
//return "";
break;
case 11:
//return "";
break;
}
return Donnees::image_humain_default;
}
else
trigger_error("Impossible de trouver la race pour ".$planete->race, E_USER_ERROR);
}
public static function needed($id, surface $planete, $print = false)
{
$neededTerrestre = array(
array(
array('batiments', 7, 1)
),
array(
array('batiments', 7, 3)
),
array(
array('batiments', 7, 4)
),
array(
array('batiments', 7, 6)
),
array(
array('batiments', 7, 1)
),
array(
array('batiments', 7, 2)
),
array(
array('batiments', 7, 3)
),
array(
array('batiments', 7, 5)
),
//Défenses
array(
array('batiments', 7, 1),
array('technologies', 6, 0, 1)
),
array(
array('batiments', 7, 3),
array('technologies', 6, 3, 8)
),
array(
array('batiments', 7, 4),
array('technologies', 6, 1, 2)
),
array(
array('batiments', 7, 4),
array('technologies', 6, 4, 16)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 2, 4)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 5, 32)
),
array(
array('batiments', 7, 8),
array('technologies', 6, 6, 64)
),
array(
array('batiments', 7, 10),
array('technologies', 7, 11, 2048)
)
);
if ($print)
return dDonnees::print_neededCheck($neededTerrestre[$id], $planete);
else
return dDonnees::neededCheck($neededTerrestre[$id], $planete);
}
}
?>

View file

@ -0,0 +1,257 @@
<?php
require_once("Class/File/interface.php");
class FileAlliancesBatiments extends FileCommun implements File
{
public function objectInFile($object)
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
return false;
}
public function nbObjectInFile($object, $type = null)
{
$c = 0;
if (isset($type))
{
if (!isset($type) || $type)
{
foreach($this->files as $file)
{
$c += count(array_keys($file, array($object, true)));
}
}
if (!isset($type) || !$type)
{
foreach($this->files as $file)
{
$c += count(array_keys($file, array($object, false)));
}
}
}
return $c;
}
public function addObjet($object, $nombre, surface $planete)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete))
throw new ExceptionHB(1, 1);
//Validation des conditions de construction
if (!dAlliancesBatiments::needed($object, $planete))
throw new ExceptionHB(1, 2);
//On vérifie qu'il n'y ait pas une demande de démolition du même bâtiment
if ($this->nbObjectInFile($object, true) >= 1)
throw new ExceptionHB(1, 7);
//Calcul du prochain niveau du batiment
$nextLvl = $planete->batiments[$object] + $this->nbObjectInFile($object, false) + 1;
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dAlliancesBatiments::metal($object, $nextLvl, $planete), dAlliancesBatiments::cristal($object, $nextLvl, $planete), dAlliancesBatiments::hydrogene($object, $nextLvl, $planete), dAlliancesBatiments::credits($object, $nextLvl, $planete)))
{
$this->files[$lieu][] = array($object, false);
$planete->addModif("file_bat");
return true;
}
else
throw new ExceptionHB(1, 4);
}
public function addDemolition($object, $nombre, surface $planete)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete))
throw new ExceptionHB(1, 1);
//On vérifie que le niveau actuel du batiment ne soit non nul
if ($planete->batiments[$object] <= $this->nbObjectInFile($object, false))
throw new ExceptionHB(1, 6);
//On vérifie qu'il n'y ait pas une demande de construction du même bâtiment
if ($this->nbObjectInFile($object, false) >= 1)
throw new ExceptionHB(1, 7);
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
$this->files[$lieu][] = array($object, true);
$planete->addModif("file_bat");
return true;
}
public function delObjet($id, $nombre, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(1, 5);
//On récupère le type de batiment
$object = $this->files[$lieu][$id][0];
//On gère les démolition
//@todo -cFileBatiments Est-ce vraiment utile de calculer le niveau du batiment en cas de démolition ?
if ($this->files[$lieu][$id][1])
$lvlAnnule = $planete->batiments[$object] - $this->nbObjectInFile($object, true) + 1;
else
$lvlAnnule = $planete->batiments[$object] + $this->nbObjectInFile($object, false);
//On met à jour le temps si on vient d'annuler le premier batiment en lice
if ($id == $this->findFirstKey($lieu))
$this->times[$lieu] = time();
$planete->addModif("file_bat");
if (!$this->files[$lieu][$id][1])
{
//On redonne 60% des ressources au joueur si c'est la première construction dans la file d'attente
if ($id == 0)
$planete->addRessources(dAlliancesBatiments::metal($object, $lvlAnnule, $planete)*0.6, dAlliancesBatiments::cristal($object, $lvlAnnule, $planete)*0.6, dAlliancesBatiments::hydrogene($object, $lvlAnnule, $planete)*0.6, dAlliancesBatiments::credits($object, $lvlAnnule, $planete)*0.6);
else
$planete->addRessources(dAlliancesBatiments::metal($object, $lvlAnnule, $planete), dAlliancesBatiments::cristal($object, $lvlAnnule, $planete), dAlliancesBatiments::hydrogene($object, $lvlAnnule, $planete), dAlliancesBatiments::credits($object, $lvlAnnule, $planete));
}
//Effacement de la file
unset($this->files[$lieu][$id]);
return true;
}
public function ready(SURFACE $planete)
{
//On parcourt la liste des lieux de construction
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la file
foreach ($file as $keyE => $element)
{
$tempsEcoule = time() - $this->times[$keyF];
//On gère les démolitions
if ($element[1])
{
//On récupère le niveau actuel du batiment
$lvl = $planete->batiments[$element[0]];
//On calcul le temps de démolition nécessaire (60% du niveau actuel)
$tempsNecessaire = dAlliancesBatiments::temps($element[0], $lvl, $planete, true);
if ($tempsEcoule >= $tempsNecessaire)
{
$metal = dAlliancesBatiments::metal($element[0], $lvl, $planete);
$cristal = dAlliancesBatiments::cristal($element[0], $lvl, $planete);
$hydrogene = dAlliancesBatiments::hydrogene($element[0], $lvl, $planete);
//On redonne 70% des ressources du batiment au joueur
$planete->addRessources($metal*0.7, $cristal*0.7, $hydrogene*0.7);
//On retire un niveau au batiment
$planete->batiments[$element[0]]--;
//On efface l'entrée de la file et on met à jour le temps de la file
unset($this->files[$keyF][$keyE]);
$this->times[$keyF] += $tempsNecessaire;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("batiments", $element[0]));
$planete->addModif("file_bat");
//On retire les points
$planete->addPoints($metal, $cristal, $hydrogene, 0, true);
unset($metal, $cristal, $hydrogene);
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
else //Cas de la construction
{
//Récupération du niveau du batiment
$lvl = $planete->batiments[$element[0]] + 1;
$tempsNecessaire = dAlliancesBatiments::temps($element[0], $lvl, $planete);
//Si le temps écoulé est suffisant
if ($tempsEcoule >= $tempsNecessaire)
{
//On ajoute un niveau au batiment
$planete->batiments[$element[0]]++;
//On efface l'entrée de la file et on met à jour le temps de la file
unset($this->files[$keyF][$keyE]);
$this->times[$keyF] += $tempsNecessaire;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("batiments", $element[0]));
$planete->addModif("file_bat");
//On ajoute les points
$planete->addPoints(dAlliancesBatiments::metal($element[0], $planete->batiments[$element[0]], $planete), dAlliancesBatiments::cristal($element[0], $planete->batiments[$element[0]], $planete), dAlliancesBatiments::hydrogene($element[0], $planete->batiments[$element[0]], $planete));
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
}
public function printFile(SURFACE $planete, $lieu = NULL)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
if ($element[1]) //Cas d'une démolition
{
$temps = dAlliancesBatiments::temps($element[0], $planete->batiments[$element[0]], $planete, true);
if ($prems)
$temps -= time() - $this->times[$keyF];
$out[$keyF][$keyE] = array($element[0], $element[1], ceil($temps), $prems);
}
else //Cas d'une construction
{
$temps = dAlliancesBatiments::temps($element[0], $planete->batiments[$element[0]]+1, $planete);
if ($prems)
$temps -= time() - $this->times[$keyF];
$out[$keyF][$keyE] = array($element[0], $element[1], ceil($temps), $prems);
}
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,268 @@
<?php
require_once("Class/File/interface.php");
class FileBatiments extends FileCommun implements File
{
public function objectInFile($object)
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
return false;
}
public function nbObjectInFile($object, $type = null)
{
$c = 0;
if (!isset($object))
{
foreach($this->files as $file)
{
$c += count($file);
}
}
else
{
if (!isset($type) || $type)
{
foreach($this->files as $file)
{
$c += count(array_keys($file, array($object, true)));
}
}
if (!isset($type) || !$type)
{
foreach($this->files as $file)
{
$c += count(array_keys($file, array($object, false)));
}
}
}
return $c;
}
public function addObjet($object, $nombre, surface $planete)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete))
throw new ExceptionHB(1, 1);
//Validation des conditions de construction
if (!dBatiments::needed($object, $planete))
throw new ExceptionHB(1, 2);
//On vérifie qu'il n'y ait pas une demande de démolition du même bâtiment
if ($this->nbObjectInFile($object, true) >= 1)
throw new ExceptionHB(1, 7);
//On vérifie qu'il reste suffisamment de place sur la planète
if ($planete->casesRest <= 0 || $planete->casesRest <= $this->nbObjectInFile(null))
throw new ExceptionHB(1, 0);
//Calcul du prochain niveau du batiment
$nextLvl = $planete->batiments[$object] + $this->nbObjectInFile($object, false) + 1;
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dBatiments::metal($object, $nextLvl, $planete), dBatiments::cristal($object, $nextLvl, $planete), dBatiments::hydrogene($object, $nextLvl, $planete), dBatiments::credits($object, $nextLvl, $planete)))
{
$this->files[$lieu][] = array($object, false);
$planete->addModif("file_bat");
return true;
}
else
throw new ExceptionHB(1, 4);
}
public function addDemolition($object, $nombre, surface $planete)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete))
throw new ExceptionHB(1, 1);
//On vérifie que le niveau actuel du batiment ne soit non nul
if ($planete->batiments[$object] <= $this->nbObjectInFile($object, false))
throw new ExceptionHB(1, 6);
//On vérifie qu'il n'y ait pas une demande de construction du même bâtiment
if ($this->nbObjectInFile($object, false) >= 1)
throw new ExceptionHB(1, 7);
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
$this->files[$lieu][] = array($object, true);
$planete->addModif("file_bat");
return true;
}
public function delObjet($id, $nombre, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(1, 5);
//On récupère le type de batiment
$object = $this->files[$lieu][$id][0];
//On gère les démolition
//@todo -cFileBatiments Est-ce vraiment utile de calculer le niveau du batiment en cas de démolition ?
if ($this->files[$lieu][$id][1])
$lvlAnnule = $planete->batiments[$object] - $this->nbObjectInFile($object, true) + 1;
else
$lvlAnnule = $planete->batiments[$object] + $this->nbObjectInFile($object, false);
//On met à jour le temps si on vient d'annuler le premier batiment en lice
if ($id == $this->findFirstKey($lieu))
$this->times[$lieu] = time();
$planete->addModif("file_bat");
if (!$this->files[$lieu][$id][1])
{
//On redonne 60% des ressources au joueur si c'est la première construction dans la file d'attente
if ($id == 0)
$planete->addRessources(dBatiments::metal($object, $lvlAnnule, $planete)*0.6, dBatiments::cristal($object, $lvlAnnule, $planete)*0.6, dBatiments::hydrogene($object, $lvlAnnule, $planete)*0.6, dBatiments::credits($object, $lvlAnnule, $planete)*0.6);
else
$planete->addRessources(dBatiments::metal($object, $lvlAnnule, $planete), dBatiments::cristal($object, $lvlAnnule, $planete), dBatiments::hydrogene($object, $lvlAnnule, $planete), dBatiments::credits($object, $lvlAnnule, $planete));
}
//Effacement de la file
unset($this->files[$lieu][$id]);
return true;
}
public function ready(SURFACE $planete)
{
//On parcourt la liste des lieux de construction
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la file
foreach ($file as $keyE => $element)
{
$tempsEcoule = time() - $this->times[$keyF];
//On gère les démolitions
if ($element[1])
{
//On récupère le niveau actuel du batiment
$lvl = $planete->batiments[$element[0]];
//On calcul le temps de démolition nécessaire (60% du niveau actuel)
$tempsNecessaire = dBatiments::temps($element[0], $lvl, $planete, true);
if ($tempsEcoule >= $tempsNecessaire)
{
$metal = dBatiments::metal($element[0], $lvl, $planete);
$cristal = dBatiments::cristal($element[0], $lvl, $planete);
$hydrogene = dBatiments::hydrogene($element[0], $lvl, $planete);
//On redonne 70% des ressources du batiment au joueur
$planete->addRessources($metal*0.7, $cristal*0.7, $hydrogene*0.7);
//On retire un niveau au batiment
$planete->batiments[$element[0]]--;
//On efface l'entrée de la file et on met à jour le temps de la file
unset($this->files[$keyF][$keyE]);
$this->times[$keyF] += $tempsNecessaire;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("batiments", $element[0]));
$planete->addModif("file_bat");
//On retire les points
$planete->addPoints($metal, $cristal, $hydrogene, 0, true);
unset($metal, $cristal, $hydrogene);
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
else //Cas de la construction
{
//Récupération du niveau du batiment
$lvl = $planete->batiments[$element[0]] + 1;
$tempsNecessaire = dBatiments::temps($element[0], $lvl, $planete);
//Si le temps écoulé est suffisant
if ($tempsEcoule >= $tempsNecessaire)
{
//On ajoute un niveau au batiment
$planete->batiments[$element[0]]++;
//On efface l'entrée de la file et on met à jour le temps de la file
unset($this->files[$keyF][$keyE]);
$this->times[$keyF] += $tempsNecessaire;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("batiments", $element[0]));
$planete->addModif("file_bat");
//On ajoute les points
$planete->addPoints(dBatiments::metal($element[0], $planete->batiments[$element[0]], $planete), dBatiments::cristal($element[0], $planete->batiments[$element[0]], $planete), dBatiments::hydrogene($element[0], $planete->batiments[$element[0]], $planete));
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
}
public function printFile(SURFACE $planete, $lieu = null)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
if ($element[1]) //Cas d'une démolition
{
$temps = dBatiments::temps($element[0], $planete->batiments[$element[0]], $planete, true);
if ($prems)
$temps -= time() - $this->times[$keyF];
$out[$keyF][$keyE] = array($element[0], $element[1], ceil($temps), $prems);
}
else //Cas d'une construction
{
$temps = dBatiments::temps($element[0], $planete->batiments[$element[0]]+1, $planete);
if ($prems)
$temps -= time() - $this->times[$keyF];
$out[$keyF][$keyE] = array($element[0], $element[1], ceil($temps), $prems);
}
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,309 @@
<?php
require_once("Class/File/interface.php");
class FileCaserne extends FileCommun implements File
{
public function objectInFile($object, $lieu = null)
{
if (isset($lieu))
{
if (!empty($this->files[$lieu]))
{
foreach($this->files[$lieu] as $keyE => $element)
{
if ($element[0] == $object)
return array($lieu, $keyE);
}
}
}
else
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
}
return false;
}
public function nbObjectInFile($object)
{
$c = 0;
foreach($this->files as $key => $file)
{
foreach($file as $element)
{
if ($element[0] == $object)
$c += $element[1];
}
}
return $c;
}
public function addObjet($object, $nombre, surface $planete, $lieu = null)
{
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//Validation des conditions de construction
if (!dCaserne::needed($object, $planete))
throw new ExceptionHB(3, 2);
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!($sauvLastKey = $this->objectInFile($object, $lieu)) && !$this->checkMaxSize($planete, $lieu))
throw new ExceptionHB(3, 1);
//On tronque au maximum d'unités constructible sur la planète
if (($metal = dCaserne::metal($object, 1, $planete)) > 0)
$metal = $planete->metal/$metal;
else
$metal = $nombre;
if (($cristal = dCaserne::cristal($object, 1, $planete)) > 0)
$cristal = $planete->cristal/$cristal;
else
$cristal = $nombre;
if (($hydrogene = dCaserne::hydrogene($object, 1, $planete)) > 0)
$hydrogene = $planete->hydrogene/$hydrogene;
else
$hydrogene = $nombre;
$nombre = floor(min($nombre, $metal, $cristal, $hydrogene));
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dCaserne::metal($object, $nombre, $planete), dCaserne::cristal($object, $nombre, $planete), dCaserne::hydrogene($object, $nombre, $planete), dCaserne::credits($object, $nombre, $planete)))
{
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey) && isset($this->files[$sauvLastKey[0]][$sauvLastKey[1]]))
{
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($sauvLastKey[0]);
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
}
else
{
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
$this->files[$lieu][] = array($object, $nombre, false);
}
$planete->addModif("file_cas");
return true;
}
else
throw new ExceptionHB(3, 4);
}
public function addDemolition($object, $nombre, surface $planete, $lieu = null)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete, $lieu) && !($sauvLastKey = $this->objectInFile($object, $lieu)))
throw new ExceptionHB(3, 1);
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//On vérifie que le nombre d'unité actuel soit non nul
if ($planete->casernes[$object] < $nombre)
throw new ExceptionHB(3, 6);
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey))
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
else
$this->files[$lieu][] = array($object, $nombre, false);
$planete->addModif("file_cas");
return true;
}
public function delObjet($id, $nombre, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(1, 5);
//Si $nombre est supérieur au nombre présent dans la file, on le réduit
if ($this->files[$lieu][$id][1] < $nombre)
$nombre = $this->files[$lieu][$id][1];
//On récupère les informations disponibles
$objet = $this->files[$lieu][$id][0];
$nombreMax = $this->files[$lieu][$id][1];
//On met à jour le temps si on vient d'annuler le premier groupe d'unités en lice
if ($id == $this->findFirstKey($lieu) && $nombreMax == $nombre)
$this->times[$lieu] = time();
$planete->addModif("file_cas");
if (!$this->files[$lieu][$id][2])
$planete->addRessources(dCaserne::metal($objet, $nombre, $planete), dCaserne::cristal($objet, $nombre, $planete), dCaserne::hydrogene($objet, $nombre, $planete), dCaserne::credits($objet, $nombre, $planete));
//Effacement de la file
if ($nombre >= $nombreMax)
unset($this->files[$lieu][$id]);
else
$this->files[$lieu][$id][1] -= $nombre;
$planete->addModif("file_cas");
return true;
}
public function ready(SURFACE $planete)
{
//On parcourt la liste des lieux de construction
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la liste à la recherche des unités terminées dans l'ordre
foreach($file as $keyE => $element)
{
//Calcul du temps écoulé depuis le dernier entraînement
$tempsEcoule = time() - $this->times[$keyF];
//On gére les licenciments !
if ($element[2])
{
//On vérifie qu'il reste des unités du type sur la planète
if ($planete->casernes[$element[0]] <= 0)
{
unset($this->files[$keyF][$keyE]);
$planete->addModif("file_cas");
}
else
{
//Récupération de 60% du temps nécessaire
$tempsNecessaire = dCaserne::temps($element[0], 1, $planete) * 0.6;
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1], $planete->casernes[$element[0]]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On redonne 70% des ressources de l'unité au joueur
$planete->addRessources(dCaserne::metal($element[0], $nbUnitee, $planete)*0.7, dCaserne::cristal($element[0], $nbUnitee, $planete)*0.7, dCaserne::hydrogene($element[0], $nbUnitee, $planete)*0.7, dCaserne::credits($element[0], $nbUnitee, $planete)*0.7);
//On retire les unités
$planete->casernes[$element[0]] -= $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->filefiles[$keyF][$keyE]);
else
$this->file[$key][1] -= $nbUnitee;
$this->timefiles[$keyF] += $tempsNecessaire*$nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("casernes", $element[0]));
$planete->addModif("file_cas");
if ($nbUnitee < $element[1])
return false;
}
//Si le temps écoulé n'est pas suffisant pour cette unité, on annule toutes les suivantes
else
break;
}
}
else //Cas de la construction
{
//Récupération du temps nécessaire
$tempsNecessaire = dCaserne::temps($element[0], 1, $planete);
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On ajoute le nombre d'unités
$planete->casernes[$element[0]] += $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->files[$keyF][$keyE]);
else
$this->files[$keyF][$keyE][1] -= $nbUnitee;
$this->times[$keyF] += $tempsNecessaire * $nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("casernes", $element[0]));
$planete->addModif("file_cas");
if ($nbUnitee < $element[1])
break;
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
}
function printFile(SURFACE $planete, $lieu = NULL)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
if ($element[2])
{
$temps = dCaserne::temps($element[0], 1, $planete) * 0.6;
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems);
}
else
{
$temps = dCaserne::temps($element[0], 1, $planete);
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems);
}
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,113 @@
<?php
if(!defined('ONYX')) exit;
interface File
{
public function objectInFile($object);
public function nbObjectInFile($object);
public function addObjet($object, $nombre, surface $planete);
public function addDemolition($object, $nombre, surface $planete);
public function delObjet($id, $nombre, $lieu, surface $planete);
public function ready(surface $planete);
public function printFile(surface $planete, $lieu = NULL);
}
class FileCommun
{
protected $files = array();
protected $times = array();
protected $simultane;
function __construct()
{
$this->times[] = time();
$this->simultane = 1;
}
function refreshTime($lieu)
{
if (empty($this->files[$lieu]) || count($this->files[$lieu]) < 1)
$this->times[$lieu] = time();
}
function reajusteVacances($timelost)
{
foreach($this->times as $key => $time)
$this->times[$key] += $timelost;
return serialize($this);
}
function hasObject()
{
foreach($this->files as $file)
{
if (count($file) > 0)
return true;
}
return false;
}
function checkMaxSize(surface $planete, $lieu = null)
{
$nombre = 0;
if (isset($lieu))
{
if (!empty($this->files[$lieu]))
$nombre = count($this->files[$lieu]);
}
else
{
foreach($this->files as $file)
{
$nombre += count($file);
}
}
return ($nombre < dDonnees::tailleFile($planete));
}
function findShorter()
{
$short = 0;
$value = 99;
foreach($this->files as $key => $file)
{
if ($key >= $this->simultane)
break;
$count = count($file);
if ($value > $count)
{
$value = $count;
$short = $key;
}
}
return $short;
}
function findFirstKey($lieu)
{
foreach($this->files[$lieu] as $key => $file)
return $key;
}
function DEBUG__print()
{
var_dump($this);
var_dump($this->files);
}
function DEBUG__setTime($lieu, $moins)
{
$this->times[$lieu] -= $moins;
return $this->times[$lieu];
}
}
?>

View file

@ -0,0 +1,309 @@
<?php
require_once("Class/File/interface.php");
class FileSpatial extends FileCommun implements File
{
public function objectInFile($object, $lieu = null)
{
if (isset($lieu))
{
if (!empty($this->files[$lieu]))
{
foreach($this->files[$lieu] as $keyE => $element)
{
if ($element[0] == $object)
return array($lieu, $keyE);
}
}
}
else
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
}
return false;
}
public function nbObjectInFile($object)
{
$c = 0;
foreach($this->files as $key => $file)
{
foreach($file as $element)
{
if ($element[0] == $object)
$c += $element[1];
}
}
return $c;
}
public function addObjet($object, $nombre, surface $planete, $lieu = null)
{
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//Validation des conditions de construction
if (!dSpatial::needed($object, $planete))
throw new ExceptionHB(3, 2);
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!($sauvLastKey = $this->objectInFile($object, $lieu)) && !$this->checkMaxSize($planete, $lieu))
throw new ExceptionHB(3, 1);
//On tronque au maximum d'unités constructible sur la planète
if (($metal = dSpatial::metal($object, 1, $planete)) > 0)
$metal = $planete->metal/$metal;
else
$metal = $nombre;
if (($cristal = dSpatial::cristal($object, 1, $planete)) > 0)
$cristal = $planete->cristal/$cristal;
else
$cristal = $nombre;
if (($hydrogene = dSpatial::hydrogene($object, 1, $planete)) > 0)
$hydrogene = $planete->hydrogene/$hydrogene;
else
$hydrogene = $nombre;
$nombre = floor(min($nombre, $metal, $cristal, $hydrogene));
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dSpatial::metal($object, $nombre, $planete), dSpatial::cristal($object, $nombre, $planete), dSpatial::hydrogene($object, $nombre, $planete), dSpatial::credits($object, $nombre, $planete)))
{
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey) && isset($this->files[$sauvLastKey[0]][$sauvLastKey[1]]))
{
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($sauvLastKey[0]);
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
}
else
{
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
$this->files[$lieu][] = array($object, $nombre, false);
}
$planete->addModif("file_vais");
return true;
}
else
throw new ExceptionHB(3, 4);
}
public function addDemolition($object, $nombre, surface $planete, $lieu = null)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete, $lieu) && !($sauvLastKey = $this->objectInFile($object, $lieu)))
throw new ExceptionHB(3, 1);
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//On vérifie que le nombre d'unité actuel soit non nul
if ($planete->vaisseaux[$object] < $nombre)
throw new ExceptionHB(3, 6);
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey))
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
else
$this->files[$lieu][] = array($object, $nombre, false);
$planete->addModif("file_vais");
return true;
}
public function delObjet($id, $nombre, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(1, 5);
//Si $nombre est supérieur au nombre présent dans la file, on le réduit
if ($this->files[$lieu][$id][1] < $nombre)
$nombre = $this->files[$lieu][$id][1];
//On récupère les informations disponibles
$objet = $this->files[$lieu][$id][0];
$nombreMax = $this->files[$lieu][$id][1];
//On met à jour le temps si on vient d'annuler le premier groupe d'unités en lice
if ($id == $this->findFirstKey($lieu) && $nombreMax == $nombre)
$this->times[$lieu] = time();
$planete->addModif("file_vais");
if (!$this->files[$lieu][$id][2])
$planete->addRessources(dSpatial::metal($objet, $nombre, $planete), dSpatial::cristal($objet, $nombre, $planete), dSpatial::hydrogene($objet, $nombre, $planete), dSpatial::credits($objet, $nombre, $planete));
//Effacement de la file
if ($nombre >= $nombreMax)
unset($this->files[$lieu][$id]);
else
$this->files[$lieu][$id][1] -= $nombre;
$planete->addModif("file_vais");
return true;
}
public function ready(SURFACE $planete)
{
//On parcourt la liste des lieux de construction
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la liste à la recherche des unités terminées dans l'ordre
foreach($file as $keyE => $element)
{
//Calcul du temps écoulé depuis le dernier entraînement
$tempsEcoule = time() - $this->times[$keyF];
//On gére les licenciments !
if ($element[2])
{
//On vérifie qu'il reste des unités du type sur la planète
if ($planete->vaisseaux[$element[0]] <= 0)
{
unset($this->files[$keyF][$keyE]);
$planete->addModif("file_vais");
}
else
{
//Récupération de 60% du temps nécessaire
$tempsNecessaire = dSpatial::temps($element[0], 1, $planete) * 0.6;
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1], $planete->vaisseaux[$element[0]]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On redonne 70% des ressources de l'unité au joueur
$planete->addRessources(dSpatial::metal($element[0], $nbUnitee, $planete)*0.7, dSpatial::cristal($element[0], $nbUnitee, $planete)*0.7, dSpatial::hydrogene($element[0], $nbUnitee, $planete)*0.7, dSpatial::credits($element[0], $nbUnitee, $planete)*0.7);
//On retire les unités
$planete->vaisseaux[$element[0]] -= $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->filefiles[$keyF][$keyE]);
else
$this->file[$key][1] -= $nbUnitee;
$this->timefiles[$keyF] += $tempsNecessaire*$nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("vaisseaux", $element[0]));
$planete->addModif("file_vais");
if ($nbUnitee < $element[1])
return false;
}
//Si le temps écoulé n'est pas suffisant pour cette unité, on annule toutes les suivantes
else
break;
}
}
else //Cas de la construction
{
//Récupération du temps nécessaire
$tempsNecessaire = dSpatial::temps($element[0], 1, $planete);
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On ajoute le nombre d'unités
$planete->vaisseaux[$element[0]] += $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->files[$keyF][$keyE]);
else
$this->files[$keyF][$keyE][1] -= $nbUnitee;
$this->times[$keyF] += $tempsNecessaire * $nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("vaisseaux", $element[0]));
$planete->addModif("file_vais");
if ($nbUnitee < $element[1])
break;
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
}
function printFile(SURFACE $planete, $lieu = NULL)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
if ($element[2])
{
$temps = dSpatial::temps($element[0], 1, $planete) * 0.6;
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems);
}
else
{
$temps = dSpatial::temps($element[0], 1, $planete);
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems);
}
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,163 @@
<?php
require_once("Class/File/interface.php");
//Un object au sens technologie est définit par un tableau : array($branche, $tech);
class FileTechnologies extends FileCommun implements File
{
public function objectInFile($object)
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
return false;
}
public function nbObjectInFile($branche, $tech = null)
{
$c = 0;
foreach($this->files as $file)
{
$c += count(array_keys($file, array($branche, $tech)));
}
return $c;
}
public function addObjet($branche, $tech, surface $planete)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete))
throw new ExceptionHB(4, 1);
//On vérifie qu'il n'y ait pas une recherche de la même technologie
if ($this->nbObjectInFile($branche, $tech) >= 1)
throw new ExceptionHB(4, 7);
//On vérifie que la technologie ne soit pas déjà développée
if (dTechnologies::idToBit($tech) & $planete->technologies[$branche])
throw new ExceptionHB(4, 7);
//Validation des conditions de construction
if (!dTechnologies::needed(array($branche, $tech), $planete))
throw new ExceptionHB(4, 2);
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dTechnologies::metal($branche, $tech, $planete), dTechnologies::cristal($branche, $tech, $planete), dTechnologies::hydrogene($branche, $tech, $planete), dTechnologies::credits($branche, $tech, $planete)))
{
$this->files[$lieu][] = array($branche, $tech);
$planete->addModif("file_tech");
return true;
}
else
throw new ExceptionHB(4, 4);
}
public function addDemolition($object, $nombre = 1, surface $planete)
{
trigger_error("Pas de démolition possible pour les technologies");
}
public function delObjet($id, $nombre = 1, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(4, 5);
//On récupère la branche et l'id de la technologie
$branche = $this->files[$lieu][$id][0];
$tech = $this->files[$lieu][$id][1];
//On met à jour le temps si on vient d'annuler la première recherche en lice
if ($tech == $this->findFirstKey($lieu))
$this->times[$lieu] = time();
$planete->addModif("file_tech");
//On redonne 70% des ressources au joueur si c'est la première construction dans la file d'attente
if ($id == 0)
$planete->addRessources(dTechnologies::metal($branche, $tech, $planete)*0.7, dTechnologies::cristal($branche, $tech, $planete)*0.7, dTechnologies::hydrogene($branche, $tech, $planete)*0.7, dTechnologies::credits($branche, $tech, $planete)*0.7);
else
$planete->addRessources(dTechnologies::metal($branche, $tech, $planete), dTechnologies::cristal($branche, $tech, $planete), dTechnologies::hydrogene($branche, $tech, $planete), dTechnologies::credits($branche, $tech, $planete));
//Effacement de la file
unset($this->files[$lieu][$id]);
return true;
}
public function ready(surface $planete)
{
//On parcourt la liste des lieux de recherche
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la file
foreach ($file as $keyE => $element)
{
$tempsEcoule = time() - $this->times[$keyF];
$tempsNecessaire = dTechnologies::temps($element[0], $element[1], $planete);
//Si le temps écoulé est suffisant
if ($tempsEcoule >= $tempsNecessaire)
{
//On ajoute un niveau au batiment
$planete->technologies[$element[0]] = $planete->technologies[$element[0]] | dTechnologies::idToBit($element[1]);
//On efface l'entrée de la file et on met à jour le temps de la file
unset($this->files[$keyF][$keyE]);
$this->times[$keyF] += $tempsNecessaire;
//On demande la mise à jour des champs modifiés
$planete->addModifUser(array("technologies", $element[0]));
$planete->addModif("file_tech");
//On ajoute les points
$planete->addPoints(dTechnologies::metal($element[0], $element[0], $planete), dTechnologies::cristal($element[0], $element[1], $planete), dTechnologies::hydrogene($element[0], $element[1], $planete), dTechnologies::credits($element[0], $element[1], $planete));
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
public function printFile(surface $planete, $lieu = null)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
$temps = dTechnologies::temps($element[0], $element[1], $planete);
if ($prems)
$temps -= time() - $this->times[$keyF];
$out[$keyF][$keyE] = array($element[0], $element[1], ceil($temps), $prems);
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,309 @@
<?php
require_once("Class/File/interface.php");
class FileTerrestre extends FileCommun implements File
{
public function objectInFile($object, $lieu = null)
{
if (isset($lieu))
{
if (!empty($this->files[$lieu]))
{
foreach($this->files[$lieu] as $keyE => $element)
{
if ($element[0] == $object)
return array($lieu, $keyE);
}
}
}
else
{
foreach($this->files as $keyF => $file)
{
foreach($file as $keyE => $element)
{
if ($element[0] == $object)
return array($keyF, $keyE);
}
}
}
return false;
}
public function nbObjectInFile($object)
{
$c = 0;
foreach($this->files as $key => $file)
{
foreach($file as $element)
{
if ($element[0] == $object)
$c += $element[1];
}
}
return $c;
}
public function addObjet($object, $nombre, surface $planete, $lieu = null)
{
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//Validation des conditions de construction
if (!dTerrestre::needed($object, $planete))
throw new ExceptionHB(3, 2);
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!($sauvLastKey = $this->objectInFile($object, $lieu)) && !$this->checkMaxSize($planete, $lieu))
throw new ExceptionHB(3, 1);
//On tronque au maximum d'unités constructible sur la planète
if (($metal = dTerrestre::metal($object, 1, $planete)) > 0)
$metal = $planete->metal/$metal;
else
$metal = $nombre;
if (($cristal = dTerrestre::cristal($object, 1, $planete)) > 0)
$cristal = $planete->cristal/$cristal;
else
$cristal = $nombre;
if (($hydrogene = dTerrestre::hydrogene($object, 1, $planete)) > 0)
$hydrogene = $planete->hydrogene/$hydrogene;
else
$hydrogene = $nombre;
$nombre = floor(min($nombre, $metal, $cristal, $hydrogene));
//On vérifie qu'il y ait assez de ressources sur la planète
if ($planete->checkAndRetireRessources(dTerrestre::metal($object, $nombre, $planete), dTerrestre::cristal($object, $nombre, $planete), dTerrestre::hydrogene($object, $nombre, $planete), dTerrestre::credits($object, $nombre, $planete)))
{
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey) && isset($this->files[$sauvLastKey[0]][$sauvLastKey[1]]))
{
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($sauvLastKey[0]);
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
}
else
{
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
$this->files[$lieu][] = array($object, $nombre, false);
}
$planete->addModif("file_ter");
return true;
}
else
throw new ExceptionHB(3, 4);
}
public function addDemolition($object, $nombre, surface $planete, $lieu = null)
{
//On vérifie que l'on ne dépasse pas la taille maximale de la file
if (!$this->checkMaxSize($planete, $lieu) && !($sauvLastKey = $this->objectInFile($object, $lieu)))
throw new ExceptionHB(3, 1);
//Vérification du nombre passé en entrée
if (!is_numeric($nombre) || $nombre < 0 || $nombre > 99999)
throw new ExceptionHB(3, 8);
//On vérifie que le nombre d'unité actuel soit non nul
if ($planete->terrestres[$object] < $nombre)
throw new ExceptionHB(3, 6);
if (!isset($lieu))
{
//On recherche le lieu ayant le moins de construction en cours
$lieu = $this->findShorter();
}
//On rafraîchit le temps de la file si aucun objet n'est en file d'attente
$this->refreshTime($lieu);
//Si il existe déjà l'objet en file d'attente, on l'ajoute
if(isset($sauvLastKey))
$this->files[$sauvLastKey[0]][$sauvLastKey[1]][1] += $nombre;
else
$this->files[$lieu][] = array($object, $nombre, false);
$planete->addModif("file_ter");
return true;
}
public function delObjet($id, $nombre, $lieu, surface $planete)
{
//Vérification de l'existance de l'objet en file d'attente
if (empty($this->files[$lieu][$id]))
throw new ExceptionHB(1, 5);
//Si $nombre est supérieur au nombre présent dans la file, on le réduit
if ($this->files[$lieu][$id][1] < $nombre)
$nombre = $this->files[$lieu][$id][1];
//On récupère les informations disponibles
$objet = $this->files[$lieu][$id][0];
$nombreMax = $this->files[$lieu][$id][1];
//On met à jour le temps si on vient d'annuler le premier groupe d'unités en lice
if ($id == $this->findFirstKey($lieu) && $nombreMax == $nombre)
$this->times[$lieu] = time();
$planete->addModif("file_ter");
if (!$this->files[$lieu][$id][2])
$planete->addRessources(dTerrestre::metal($objet, $nombre, $planete), dTerrestre::cristal($objet, $nombre, $planete), dTerrestre::hydrogene($objet, $nombre, $planete), dTerrestre::credits($objet, $nombre, $planete));
//Effacement de la file
if ($nombre >= $nombreMax)
unset($this->files[$lieu][$id]);
else
$this->files[$lieu][$id][1] -= $nombre;
$planete->addModif("file_ter");
return true;
}
public function ready(SURFACE $planete)
{
//On parcourt la liste des lieux de construction
foreach($this->files as $keyF => $file)
{
//On vérifie qu'il y a bien des éléments dans cette file d'attente
if (count($file) == 0)
continue;
//On parcourt la liste à la recherche des unités terminées dans l'ordre
foreach($file as $keyE => $element)
{
//Calcul du temps écoulé depuis le dernier entraînement
$tempsEcoule = time() - $this->times[$keyF];
//On gére les licenciments !
if ($element[2])
{
//On vérifie qu'il reste des unités du type sur la planète
if ($planete->terrestres[$element[0]] <= 0)
{
unset($this->files[$keyF][$keyE]);
$planete->addModif("file_ter");
}
else
{
//Récupération de 60% du temps nécessaire
$tempsNecessaire = dTerrestre::temps($element[0], 1, $planete) * 0.6;
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1], $planete->terrestres[$element[0]]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On redonne 70% des ressources de l'unité au joueur
$planete->addRessources(dTerrestre::metal($element[0], $nbUnitee, $planete)*0.7, dTerrestre::cristal($element[0], $nbUnitee, $planete)*0.7, dTerrestre::hydrogene($element[0], $nbUnitee, $planete)*0.7, dTerrestre::credits($element[0], $nbUnitee, $planete)*0.7);
//On retire les unités
$planete->terrestres[$element[0]] -= $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->filefiles[$keyF][$keyE]);
else
$this->file[$key][1] -= $nbUnitee;
$this->timefiles[$keyF] += $tempsNecessaire*$nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("terrestres", $element[0]));
$planete->addModif("file_ter");
if ($nbUnitee < $element[1])
return false;
}
//Si le temps écoulé n'est pas suffisant pour cette unité, on annule toutes les suivantes
else
break;
}
}
else //Cas de la construction
{
//Récupération du temps nécessaire
$tempsNecessaire = dTerrestre::temps($element[0], 1, $planete);
//Calcul du nombre d'unités maximum
$nbUnitee = min(floor($tempsEcoule/$tempsNecessaire), $element[1]);
//Si le temps écoulé est suffisant
if ($nbUnitee > 0)
{
//On ajoute le nombre d'unités
$planete->terrestres[$element[0]] += $nbUnitee;
//On efface l'entrée de la file et on met à jour le temps de la file
if ($nbUnitee >= $element[1])
unset($this->files[$keyF][$keyE]);
else
$this->files[$keyF][$keyE][1] -= $nbUnitee;
$this->times[$keyF] += $tempsNecessaire * $nbUnitee;
//On demande la mise à jour des champs modifiés
$planete->addModif(array("terrestres", $element[0]));
$planete->addModif("file_ter");
if ($nbUnitee < $element[1])
break;
}
//Si le temps écoulé n'est pas suffisant pour ce batiment, on annule tous les suivants
else
break;
}
}
}
}
function printFile(SURFACE $planete, $lieux = NULL)
{
$out = array();
foreach ($this->files as $keyF => $file)
{
if (isset($lieu) && $lieu != $keyF)
continue;
$prems = true;
foreach ($file as $keyE => $element)
{
if ($element[2])
{
$temps = dTerrestre::temps($element[0], 1, $planete) * 0.6;
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems, dTerrestre::type($element[0]));
}
else
{
$temps = dTerrestre::temps($element[0], 1, $planete);
if ($prems)
$temps_moins = time() - $this->times[$keyF];
else
$temps_moins = 0;
$out[$keyF][$keyE] = array($element[0], $element[1], $element[2], ceil($temps * $element[1] - $temps_moins), ceil($temps - $temps_moins), $prems, dTerrestre::type($element[0]));
}
$prems = false;
}
}
return $out;
}
}
?>

View file

@ -0,0 +1,806 @@
<?php
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
/**
* Converts to and from JSON format.
*
* JSON (JavaScript Object Notation) is a lightweight data-interchange
* format. It is easy for humans to read and write. It is easy for machines
* to parse and generate. It is based on a subset of the JavaScript
* Programming Language, Standard ECMA-262 3rd Edition - December 1999.
* This feature can also be found in Python. JSON is a text format that is
* completely language independent but uses conventions that are familiar
* to programmers of the C-family of languages, including C, C++, C#, Java,
* JavaScript, Perl, TCL, and many others. These properties make JSON an
* ideal data-interchange language.
*
* This package provides a simple encoder and decoder for JSON notation. It
* is intended for use with client-side Javascript applications that make
* use of HTTPRequest to perform server communication functions - data can
* be encoded into JSON notation for use in a client-side javascript, or
* decoded from incoming Javascript requests. JSON format is native to
* Javascript, and can be directly eval()'ed with no further parsing
* overhead
*
* All strings should be in ASCII or UTF-8 format!
*
* LICENSE: Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met: Redistributions of source code must retain the
* above copyright notice, this list of conditions and the following
* disclaimer. Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN
* NO EVENT SHALL CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
* TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE
* USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*
* @category
* @package Services_JSON
* @author Michal Migurski <mike-json@teczno.com>
* @author Matt Knapp <mdknapp[at]gmail[dot]com>
* @author Brett Stimmerman <brettstimmerman[at]gmail[dot]com>
* @copyright 2005 Michal Migurski
* @version CVS: $Id: JSON.php,v 1.31 2006/06/28 05:54:17 migurski Exp $
* @license http://www.opensource.org/licenses/bsd-license.php
* @link http://pear.php.net/pepr/pepr-proposal-show.php?id=198
*/
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_SLICE', 1);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_STR', 2);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_ARR', 3);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_OBJ', 4);
/**
* Marker constant for Services_JSON::decode(), used to flag stack state
*/
define('SERVICES_JSON_IN_CMT', 5);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_LOOSE_TYPE', 16);
/**
* Behavior switch for Services_JSON::decode()
*/
define('SERVICES_JSON_SUPPRESS_ERRORS', 32);
/**
* Converts to and from JSON format.
*
* Brief example of use:
*
* <code>
* // create a new instance of Services_JSON
* $json = new Services_JSON();
*
* // convert a complexe value to JSON notation, and send it to the browser
* $value = array('foo', 'bar', array(1, 2, 'baz'), array(3, array(4)));
* $output = $json->encode($value);
*
* print($output);
* // prints: ["foo","bar",[1,2,"baz"],[3,[4]]]
*
* // accept incoming POST data, assumed to be in JSON notation
* $input = file_get_contents('php://input', 1000000);
* $value = $json->decode($input);
* </code>
*/
class Services_JSON
{
/**
* constructs a new JSON instance
*
* @param int $use object behavior flags; combine with boolean-OR
*
* possible values:
* - SERVICES_JSON_LOOSE_TYPE: loose typing.
* "{...}" syntax creates associative arrays
* instead of objects in decode().
* - SERVICES_JSON_SUPPRESS_ERRORS: error suppression.
* Values which can't be encoded (e.g. resources)
* appear as NULL instead of throwing errors.
* By default, a deeply-nested resource will
* bubble up with an error, so all return values
* from encode() should be checked with isError()
*/
function Services_JSON($use = 0)
{
$this->use = $use;
}
/**
* convert a string from one UTF-16 char to one UTF-8 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf16 UTF-16 character
* @return string UTF-8 character
* @access private
*/
function utf162utf8($utf16)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf16, 'UTF-8', 'UTF-16');
}
$bytes = (ord($utf16{0}) << 8) | ord($utf16{1});
switch(true) {
case ((0x7F & $bytes) == $bytes):
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x7F & $bytes);
case (0x07FF & $bytes) == $bytes:
// return a 2-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xC0 | (($bytes >> 6) & 0x1F))
. chr(0x80 | ($bytes & 0x3F));
case (0xFFFF & $bytes) == $bytes:
// return a 3-byte UTF-8 character
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0xE0 | (($bytes >> 12) & 0x0F))
. chr(0x80 | (($bytes >> 6) & 0x3F))
. chr(0x80 | ($bytes & 0x3F));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* convert a string from one UTF-8 char to one UTF-16 char
*
* Normally should be handled by mb_convert_encoding, but
* provides a slower PHP-only method for installations
* that lack the multibye string extension.
*
* @param string $utf8 UTF-8 character
* @return string UTF-16 character
* @access private
*/
function utf82utf16($utf8)
{
// oh please oh please oh please oh please oh please
if(function_exists('mb_convert_encoding')) {
return mb_convert_encoding($utf8, 'UTF-16', 'UTF-8');
}
switch(strlen($utf8)) {
case 1:
// this case should never be reached, because we are in ASCII range
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return $utf8;
case 2:
// return a UTF-16 character from a 2-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr(0x07 & (ord($utf8{0}) >> 2))
. chr((0xC0 & (ord($utf8{0}) << 6))
| (0x3F & ord($utf8{1})));
case 3:
// return a UTF-16 character from a 3-byte UTF-8 char
// see: http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
return chr((0xF0 & (ord($utf8{0}) << 4))
| (0x0F & (ord($utf8{1}) >> 2)))
. chr((0xC0 & (ord($utf8{1}) << 6))
| (0x7F & ord($utf8{2})));
}
// ignoring UTF-32 for now, sorry
return '';
}
/**
* encodes an arbitrary variable into JSON format
*
* @param mixed $var any number, boolean, string, array, or object to be encoded.
* see argument 1 to Services_JSON() above for array-parsing behavior.
* if var is a strng, note that encode() always expects it
* to be in ASCII or UTF-8 format!
*
* @return mixed JSON string representation of input var or an error if a problem occurs
* @access public
*/
function encode($var)
{
switch (gettype($var)) {
case 'boolean':
return $var ? 'true' : 'false';
case 'NULL':
return 'null';
case 'integer':
return (int) $var;
case 'double':
case 'float':
return (float) $var;
case 'string':
// STRINGS ARE EXPECTED TO BE IN ASCII OR UTF-8 FORMAT
$ascii = '';
$strlen_var = strlen($var);
/*
* Iterate over every character in the string,
* escaping with a slash or encoding to UTF-8 where necessary
*/
for ($c = 0; $c < $strlen_var; ++$c) {
$ord_var_c = ord($var{$c});
switch (true) {
case $ord_var_c == 0x08:
$ascii .= '\b';
break;
case $ord_var_c == 0x09:
$ascii .= '\t';
break;
case $ord_var_c == 0x0A:
$ascii .= '\n';
break;
case $ord_var_c == 0x0C:
$ascii .= '\f';
break;
case $ord_var_c == 0x0D:
$ascii .= '\r';
break;
case $ord_var_c == 0x22:
case $ord_var_c == 0x2F:
case $ord_var_c == 0x5C:
// double quote, slash, slosh
$ascii .= '\\'.$var{$c};
break;
case (($ord_var_c >= 0x20) && ($ord_var_c <= 0x7F)):
// characters U-00000000 - U-0000007F (same as ASCII)
$ascii .= $var{$c};
break;
case (($ord_var_c & 0xE0) == 0xC0):
// characters U-00000080 - U-000007FF, mask 110XXXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c, ord($var{$c + 1}));
$c += 1;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF0) == 0xE0):
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}));
$c += 2;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xF8) == 0xF0):
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}));
$c += 3;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFC) == 0xF8):
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}));
$c += 4;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
case (($ord_var_c & 0xFE) == 0xFC):
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$char = pack('C*', $ord_var_c,
ord($var{$c + 1}),
ord($var{$c + 2}),
ord($var{$c + 3}),
ord($var{$c + 4}),
ord($var{$c + 5}));
$c += 5;
$utf16 = $this->utf82utf16($char);
$ascii .= sprintf('\u%04s', bin2hex($utf16));
break;
}
}
return '"'.$ascii.'"';
case 'array':
/*
* As per JSON spec if any array key is not an integer
* we must treat the the whole array as an object. We
* also try to catch a sparsely populated associative
* array with numeric keys here because some JS engines
* will create an array with empty indexes up to
* max_index which can cause memory issues and because
* the keys, which may be relevant, will be remapped
* otherwise.
*
* As per the ECMA and JSON specification an object may
* have any string as a property. Unfortunately due to
* a hole in the ECMA specification if the key is a
* ECMA reserved word or starts with a digit the
* parameter is only accessible using ECMAScript's
* bracket notation.
*/
// treat as a JSON object
if (is_array($var) && count($var) && (array_keys($var) !== range(0, sizeof($var) - 1))) {
$properties = array_map(array($this, 'name_value'),
array_keys($var),
array_values($var));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
}
// treat it like a regular array
$elements = array_map(array($this, 'encode'), $var);
foreach($elements as $element) {
if(Services_JSON::isError($element)) {
return $element;
}
}
return '[' . join(',', $elements) . ']';
case 'object':
$vars = get_object_vars($var);
$properties = array_map(array($this, 'name_value'),
array_keys($vars),
array_values($vars));
foreach($properties as $property) {
if(Services_JSON::isError($property)) {
return $property;
}
}
return '{' . join(',', $properties) . '}';
default:
return ($this->use & SERVICES_JSON_SUPPRESS_ERRORS)
? 'null'
: new Services_JSON_Error(gettype($var)." can not be encoded as JSON string");
}
}
/**
* array-walking function for use in generating JSON-formatted name-value pairs
*
* @param string $name name of key to use
* @param mixed $value reference to an array element to be encoded
*
* @return string JSON-formatted name-value pair, like '"name":value'
* @access private
*/
function name_value($name, $value)
{
$encoded_value = $this->encode($value);
if(Services_JSON::isError($encoded_value)) {
return $encoded_value;
}
return $this->encode(strval($name)) . ':' . $encoded_value;
}
/**
* reduce a string by removing leading and trailing comments and whitespace
*
* @param $str string string value to strip of comments and whitespace
*
* @return string string value stripped of comments and whitespace
* @access private
*/
function reduce_string($str)
{
$str = preg_replace(array(
// eliminate single line comments in '// ...' form
'#^\s*//(.+)$#m',
// eliminate multi-line comments in '/* ... */' form, at start of string
'#^\s*/\*(.+)\*/#Us',
// eliminate multi-line comments in '/* ... */' form, at end of string
'#/\*(.+)\*/\s*$#Us'
), '', $str);
// eliminate extraneous space
return trim($str);
}
/**
* decodes a JSON string into appropriate variable
*
* @param string $str JSON-formatted string
*
* @return mixed number, boolean, string, array, or object
* corresponding to given JSON input string.
* See argument 1 to Services_JSON() above for object-output behavior.
* Note that decode() always returns strings
* in ASCII or UTF-8 format!
* @access public
*/
function decode($str)
{
$str = $this->reduce_string($str);
switch (strtolower($str)) {
case 'true':
return true;
case 'false':
return false;
case 'null':
return null;
default:
$m = array();
if (is_numeric($str)) {
// Lookie-loo, it's a number
// This would work on its own, but I'm trying to be
// good about returning integers where appropriate:
// return (float)$str;
// Return float or int, as appropriate
return ((float)$str == (integer)$str)
? (integer)$str
: (float)$str;
} elseif (preg_match('/^("|\').*(\1)$/s', $str, $m) && $m[1] == $m[2]) {
// STRINGS RETURNED IN UTF-8 FORMAT
$delim = substr($str, 0, 1);
$chrs = substr($str, 1, -1);
$utf8 = '';
$strlen_chrs = strlen($chrs);
for ($c = 0; $c < $strlen_chrs; ++$c) {
$substr_chrs_c_2 = substr($chrs, $c, 2);
$ord_chrs_c = ord($chrs{$c});
switch (true) {
case $substr_chrs_c_2 == '\b':
$utf8 .= chr(0x08);
++$c;
break;
case $substr_chrs_c_2 == '\t':
$utf8 .= chr(0x09);
++$c;
break;
case $substr_chrs_c_2 == '\n':
$utf8 .= chr(0x0A);
++$c;
break;
case $substr_chrs_c_2 == '\f':
$utf8 .= chr(0x0C);
++$c;
break;
case $substr_chrs_c_2 == '\r':
$utf8 .= chr(0x0D);
++$c;
break;
case $substr_chrs_c_2 == '\\"':
case $substr_chrs_c_2 == '\\\'':
case $substr_chrs_c_2 == '\\\\':
case $substr_chrs_c_2 == '\\/':
if (($delim == '"' && $substr_chrs_c_2 != '\\\'') ||
($delim == "'" && $substr_chrs_c_2 != '\\"')) {
$utf8 .= $chrs{++$c};
}
break;
case preg_match('/\\\u[0-9A-F]{4}/i', substr($chrs, $c, 6)):
// single, escaped unicode character
$utf16 = chr(hexdec(substr($chrs, ($c + 2), 2)))
. chr(hexdec(substr($chrs, ($c + 4), 2)));
$utf8 .= $this->utf162utf8($utf16);
$c += 5;
break;
case ($ord_chrs_c >= 0x20) && ($ord_chrs_c <= 0x7F):
$utf8 .= $chrs{$c};
break;
case ($ord_chrs_c & 0xE0) == 0xC0:
// characters U-00000080 - U-000007FF, mask 110XXXXX
//see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 2);
++$c;
break;
case ($ord_chrs_c & 0xF0) == 0xE0:
// characters U-00000800 - U-0000FFFF, mask 1110XXXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 3);
$c += 2;
break;
case ($ord_chrs_c & 0xF8) == 0xF0:
// characters U-00010000 - U-001FFFFF, mask 11110XXX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 4);
$c += 3;
break;
case ($ord_chrs_c & 0xFC) == 0xF8:
// characters U-00200000 - U-03FFFFFF, mask 111110XX
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 5);
$c += 4;
break;
case ($ord_chrs_c & 0xFE) == 0xFC:
// characters U-04000000 - U-7FFFFFFF, mask 1111110X
// see http://www.cl.cam.ac.uk/~mgk25/unicode.html#utf-8
$utf8 .= substr($chrs, $c, 6);
$c += 5;
break;
}
}
return $utf8;
} elseif (preg_match('/^\[.*\]$/s', $str) || preg_match('/^\{.*\}$/s', $str)) {
// array, or object notation
if ($str{0} == '[') {
$stk = array(SERVICES_JSON_IN_ARR);
$arr = array();
} else {
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = array();
} else {
$stk = array(SERVICES_JSON_IN_OBJ);
$obj = new stdClass();
}
}
array_push($stk, array('what' => SERVICES_JSON_SLICE,
'where' => 0,
'delim' => false));
$chrs = substr($str, 1, -1);
$chrs = $this->reduce_string($chrs);
if ($chrs == '') {
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} else {
return $obj;
}
}
//print("\nparsing {$chrs}\n");
$strlen_chrs = strlen($chrs);
for ($c = 0; $c <= $strlen_chrs; ++$c) {
$top = end($stk);
$substr_chrs_c_2 = substr($chrs, $c, 2);
if (($c == $strlen_chrs) || (($chrs{$c} == ',') && ($top['what'] == SERVICES_JSON_SLICE))) {
// found a comma that is not inside a string, array, etc.,
// OR we've reached the end of the character list
$slice = substr($chrs, $top['where'], ($c - $top['where']));
array_push($stk, array('what' => SERVICES_JSON_SLICE, 'where' => ($c + 1), 'delim' => false));
//print("Found split at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
if (reset($stk) == SERVICES_JSON_IN_ARR) {
// we are in an array, so just push an element onto the stack
array_push($arr, $this->decode($slice));
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
// we are in an object, so figure
// out the property name and set an
// element in an associative array,
// for now
$parts = array();
if (preg_match('/^\s*(["\'].*[^\\\]["\'])\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// "name":value pair
$key = $this->decode($parts[1]);
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
} elseif (preg_match('/^\s*(\w+)\s*:\s*(\S.*),?$/Uis', $slice, $parts)) {
// name:value pair, where name is unquoted
$key = $parts[1];
$val = $this->decode($parts[2]);
if ($this->use & SERVICES_JSON_LOOSE_TYPE) {
$obj[$key] = $val;
} else {
$obj->$key = $val;
}
}
}
} elseif ((($chrs{$c} == '"') || ($chrs{$c} == "'")) && ($top['what'] != SERVICES_JSON_IN_STR)) {
// found a quote, and we are not inside a string
array_push($stk, array('what' => SERVICES_JSON_IN_STR, 'where' => $c, 'delim' => $chrs{$c}));
//print("Found start of string at {$c}\n");
} elseif (($chrs{$c} == $top['delim']) &&
($top['what'] == SERVICES_JSON_IN_STR) &&
((strlen(substr($chrs, 0, $c)) - strlen(rtrim(substr($chrs, 0, $c), '\\'))) % 2 != 1)) {
// found a quote, we're in a string, and it's not escaped
// we know that it's not escaped becase there is _not_ an
// odd number of backslashes at the end of the string so far
array_pop($stk);
//print("Found end of string at {$c}: ".substr($chrs, $top['where'], (1 + 1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '[') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-bracket, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_ARR, 'where' => $c, 'delim' => false));
//print("Found start of array at {$c}\n");
} elseif (($chrs{$c} == ']') && ($top['what'] == SERVICES_JSON_IN_ARR)) {
// found a right-bracket, and we're in an array
array_pop($stk);
//print("Found end of array at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($chrs{$c} == '{') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a left-brace, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_OBJ, 'where' => $c, 'delim' => false));
//print("Found start of object at {$c}\n");
} elseif (($chrs{$c} == '}') && ($top['what'] == SERVICES_JSON_IN_OBJ)) {
// found a right-brace, and we're in an object
array_pop($stk);
//print("Found end of object at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
} elseif (($substr_chrs_c_2 == '/*') &&
in_array($top['what'], array(SERVICES_JSON_SLICE, SERVICES_JSON_IN_ARR, SERVICES_JSON_IN_OBJ))) {
// found a comment start, and we are in an array, object, or slice
array_push($stk, array('what' => SERVICES_JSON_IN_CMT, 'where' => $c, 'delim' => false));
$c++;
//print("Found start of comment at {$c}\n");
} elseif (($substr_chrs_c_2 == '*/') && ($top['what'] == SERVICES_JSON_IN_CMT)) {
// found a comment end, and we're in one now
array_pop($stk);
$c++;
for ($i = $top['where']; $i <= $c; ++$i)
$chrs = substr_replace($chrs, ' ', $i, 1);
//print("Found end of comment at {$c}: ".substr($chrs, $top['where'], (1 + $c - $top['where']))."\n");
}
}
if (reset($stk) == SERVICES_JSON_IN_ARR) {
return $arr;
} elseif (reset($stk) == SERVICES_JSON_IN_OBJ) {
return $obj;
}
}
}
}
/**
* @todo Ultimately, this should just call PEAR::isError()
*/
function isError($data, $code = null)
{
if (class_exists('pear')) {
return PEAR::isError($data, $code);
} elseif (is_object($data) && (get_class($data) == 'services_json_error' ||
is_subclass_of($data, 'services_json_error'))) {
return true;
}
return false;
}
}
if (class_exists('PEAR_Error')) {
class Services_JSON_Error extends PEAR_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
parent::PEAR_Error($message, $code, $mode, $options, $userinfo);
}
}
} else {
/**
* @todo Ultimately, this class shall be descended from PEAR_Error
*/
class Services_JSON_Error
{
function Services_JSON_Error($message = 'unknown error', $code = null,
$mode = null, $options = null, $userinfo = null)
{
}
}
}
?>

View file

@ -0,0 +1,140 @@
<?php
/***************************************************************************
* class.alliance.php
* --------------------
* begin : Vendredi 10 octobre 2008
* update : Samedi 11 octobre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Alliance extends SURFACE{
var $id,
$race,
$fondateur,
$sante,
$nom,
$tag,
$galaxie,
$ss,
$nom_asteroide,
$image_asteroide,
$debris_met,
$debris_cri,
$credits,
$metal,
$cristal,
$hydrogene;
/**
* Constructeur
* @param int $id id de l'alliance à importer
*
* @return void
* @access public
*/
function Alliance($id = 0){
if (!empty($id)) {
global $var___db, $config, $table_alliances;
global $alli_batimentVAR, $spatialVAR;
$bdd = new bdd();
$bdd->connexion();
$bdd->escape($id);
$alli = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
if (!empty($alli)) {
$this->id = $alli["id"];
$this->race = $alli["race"];
$this->fondateur = $alli["fondateur"];
$this->sante = $alli["sante"];
$this->nom = $alli["nom"];
$this->tag = $alli["tag"];
$this->galaxie = $alli["galaxie"];
$this->ss = $alli["ss"];
$this->position = $alli["wing"];
$this->nom_asteroide = $alli["nom_asteroide"];
$this->image_asteroide = $alli["image_asteroide"];
$this->debris_met = $alli["debris_met"];
$this->debris_cri = $alli["debris_cri"];
$this->credits = $alli["credits"];
$this->metal = $alli["metal"];
$this->cristal = $alli["cristal"];
$this->hydrogene = $alli["hydrogene"];
foreach($alli_batimentVAR as $bat){
$this->batiments[] = $alli[$bat];
}
$this->file_bat = unserialize($alli["file_bat"]);
foreach($spatialVAR as $vais){
$this->vaisseaux[] = $plan[$vais];
}
$this->file_vais = unserialize($alli["file_vais"]);
$this->actualiser();
}
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true){
//Actualisation des files d'attentes
if ($actuFile) {
$this->file_pret("alli_batiments");
$this->file_pret("vaisseaux");
}
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $var___db, $config, $table_alliances;
$nb = count($this->modif);
$out = array();
$bdd = new bdd();
$bdd->connexion();
for($i = 0; $i < $nb; $i++){
if (!is_array($this->{$this->modif[$i]})) {
$bdd->escape($this->{$this->modif[$i]});
if (is_int($this->{$this->modif[$i]}) || is_float($this->{$this->modif[$i]})) $out[] .= $this->modif[$i]." = ".$this->{$this->modif[$i]};
else $out[] .= $this->modif[$i]." = '".$this->{$this->modif[$i]}."'";
}
else {
if (ereg('file', $this->modif[$i])) {
$prep = serialize($this->{$this->modif[$i]});
$bdd->escape($prep);
$out[] .= $this->modif[$i]." = '$prep'";
}
else {
if ($this->modif[$i] == "batiments") $calc = "batiment";
elseif ($this->modif[$i] == "alli_batiments") $calc = "alli_batiment";
elseif ($this->modif[$i] == "technologies") $calc = "technolo";
elseif ($this->modif[$i] == "casernes")$calc = "casernen";
elseif ($this->modif[$i] == "terrestres") $calc = "nomterrn";
elseif ($this->modif[$i] == "vaisseaux") $calc = "nomvaisn";
elseif ($this->modif[$i] == "coeff_bat") $calc = "coeff";
if (!isset(${$calc.'VAR'})) global ${$calc.'VAR'};
$nombr = count(${$calc.'VAR'});
for($j = 0; $j < $nombr; $j++){
$bdd->escape($this->{$this->modif[$i]}[$j]);
$out[] .= ${$calc.'VAR'}[$j]." = ".$this->{$this->modif[$i]}[$j]."";
}
}
}
}
if (!empty($out)) $plan = $bdd->unique_query("UPDATE $table_alliances SET ".implode(', ', $out)." WHERE id = ".$this->id.";");
$bdd->deconnexion();
}
}
?>

View file

@ -0,0 +1,385 @@
<?php
include_once("Class/surface.php");
/***************************************************************************
* class.asteroide.php
* ---------------------
* begin : Jeudi 25 décembre 2008
* update : Dimanche 4 janvier 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Asteroide extends Surface
{
var $fondateur,
$sante,
$nom_alliance,
$tag,
$wing,
$nom_asteroide,
$image_asteroide,
$position = 5,
$cap = 123456789,
$credits_alliance,
$points_alliance,
$url_chat,
$url_forum,
$details = array();
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id = 0)
{
if (!empty($id)) {
global $table_alliances, $SESS;
global $alli_batimentsVAR, $spatialVAR;
$bdd = new BDD();
//On traite le cas où l'on envoie les coordonnées
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
die('Erreur #04 : Format de recherche d\'asteroide incorrect !');
if (!empty($plan))
{
$this->id = $plan["id"];
parent::User($SESS->values['id']); //On utilise le numéro d'utilisateur enregistré en session
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->points_alliance = $plan["points_alliance"];
$this->nom_asteroide = $plan["nom_asteroide"];
$this->image = $this->image_asteroide = $plan["image_asteroide"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
$this->credits_alliance = $plan["credits_alliance"];
$this->fondateur = $plan["fondateur"];
$this->nom_alliance = $plan["nom_alliance"];
$this->wing = $plan["wing"];
$this->tag = $plan["tag"];
$this->url_forum = $plan["url_forum"];
$this->url_chat = $plan["url_chat"];
foreach($alli_batimentsVAR as $bat)
$this->batiments[] = $plan[$bat];
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new FileAlliancesBatiments();
foreach($spatialVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new FileSpatial('vaisseaux');
}
}
}
function loadDetails()
{
global $table_alliances, $table_user;
$bdd = new bdd();
$this->details = array_merge($bdd->unique_query("SELECT presentation, message_inscription, texte_interne, port_chat, chan_chat, image, etat_inscription, defcon, defcon_txt FROM $table_alliances WHERE id = ".$this->id.";"), $bdd->unique_query("SELECT COUNT(id) AS nb_membres FROM $table_user WHERE id_alliance = ".$this->id.";"));
$bdd->deconnexion();
}
function actualiser($actuFile = true, $first = false)
{
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_bat->ready($this);
$this->file_vais->ready($this);
}
}
function checkAndRetireRessources($metal, $cristal, $hydrogene, $credits)
{
if ($this->metal >= $metal && $this->cristal >= $cristal && $this->hydrogene >= $hydrogene && $this->credits_alliance >= $credits)
{
$this->metal -= $metal;
$this->cristal -= $cristal;
$this->hydrogene -= $hydrogene;
$this->credits -= $credits;
$this->addModif("force");
$this->addModif("credits_alliance");
return true;
}
else
return false;
}
function addRessources($metal, $cristal, $hydrogene, $credits)
{
$perte = 0;
$this->metal += $metal;
if ($this->metal > $this->cap)
{
$perte += $this->metal - $this->cap;
$this->metal = $this->cap;
}
$this->cristal += $cristal;
if ($this->cristal > $this->cap)
{
$perte += $this->cristal - $this->cap;
$this->cristal = $this->cap;
}
$this->hydrogene += $hydrogene;
if ($this->hydrogene > $this->cap)
{
$perte += $this->hydrogene - $this->cap;
$this->hydrogene = $this->cap;
}
$this->hydrogecredits_alliancene += $credits;
$this->addModif("force");
$this->addModif("credits_alliance");
return $perte;
}
function addCreditsAlliance($credits)
{
$this->credits_alliance += $credits;
$this->addModif("credits_alliance");
return 0;
}
function addPoints($metal, $cristal, $hydrogene, $credits = 0, $demolition = false)
{
global $table_bourse_ressources;
//On charge les 3 valeurs boursières
$bdd = new BDD();
$bourse = $bdd->query("SELECT dispo FROM $table_bourse_ressources;");
$bdd->deconnexion();
if (!empty($credits))
{
//TODO Equivalence non prouvée entre $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7); et $credits/bourse_calcPrixBase($bourse[0]["dispo"], 1) * 0.7; dans le but de ne donner que 70% des points
$metal += $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7);
$cristal += $credits/bourse_calcPrixBase($bourse[1]["dispo"], 0.7);
$hydrogene += $credits/bourse_calcPrixBase($bourse[2]["dispo"], 0.7);
}
$points = bourse_calcPrixBase($bourse[0]["dispo"], $metal);
$points += bourse_calcPrixBase($bourse[1]["dispo"], $cristal);
$points += bourse_calcPrixBase($bourse[2]["dispo"], $hydrogene);
if ($demolition)
$this->points_alliance -= intval($points);
else
$this->points_alliance += intval($points);
$this->addModif("points_alliance");
}
function creer($fondateur, $mere = false)
{
global $VAR, $table_alliances_creation;
$bdd = new BDD();
$alliance = $bdd->unique_query("SELECT * FROM $table_alliances_creation WHERE fondateur = ".$fondateur->id_user." LIMIT 1;");
$bdd->deconnexion();
//On vérifie que l'alliance n'a pas déjà été créée
if (empty($alliance))
return 1;
//Définition des paramètres de l'utilisateur pour l'astéroide
$this->fondateur = $alliance["fondateur"];
$this->race = $fondateur->race;
//Génération du nombre de case et de l'image en fonction de la position dans le système
$this->sante = 1;
$this->nom_alliance = $alliance["nom_alliance"];
$this->tag = $alliance["tag"];
$this->nom_asteroide = $alliance["nom_alliance"];
$this->image_asteroide = mt_rand(1,3);
$this->modif = array("fondateur", "race", "nom_alliance", "galaxie", "ss", "tag", "nom_asteroide", "image_asteroide");
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->fondateur))
return;
if (DEBUG)
var_dump($this);
global $table_alliances;
if (empty($this->id))
{
$outNomChamps = array(); $outValeurs = array();
$bdd = new BDD();
foreach($this->modif as $modif)
{
//On gère les champs variables tableaux
if (is_array($modif))
{
if ($modif[0] == "batiments")
$calc = dDonnees::nameVAR("alli_batiments");
else
$calc = dDonnees::nameVAR($modif[0]);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$outNomChamps[] = ${$calc.'VAR'}[$modif[1]];
$outValeurs[] = $this->{$modif[0]}[$modif[1]];
}
elseif ($modif == "force")
{
$outNomChamps[] = "metal";
$outNomChamps[] = "cristal";
$outNomChamps[] = "hydrogene";
$outValeurs[] = $this->metal;
$outValeurs[] = $this->cristal;
$outValeurs[] = $this->hydrogene;
}
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$outNomChamps[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$outValeurs[] = $this->{$modif};
else
$outValeurs[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$outNomChamps[] = $modif;
$outValeurs[] = "'$prep'";
}
else
{
$calc = dDonnees::nameVAR($modif);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$outNomChamps[] = ${$calc.'VAR'}[$j];
$outValeurs[] = $value;
}
}
}
}
//On supprime le lien de construction de l'alliance
$bdd->query("DELETE FROM $table_alliances_creation WHERE fondateur = ".$this->fondateur.";");
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : fondateur = ".$this->fondateur, 2);
//On ajout l'astéroide
$bdd->query("INSERT INTO $table_alliances (".implode(', ', $outNomChamps).") VALUES (".implode(', ', $outValeurs).");");
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : outNomChamps = ".serialize($outNomChamps)." ; outValeurs = ".serialize($outValeurs), 2);
$bdd->deconnexion();
}
else
{
$out = array();
$bdd = new BDD();
foreach($this->modif as $modif)
{
//On gère les champs variables tableaux
if (is_array($modif))
{
if ($modif[0] == "batiments")
$calc = dDonnees::nameVAR("alli_batiments");
else
$calc = dDonnees::nameVAR($modif[0]);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
if (empty(${$calc.'VAR'}))
trigger_error('Impossible de trouver les données pour '.$modif[0], E_USER_ERROR);
$out[] = ${$calc.'VAR'}[$modif[1]]." = ".$this->{$modif[0]}[$modif[1]];
}
elseif ($modif == "force")
{
$out[] = "metal = ".$this->metal;
$out[] = "cristal = ".$this->cristal;
$out[] = "hydrogene = ".$this->hydrogene;
}
elseif (!is_array($this->{$modif}) && !is_object($this->{$modif}))
{
$bdd->escape($this->{$modif});
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] = $modif." = ".$this->{$modif};
else
$out[] = $modif." = '".$this->{$modif}."'";
}
else
{
if ($modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out[] = $modif." = '$prep'";
}
else
{
$calc = dDonnees::nameVAR($modif);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
$out[] = ${$calc.'VAR'}[$j]." = ".$value;
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_alliances SET ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG)
echo '<br /><br />'.$sql;
$bdd->query($sql);
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out), 2);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,42 @@
<?php
/**
*
*
*/
class Attaques
{
var $groupes = array();
/**
* Constructor
*/
function __construct()
{
}
function addGroupe($groupe)
{
$this->groupes[] = $groupe;
}
function checkAllGroupes()
{
foreach ($groupes as $key => $groupe)
$this->checkGroupe($key);
}
function checkGroupe($id)
{
if (is_a($this->groupes[$id], "Groupe"))
{
if ($this->groupes[$id]->)
{
}
}
$groupes[$id]->
}
}
?>

View file

@ -0,0 +1,190 @@
<?php
/**
* Classe Bourse par Pierre-Olivier MERCIER
* Dernière édition le 21 Juillet 2008
* Copyright Halo-Battle Tous droits réservés
*/
class Bourse{
var $bd;
var $id;
var $nom;
var $taxeA = 1.1;
var $taxeV = 1.5;
var $metal;
var $cristal;
var $actionsUser;
var $user;
/**
* Constructor
*
* @param String $nom Nom de l'action
* @param int $user ID du joueur à charger automatiquement
*
* @access protected
*/
function Bourse($nom = "", $user = 0){
global $var___db, $config;
$db = new bdd();
$db->connexion();
$this->bd = $db;
if (!empty($nom)) {
$this->loadAction($nom, "id");
if (!empty($user)) $this->loadUser($user);
}
}
function __destruct(){
$this->bd->deconnexion();
}
function loadAction($nom, $type = "nom"){
global $table_bourse;
$this->bd->escape($nom);
$act = $this->bd->unique_query("SELECT * FROM $table_bourse WHERE $type = '$nom';");
if ($act) {
$this->id = $act['id'];
$this->nom = $act['nom'];
$this->metal = $act['metal'];
$this->cristal = $act['cristal'];
}
else erreur('Impossible de trouver cette action !', "red", '?p=bourse');
}
function loadUser($user, $type = "id"){
global $table_user;
$this->bd->escape($user);
$act = $this->bd->unique_query("SELECT id, bourse FROM $table_user WHERE $type = '$user';");
$this->user = $act['id'];
$this->traitUser($act['bourse']);
}
function traitUser($start){
$end = array();
$start = explode(';', $start);
$cnt = count($start);
for($i = 0; $i < $cnt; $i++){
$tmp = explode(':', $start[$i]);
if (!empty($tmp[1])) $end[$tmp[0]] = explode(',', $tmp[1]);
else $end[$tmp[0]] = array();
}
$this->actionsUser = $end;
}
function prixAchat($nb){
return array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
}
function prixVente($nb){
if ($this->action() < $nb) $nb = $this->action();
return array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
}
function addAction($nb){
$ret = array(floor($this->metal * $nb * $this->taxeA), floor($this->cristal * $nb * $this->taxeA));
$this->metal *= pow(1.1, $nb);
$this->cristal *= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
$this->actionsUser[$this->id][] = time();
}
$this->maj();
return $ret;
}
function delAction($nb){
if ($this->action() < $nb) $nb = $this->action();
$ret = array(floor($this->metal * $nb / $this->taxeV), floor($this->cristal * $nb / $this->taxeV));
$this->metal /= pow(1.1, $nb);
$this->cristal /= pow(1.1, $nb);
for($i = 0; $i < $nb; $i++){
unset($this->actionsUser[$this->id][$i]);
}
$this->maj();
return $ret;
}
function actionIn24Hours(){
$nb = 0;
if (isset($this->actionsUser[$this->id])) {
$cnt = count($this->actionsUser[$this->id]);
for($i = 0; $i < $cnt; $i++){
if ($this->actionsUser[$this->id][$i] > time() - 86400) $nb++;
}
}
return $nb;
}
function action(){
if (isset($this->actionsUser[$this->id])) return count($this->actionsUser[$this->id]);
else return 0;
}
function maj(){
$this->majBourse();
$this->majUser();
$this->fileSave();
}
function majBourse(){
global $table_bourse;
$this->bd->query("UPDATE $table_bourse SET nom = '".$this->nom."', metal = '".$this->metal."', cristal = '".$this->cristal."' WHERE id = ".$this->id.";");
}
function majUser(){
global $table_user;
$champ = '';
foreach($this->actionsUser as $key => $cell) {
if (count($cell) > 0) {
if (empty($champ)) $champ .= $key.':'.implode(',', $cell);
else $champ .= ';'.$key.':'.implode(',', $cell);
}
}
$this->bd->query("UPDATE $table_user SET bourse = '$champ' WHERE id = ".$this->user.";");
}
function delUser($id = ""){
if (!empty($id)) $this->loadUser($id);
$champ = '';
foreach($this->actionsUser as $key => $cell) {
$cnt = count($cell);
if ($cnt > 0) {
$this->loadAction($key, "id");
$this->delAction($cnt);
}
}
}
function fileSave(){
$fichier = fopen(_FCORE."../game/cache/bourse/".$this->id.".".strftime('%Y%m%d').".bourse",'a+');
fwrite($fichier, time().';'.$this->metal.';'.$this->cristal."\n");
fclose($fichier);
}
function newGroupe($nom, $metal, $cristal, $description = ""){
global $table_bourse;
$this->bd->query("INSERT INTO $table_bourse (nom, metal, cristal, description) VALUES('$nom', '$metal', '$cristal', '$description');");
}
function editGroupe($description){
//TODO toute cette fonction !!
}
}
?>

View file

@ -0,0 +1,262 @@
<?php
/***************************************************************************
* class.var.php
* ---------------
* begin : Jeudi 29 janvier 2009
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Donnee
{
static function donneeTechnologie($branche, $idTechnologie, $retour, Planete $planete)
{
//TODO : Faire un switch pour ne renvoyer le tableau que de la branche plutôt que ce tableau avec l'intégralité des branches.
$technologies_donnees = array(
//Industrie
array(
array(1, 0, 1000, 54000),
array(2, 1, 2000, 90000),
array(4, 3, 4000, 126000),
array(8, 1, 4000, 126000),
array(16, 1, 2000, 72000),
array(32, 17, 4000, 108000),
array(64, 49, 8000, 144000),
array(128, 1, 2000, 72000),
array(256, 129, 4000, 108000),
array(512, 385, 8000, 144000),
array(1024, 1, 2000, 72000),
array(2048, 1025, 4000, 108000),
array(4096, 3073, 8000, 144000),
array(8192, 9, 3000, 126000),
array(16384, 8201, 6000, 162000),
array(32768, 24585, 12000, 198000),
array(65536, 1169, 3000, 126000),
array(131072, 66705, 6000, 162000),
array(262144, 197777, 12000, 198000)
),
//Ingénieurie
array(
array(1, 0, 1000, 54000),
array(2, 1, 2000, 90000),
array(4, 3, 4000, 126000),
array(8, 1, 2000, 90000),
array(16, 9, 4000, 126000),
array(32, 25, 8000, 162000),
array(64, 9, 3000, 126000),
array(128, 73, 6000, 162000),
array(256, 201, 12000, 198000),
array(512, 73, 4000, 162000),
array(1024, 585, 8000, 198000),
array(2048, 1609, 16000, 234000),
array(4096, 0, 1000, 54000),
array(8192, 4096, 2000, 90000),
array(16384, 12288, 4000, 126000),
array(32768, 4096, 2000, 54000),
array(65536, 36864, 4000, 90000),
array(131072, 102400, 8000, 126000),
array(262144, 12288, 2000, 72000),
array(524288, 274432, 4000, 108000),
array(1048576, 798720, 8000, 144000),
array(2097152, 274432, 2000, 54000),
array(4194304, 2371584, 4000, 90000),
array(8388608, 6565888, 8000, 126000),
array(16777216, 28672, 2000, 54000),
array(33554432, 16805888, 4000, 90000),
array(67108864, 50360320, 8000, 126000),
array(134217728, 28672, 3000, 90000),
array(268435456, 134246400, 6000, 126000),
array(536870912, 402681856, 12000, 162000)
),
//Ingénieurie 2
array(
array(1, 0, 1000, 36000),
array(2, 1, 2000, 72000),
array(4, 3, 4000, 108000),
array(8, 1, 4000, 126000),
array(16, 1, 4000, 126000),
array(32, 25, 4000, 126000),
array(64, 57, 8000, 162000),
array(128, 121, 16000, 198000)
),
//Politique
array(
array(1, 0, 1000, 36000),
array(2, 1, 2000, 72000),
array(4, 3, 4000, 108000),
array(8, 1, 2000, 72000),
array(16, 9, 4000, 108000),
array(32, 25, 8000, 144000),
array(64, 9, 4000, 126000),
array(128, 8, 6000, 162000),
array(256, 9, 6000, 162000),
array(512, 0, 1000, 90000),
array(1024, 512, 2000, 90000),
array(2048, 1536, 4000, 90000),
array(4096, 512, 2000, 72000),
array(8192, 4608, 4000, 108000),
array(16384, 12800, 8000, 144000)
),
//Armement
array(
array(1, 0, 1000, 36000),
array(2, 1, 2000, 72000),
array(4, 3, 4000, 108000),
array(8, 1, 1000, 54000),
array(16, 9, 2000, 90000),
array(32, 25, 4000, 126000),
array(64, 9, 2000, 72000),
array(128, 73, 4000, 108000),
array(256, 201, 8000, 144000),
array(512, 73, 2000, 90000),
array(1024, 585, 4000, 126000),
array(2048, 1609, 8000, 162000),
array(4096, 1, 3000, 108000),
array(8192, 4097, 6000, 144000),
array(16384, 12289, 12000, 180000),
array(32768, 4097, 3000, 126000),
array(65536, 36865, 6000, 162000),
array(131072, 102401, 12000, 198000)
),
//Défense
array(
array(1, 0, 1000, 36000),
array(2, 1, 2000, 72000),
array(4, 3, 4000, 108000),
array(8, 1, 2000, 72000),
array(16, 9, 4000, 108000),
array(32, 25, 8000, 144000),
array(64, 9, 3000, 108000),
array(128, 73, 6000, 144000),
array(256, 201, 12000, 180000),
array(512, 0, 1000, 36000),
array(1024, 512, 2000, 72000),
array(2048, 1536, 4000, 108000),
array(4096, 512, 2000, 72000),
array(8192, 4608, 4000, 108000),
array(16384, 12800, 8000, 144000),
array(32768, 4608, 3000, 108000),
array(65536, 37376, 6000, 144000),
array(131072, 102912, 12000, 180000),
array(262144, 512, 1000, 54000),
array(524288, 262656, 2000, 90000),
array(1048576, 786944, 4000, 126000),
array(2097152, 262656, 2000, 90000),
array(4194304, 2359808, 4000, 126000),
array(8388608, 6554112, 8000, 162000),
array(16777216, 2359808, 3000, 126000),
array(33554432, 19137024, 6000, 162000),
array(67108864, 52691456, 12000, 198000)
),
//Défense 2
array(
array(1, 0, 2000, 72000),
array(2, 1, 4000, 144000),
array(4, 3, 6000, 216000),
array(8, 0, 2000, 72000),
array(16, 8, 4000, 144000),
array(32, 24, 6000, 216000),
array(64, 27, 8000, 288000)
),
//Projets expérimentaux
array(
array(1, 0, 2000, 36000),
array(2, 1, 4000, 72000),
array(4, 2, 4000, 108000),
array(8, 4, 6000, 144000),
array(16, 8, 6000, 144000),
array(32, 8, 8000, 180000),
array(64, 32, 10000, 216000),
array(128, 64, 10000, 234000),
array(256, 128, 12000, 288000),
array(512, 256, 14000, 324000),
array(1024, 64, 14000, 342000),
array(2048, 256, 16000, 360000),
array(4096, 576, 18000, 396000),
array(8192, 4096, 20000, 432000),
array(16384, 8192, 22000, 504000)
),
//Technologie expansion
array(
array(1, 0, 4000, 54000),
array(2, 1, 6000, 72000),
array(4, 3, 8000, 90000),
array(8, 7, 10000, 108000),
array(16, 15, 12000, 126000),
array(32, 31, 14000, 144000),
array(64, 63, 16000, 162000),
array(128, 127, 18000, 180000),
array(256, 255, 20000, 198000),
array(512, 511, 22000, 216000),
array(1024, 1023, 24000, 234000),
array(2048, 2047, 26000, 252000),
array(4096, 4095, 28000, 270000),
array(8192, 8191, 30000, 288000),
array(16384, 16383, 32000, 306000),
array(32768, 32767, 34000, 324000),
array(65536, 65535, 36000, 342000),
array(131072, 131071, 38000, 360000)
)
);
if ($retour == "metal") return 0;
elseif ($retour == "cristal") return 0;
elseif ($retour == "hydrogene") return 0;
elseif ($retour == "credits") return $technologies_donnees[$branche][$idTechnologie][2];
elseif ($retour == "temps") return $technologies_donnees[$branche][$idTechnologie][3]/VITESSE;
elseif ($retour == "needed") return $technologies_donnees[$branche][$idTechnologie][1];
elseif ($retour == "id") return $technologies_donnees[$branche][$idTechnologie][0];
elseif ($retour == "array") return array(0, 0, 0, $technologies_donnees[$branche][$idTechnologie][2], $technologies_donnees[$branche][$idTechnologie][3]/VITESSE);
}
static function metalTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "metal", $planete);
}
static function cristalTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "cristal", $planete);
}
static function hydrogeneTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "hydrogene", $planete);
}
static function creditsTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "credits", $planete);
}
static function tempsTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "temps", $planete);
}
static function idTechnologie($branche, $idTechnologie, Planete $planete)
{
return Donnee::donneeTechnologie($branche, $idTechnologie, "id", $planete);
}
static function neededTechnologie($branche, $idTechnologie, Planete $planete)
{
$neededTechnologies = Donnee::donneeTechnologie($branche, $idTechnologie, "needed", $planete);
if (empty($neededTechnologies)) return true;
if (is_array($neededTechnologies))
{
//TODO prévoir le besoin de plus d'une technologie pour la validation, dans une autre branche, batiment (?) ...
die('TODO '.__LINE__.' in '.__FILE__);
}
else
{
if (((int)$planete->technologies[$branche]& $neededTechnologies) == $neededTechnologies)
return true;
else
return false;
}
}
}
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,186 @@
<?php
/***************************************************************************
* class.flotteGroupee.php
* -------------------------
* begin : Samedi 21 mars 2009
* update : Samedi 21 mars 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class FlotteGroupee
{
var $id_flotte = 0,
$nom,
$end_planete,
$time_end,
$end_type,
$ret_planete,
$flottes = array(),
$mission,
$modifFlotte = array();
/**
* Constructeur
* @param int $id id de la flotte à importer
* @param bool $verrou Booléen disant si la classe doit obtenir préalablement un verrou pour la flotte.
*
* @return void
* @access public
*/
function __construct($id = 0, $verrou = true)
{
if (!empty($id))
{
global $table_flottes_preparation;
global $spatialVAR, $ressoVAR;
$id = intval($id);
$bdd = new BDD();
$flotte = $bdd->unique_query("SELECT * FROM $table_flottes_preparation WHERE id = $id;");
$bdd->deconnexion();
if (!empty($flotte))
{
$this->id_flotte = $flotte["id"];
$this->nom = $flotte["nom"];
$this->end_planete = $flotte["end_planete"];
$this->end_type = $flotte["end_type"];
$this->time_end = $flotte["time_end"];
$this->mission = $flotte["mission"];
if (empty($this->flottes)
$this->flottes = array();
else
$this->flottes = unserialize($flotte["flottes"]);
}
}
}
function load_planete()
{
if (is_numeric($this->end_planete) && !empty($this->end_planete))
{
//On traite l'importation en fonction des types fornis
if ($this->end_type == 0 || $this->end_type == 1)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "planete" && $planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Planete($this->end_planete);
}
else
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "asteroide" && $planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Asteroide($this->end_planete);
}
}
}
function addFlotte($start_planete, $vitesse, $vaisseaux, $contenu_metal, $contenu_cristal, $contenu_hydrogene)
{
$this->flottes[] = array($start_planete->id_user, $start_planete->id, $vitesse, $vaisseaux, $contenu_metal, $contenu_cristal, $contenu_hydrogene);
addModifFlotte("flottes");
}
function lancer()
{
}
function addModifFlotte($modif)
{
if (!in_array($modif, $this->modifFlotte))
$this->modifFlotte[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
global $table_flottes;
if ($this->modifFlotte === "DELETE")
{
$bdd = new BDD();
$bdd->query("DELETE FROM $table_flottes WHERE id = ".$this->id_flotte.";");
$bdd->deconnexion();
}
else
{
if (empty($this->id_flotte))
{
if ($this->modifFlotte == "INSERT")
{
$out1 = ''; $out2 = '';
global $spatialVAR;
foreach ($this->vaisseaux as $key => $vais)
{
$out1 .= ', '.$spatialVAR[$key];
$out2 .= ', '.$vais;
}
$sql = "INSERT INTO $table_flottes (id_user, mission, start_time, start_type, start_planete, end_time, end_type, end_planete, vitesse, contenu_metal, contenu_cristal, contenu_hydrogene, tactique, nom, nb_vais$out1) VALUES ('".$this->start_planete->id_user."', '".$this->mission."', '".$this->start_time."', '".$this->start_type."', '".$this->start_planete->id."', '".$this->end_time."', '".$this->end_type."', '".$this->end_planete."', '".$this->vitesse."', '".$this->contenu[0]."', '".$this->contenu[1]."', '".$this->contenu[2]."', '".$this->tactique."', '".$this->nom."', ".$this->nb_vais."$out2);";
if (DEBUG) echo $sql;
$bdd = new BDD();
$bdd->query($sql);
$bdd->deconnexion();
}
}
elseif(isset($this->modifFlotte[0]))
{
$out = array();
$bdd = new BDD();
foreach($this->modifFlotte as $modif)
{
if (!is_array($this->{$modif}))
{
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] .= $modif." = ".$this->{$modif};
else
{
$bdd->escape($this->{$modif});
$out[] .= $modif." = '".$this->{$modif}."'";
}
}
else
{
if ($modif == "contenu")
$calc = "resso";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach(${$calc.'VAR'} as $key => $var)
{
$bdd->escape($this->{$modif}[$key]);
$out[] = ${$calc.'VAR'}[$key]." = ".$this->{$modif}[$key];
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_flottes SET ".implode(', ', $out).", last = 0 WHERE id = ".$this->id_flotte.";";
if (DEBUG) var_dump($sql);
$bdd->query($sql);
}
$bdd->deconnexion();
}
}
}
}
?>

View file

@ -0,0 +1,505 @@
<?php
/***************************************************************************
* class.combat.php
* -------------------
* begin : Samedi 26 janvier 2008
* update : Mercredi 4 juin 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Combat {
var $refflotte = 0;
var $ATvais = array();
var $ENvais = array();
var $ENres = array('metal' => 0, 'cristal' => 0, 'hydrogene' => 0);
var $ENdef = array();
var $Ntour = 0;
var $ATtactique = 0;
var $ENtactique = 0;
var $timestamp = 0;
var $vaisContenu = 0;
var $vaisContenuM = 0;
var $vaisContenuC = 0;
var $vaisContenuH = 0;
var $pillage = array(0, 0, 0);
var $debriM = 0;
var $debriC = 0;
/**
* Constructeur
* @param array $flotteAT tableau SQL des vaisseaux envoyés par l'attaquant
* @param array $flotteEN tableau SQL de la planète du défenseur
* @param array $defEN tableau SQL de la planète du défenseur
*
* @return void
* @access public
*/
function Combat($flotteAT, $flotteEN, $defEN, $tableTechno = array(0, 0)) {
include(_FCORE."hb_game/vars.php");
//Génération des vaisseaux attaquants
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteAT['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteAT['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[0]/10), $nomvais_pv[$i-1]);
}
$this->ATvais[] = array($i, $flotteAT['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Définition d'autres variables de la classe concernant la flotte
$this->refflotte = $flotteAT['id'];
$this->vaisContenu = $flotteAT['contenu_max'];
$this->vaisContenuM = $flotteAT['contenu_metal'];
$this->vaisContenuC = $flotteAT['contenu_cristal'];
$this->vaisContenuH = $flotteAT['contenu_hydrogene'];
$this->timestamp = $flotteAT['start_time'] + $flotteAT['end_time'];
//Génération des vaisseaux défenseurs
for ($i=1 ; $i<=12 ; $i++) {
if ($flotteEN['vaisseau_'.$i] >= 1) {
//Création des groupes
$nbvais = $flotteEN['vaisseau_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $nomvais_bc[$i-1] * (1 + $tableTechno[1]/10), $nomvais_pv[$i-1]);
}
$this->ENvais[] = array($i, $flotteEN['vaisseau_'.$i], $nbgroupes, $groupe, $nomvais_initiative[$i-1]);
}
}
//Génération des défenses défenseurs
for ($i=1 ; $i<=5 ; $i++) {
if ($defEN['def_'.$i] >= 1) {
//Création des groupes
$nbvais = $defEN['def_'.$i];
$nbgroupes = floor(sqrt(ceil($nbvais/10)));
$nbvaispgroupe = floor($nbvais/$nbgroupes);
$nbrest = $nbvais - $nbvaispgroupe * $nbgroupes;
if (isset($groupe)) unset($groupe);
$groupe = array();
for ($j=0 ; $j < $nbgroupes ; $j++) {
if ($j == 0) $groupe[] = array($nbvaispgroupe + $nbrest, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
else $groupe[] = array($nbvaispgroupe, $defense_bc[$i-1] * (1 + $tableTechno[1]/10), $defense_pv[$i-1]);
}
$this->ENdef[] = array($i, $defEN['def_'.$i], $nbgroupes, $groupe, $defense_initiative[$i-1]);
}
}
}
/**
* Change la tactique de l'attaquant
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueAT($tactique) {
$this->ATtactique = ceil($tactique);
}
/**
* Change la tactique du défenseur
* @param int $tactique numéro de la tactique choisie
*
* @return void
* @access public
*/
function changerTactiqueEN($tactique) {
$this->ENtactique = ceil($tactique);
}
/**
* Régénére les boucliers
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant régénére le bouclier de l'attaquant si true, sinon régénrére celui du défenseur
* @param bool $retour si true, renvoie true ou false si !le pourcentage a été consommé ou non, si false, retrourne ne nombre de pourcentage restant
* @param int $blindage niveau de la technologie blindage du joueur
*
* @return float pourcentage non utilisé
* @access public
*/
function regenereBC($pourcentage, $attaquant, $retour = false, $blindage = 0) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
$count = count($this->ATvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ATvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ATvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] < $maxbc) {
$this->ATvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ATvais[$i][3][$j][0];
if ($this->ATvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ATvais[$i][3][$j][1] - $maxbc)*$this->ATvais[$i][3][$j][0];
$this->ATvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $enplus/$norm;
}
else {
$count = count($this->ENvais);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENvais[$i][0]-1;
$maxbc = $nomvais_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENvais[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] < $maxbc) {
$this->ENvais[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENvais[$i][3][$j][0];
if ($this->ENvais[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENvais[$i][3][$j][1] - $maxbc)*$this->ENvais[$i][3][$j][0];
$this->ENvais[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
//Défenses
$count = count($this->ENdef);
$enplus = 0;
$norm = 0;
for ($i=0 ; $i<$count ; $i++) {
$type = $this->ENdef[$i][0]-1;
$maxbc = $defense_bc[$type] * (1 + $blindage/10);
$ajout = $maxbc*$pourcentage/100;
$cntbc = count($this->ENdef[$i][3]);
for ($j=0 ; $j<$cntbc ; $j++) {
$norm += $maxbc * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] < $maxbc) {
$this->ENdef[$i][3][$j][1] += $ajout;
}
else $enplus += $ajout * $this->ENdef[$i][3][$j][0];
if ($this->ENdef[$i][3][$j][1] > $maxbc) {
$enplus += ($this->ENdef[$i][3][$j][1] - $maxbc)*$this->ENdef[$i][3][$j][0];
$this->ENdef[$i][3][$j][1] = $maxbc;
}
}
}
if ($norm != 0) $return = $enplus/$norm;
else $return = 0;
if ($retour) {
if($norm != 0 && $enplus/$norm == 1) return $pourcentage;
else return false;
}
else return $return/2;
}
}
/**
* Calcul la puissance d'attaque disponible
* @param int $pourcentage pourcentage de régénération
* @param bool $attaquant calcul les points de l'attaquant si true, sinon calcul pour le défenseur
* @param int $armement niveau de la technologie armement du joueur
* @param bool $method true pour utiliser la mèthode classique, false pour utiliser la méthode d'Apocalypse Joe
*
* @return int points disponibles
* @access public
*/
function calcAttaque($pourcentage, $attaquant, $armement = 0, $method = false) {
include(_FCORE."hb_game/vars.php");
if ($method) {
if ($attaquant) {
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1];
}
return $puissance;
}
else {
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1];
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
else {
if ($attaquant) {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ENvais);
$countd = count($this->ENdef);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ENvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ENvais[$i][0]] = $this->ENvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ATvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ATvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ATvais[$i][0]-1][$this->ENvais[$i][0]-1] * $vaisEff[$this->ENvais[$i][0]];
}
for ($j=0 ; $j<$countd ; $j++) {
$bonus += 1/$countd;
}
$maxat = $nomvais_at[$this->ATvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ATvais[$i][1] * $bonus;
}
return $puissance;
}
else {
//Calcul du pourcentage de chaque vaisseau adverse
$vaisEff = array();
$nbvais = 0;
$countj = count($this->ATvais);
for ($i=0 ; $i<$countj ; $i++) {
$nbvais += $this->ATvais[$i][1];
}
for ($i=0 ; $i<$countj ; $i++) {
$vaisEff[$this->ATvais[$i][0]] = $this->ATvais[$i][1]/$nbvais;
}
$puissance = 0;
$count = count($this->ENvais);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENvais[$i][4] > $this->Ntour) continue;
$bonus = 0;
for ($j=0 ; $j<$countj ; $j++) {
$bonus += $nomvais_rf[$this->ENvais[$i][0]-1][$this->ATvais[$i][0]-1] * $vaisEff[$this->ATvais[$i][0]];
}
$maxat = $nomvais_at[$this->ENvais[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENvais[$i][1] * $bonus;
}
//Défenses
$count = count($this->ENdef);
for ($i=0 ; $i<$count ; $i++) {
if ($this->ENdef[$i][4] > $this->Ntour) continue;
$maxat = $defense_at[$this->ENdef[$i][0]-1] * (1 + $armement/10);
$puissance += $maxat * $pourcentage/100 * $this->ENdef[$i][1];
}
return $puissance;
}
}
}
/**
* Attaque les vaisseaux adverses
* @param int $points points d'attaque disponible pour l'attaque
* @param bool $attaquant attaque le défenseur si true, sinon attaque l'attaquant
*
* @return void
* @access public
*/
function attaquerVais($points, $attaquant) {
include(_FCORE."hb_game/vars.php");
if ($attaquant) {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ENvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENvais[$i][1];
$nbgroupes += $this->ENvais[$i][2];
}
$nb = count($this->ENdef);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ENdef[$i][1];
$nbgroupes += $this->ENdef[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque contre les vaisseaux
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENvais)-1);
$l = rand(0, count($this->ENvais[$k][3])-1);
$this->ENvais[$k][3][$l][1] -= $ppv;
if ($this->ENvais[$k][3][$l][1] < 0) {
$this->ENvais[$k][3][$l][2] -= abs($this->ENvais[$k][3][$l][1]);
$this->ENvais[$k][3][$l][1] = 0;
if ($this->ENvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENvais[$k][3][$l][0] * $nomvais_md[$this->ENvais[$k][0]];
$this->debriC += $this->ENvais[$k][3][$l][0] * $nomvais_cd[$this->ENvais[$k][0]];
$this->ENvais[$k][1] -= $this->ENvais[$k][3][$l][0];
$this->ENvais[$k][2] --;
array_splice($this->ENvais[$k][3], $l, 1);
if (!count($this->ENvais[$k][3])) {
array_splice($this->ENvais, $k, 1);
}
}
}
}
//On lance l'attaque contre les défenses
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ENdef)-1);
$l = rand(0, count($this->ENdef[$k][3])-1);
$this->ENdef[$k][3][$l][1] -= $ppv;
if ($this->ENdef[$k][3][$l][1] < 0) {
$this->ENdef[$k][3][$l][2] -= abs($this->ENdef[$k][3][$l][1]);
$this->ENdef[$k][3][$l][1] = 0;
if ($this->ENdef[$k][3][$l][2] <= 0) {
$this->debriM += $this->ENdef[$k][3][$l][0] * $nomvais_md[$this->ENdef[$k][0]];
$this->debriC += $this->ENdef[$k][3][$l][0] * $nomvais_cd[$this->ENdef[$k][0]];
$this->ENdef[$k][1] -= $this->ENdef[$k][3][$l][0];
$this->ENdef[$k][2] --;
array_splice($this->ENdef[$k][3], $l, 1);
if (!count($this->ENdef[$k][3])) {
array_splice($this->ENdef, $k, 1);
}
}
}
}
}
return count($this->ENvais) + count($this->ENdef);
}
else {
while($points > 0) {
// Calcul du nombre de vaisseaux et défenses à attaquer
$nbvais = 0;
$nbgroupes = 0;
$nb = count($this->ATvais);
for ($i=0 ; $i<$nb ; $i++) {
$nbvais += $this->ATvais[$i][1];
$nbgroupes += $this->ATvais[$i][2];
}
//S'il ne reste plus de vaisseaux et de défenses, on arrête la boucle
if ($nbvais <= 0 || $nbgroupes <= 0 || $points <= 0) break;
//Calcul du nombre de points qui sera enlevé par vaisseau ou défense
$ppv = $points / $nbvais;
$points = 0;
//On lance l'attaque
for ($j=0 ; $j<$nbgroupes ; $j++){
$k = rand(0, count($this->ATvais)-1);
$l = rand(0, count($this->ATvais[$k][3])-1);
$this->ATvais[$k][3][$l][1] -= $ppv;
if ($this->ATvais[$k][3][$l][1] < 0) {
$this->ATvais[$k][3][$l][2] -= abs($this->ATvais[$k][3][$l][1]);
$this->ATvais[$k][3][$l][1] = 0;
if ($this->ATvais[$k][3][$l][2] <= 0) {
$this->debriM += $this->ATvais[$k][3][$l][0] * $nomvais_md[$this->ATvais[$k][0]];
$this->debriC += $this->ATvais[$k][3][$l][0] * $nomvais_cd[$this->ATvais[$k][0]];
$this->ATvais[$k][1] -= $this->ATvais[$k][3][$l][0];
$this->ATvais[$k][2] --;
array_splice($this->ATvais[$k][3], $l, 1);
if (!count($this->ATvais[$k][3])) {
array_splice($this->ATvais, $k, 1);
}
}
}
}
}
return count($this->ATvais);
}
}
function exportAT($pillage = false){
include(_FCORE."hb_game/vars.php");
$nb = count($this->ATvais);
$nbvais = 0; $vaisContenu = 0; $vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ATvais[$i][0]} += $this->ATvais[$i][1];
$nbvais += $this->ATvais[$i][1];
$this->vaisContenu += $nomvais_rs[$this->ATvais[$i][0]-1];
}
$sommeCont = $this->vaisContenuM + $this->vaisContenuC + $this->vaisContenuH;
if ($sommeCont > $this->vaisContenu) {
$retirer = $sommeCont/$this->vaisContenu;
$this->vaisContenuM = floor($this->vaisContenuM/$retirer);
$this->vaisContenuC = floor($this->vaisContenuC/$retirer);
$this->vaisContenuH = floor($this->vaisContenuH/$retirer);
}
if ($pillage) {
$ressplus = pillage($this->ENres['metal'], $this->ENres['cristal'], $this->ENres['hydrogene'], $this->vaisContenu - $this->vaisContenuM - $this->vaisContenuC - $this->vaisContenuH);
$this->vaisContenuM += $ressplus[0];
$this->vaisContenuC += $ressplus[1];
$this->vaisContenuH += $ressplus[2];
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
return 'nb_vais = \''.$nbvais.'\', contenu_max = \''.$this->vaisContenu.'\', contenu_metal = \''.$this->vaisContenuM.'\', contenu_cristal = \''.$this->vaisContenuC.'\', contenu_hydrogene = \''.$this->vaisContenuH.'\', vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\'';
}
function pillageSimul($metal, $cristal, $hydrogene){
$ressplus = pillage($metal, $cristal, $hydrogene, 999999);
$this->pillage = array($ressplus[0], $ressplus[1], $ressplus[2]);
}
function exportEN(){
$nb = count($this->ENvais);
$vaisseau_1 = 0; $vaisseau_2 = 0; $vaisseau_3 = 0; $vaisseau_4 = 0; $vaisseau_5 = 0; $vaisseau_6 = 0; $vaisseau_7 = 0; $vaisseau_8 = 0; $vaisseau_9 = 0; $vaisseau_10 = 0; $vaisseau_11 = 0; $vaisseau_12 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'vaisseau_'.$this->ENvais[$i][0]} += $this->ENvais[$i][1];
}
$nb = count($this->ENdef);
$def_1 = 0; $def_2 = 0; $def_3 = 0; $def_4 = 0; $def_5 = 0;
for($i=0 ; $i<$nb ; $i++) {
${'def_'.$this->ENdef[$i][0]} += $this->ENdef[$i][1];
}
return 'vaisseau_1 = \''.$vaisseau_1.'\', vaisseau_2 = \''.$vaisseau_2.'\', vaisseau_3 = \''.$vaisseau_3.'\', vaisseau_4 = \''.$vaisseau_4.'\', vaisseau_5 = \''.$vaisseau_5.'\', vaisseau_6 = \''.$vaisseau_6.'\', vaisseau_7 = \''.$vaisseau_7.'\', vaisseau_8 = \''.$vaisseau_8.'\', vaisseau_9 = \''.$vaisseau_9.'\', vaisseau_10 = \''.$vaisseau_10.'\', vaisseau_11 = \''.$vaisseau_11.'\', vaisseau_12 = \''.$vaisseau_12.'\', def_1 = \''.$def_1.'\', def_2 = \''.$def_2.'\', def_3 = \''.$def_3.'\', def_4 = \''.$def_4.'\', def_5 = \''.$def_5.'\'';
}
}
?>

View file

@ -0,0 +1,153 @@
<?php
/***************************************************************************
* class.exceptionHB.php
* -----------------------
* begin : Lundi 9 février 2009
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class ExceptionHB extends Exception {
public function __construct($branche, $code = 0, $debug = true, $gerer = false) {
if ($gerer)
parent::__construct($branche, $code);
else
{
if (is_numeric($branche))
{
switch($branche)
{
case 1:
switch($code)
{
case 0:
$message = "La planète est pleine, vous ne pouvez plus construire de batiment dessus !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de batiments.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour construire ce bâtiment.";
break;
case 3:
$message = "Le bâtiment dont vous demandez la construction est actuellement en démolition. Annulez la démolition pour lui ajouter l'aggrandir.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour construire ce bâtiment !";
break;
case 5:
$message = "Impossible d'annuler la construction de ce bâtiment, il n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démolir ce batiment, il n'est pas encore construit !";
break;
case 7:
$message = "Le bâtiment dont vous demandez la démolition est actuellement en travaux. Annulez les travaux en cours pour pouvoir le démolir.";
break;
}
break;
case 2:
switch($code)
{
case 0:
$message = "Cette technologie est déjà en file d'attente, soyez patient !";
break;
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de technologies.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour rechercher cette technologie.";
break;
case 3:
$message = "Vous possédez déjà cette technologie !";
break;
case 4:
$message = "Vous n'avez pas les crédits ou ressources nécessaires pour rechercher cette technologie !";
break;
case 5:
$message = "Impossible d'annuler la recherche de cette technologie, elle n'a pas été trouvée dans la file !";
break;
}
break;
case 3:
switch($code)
{
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus d'unités.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour entraîner ces unités.";
break;
case 3:
$message = "L'unité dont vous demandez l'entraînement est actuellement en démentellement. Annulez le démentellement pour l'entraîner de nouveau.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour entraîner cette unité !";
break;
case 5:
$message = "Impossible d'annuler l'entraînement de cette unité, elle n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Vous ne pouvez pas démenteler autant d'unités !";
break;
case 7:
$message = "L'unité dont vous demandez le démentellement est actuellement en entraînement. Annulez l'entraînement en cours pour pouvoir la démenteller.";
break;
case 8:
$message = "Dépassement de capacité.<br />Vous ne pouvez pas demander la construction d'autant d'unités en même temps.";
break;
}
break;
case 4:
switch($code)
{
case 1:
$message = "La file d'attente est pleine, vous ne pouvez pas rajouter plus de recherches.";
break;
case 2:
$message = "Vous n'avez pas les bâtiments et/ou technologies nécessaires pour rechercher cette technologie.";
break;
case 4:
$message = "Vous n'avez pas les ressources nécessaire pour rechercher cette technologie !";
break;
case 5:
$message = "Impossible d'annuler la recherche de cette technologie, elle n'a pas été trouvé dans la file !";
break;
case 6:
$message = "Il n'est pas possible d'annuler une technologie connue";
break;
case 7:
$message = "Vous recherchez déjà cette technologie !";
break;
}
break;
}
}
else
$message = $branche;
if ($debug || empty($message))
$message = "Erreur #".intval($branche)."/".$code." :<br />".$message;
global $template, $page;
if (!empty($page))
$template->assign('page', $page);
$template->assign('message', $message);
$template->assign('couleur', 'red');
$template->display('game/erreur.tpl');
exit;
}
}
}
?>

View file

@ -0,0 +1,839 @@
<?php
include_once("Class/rapport.php");
/***************************************************************************
* class.flotte.php
* ------------------
* begin : Samedi 20 septembre 2008
* update : Samedi 20 septembre 2008
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Flotte
{
var $id_flotte = 0,
$nom,
$start_planete,
$start_time,
$start_type,
$end_planete,
$end_time,
$end_type,
$ret_planete,
$ret_type,
$ret_time,
$nb_vais,
$vaisseaux = array(),
$tactique = 0,
$mission,
$vitesse,
$statut = 0,
$last,
$contenu = array(0,0,0),
$contenuMax = 0,
$modifFlotte = array();
/**
* Constructeur
* @param int $id id de la flotte à importer
* @param bool $verrou Booléen disant si la classe doit obtenir préalablement un verrou pour la flotte.
*
* @return void
* @access public
*/
function __construct($id = 0, $verrou = true)
{
if (!empty($id))
{
global $table_flottes;
global $ressoVAR, $spatialVAR;
$id = intval($id);
$bdd = new BDD();
$flotte = $bdd->unique_query("SELECT * FROM $table_flottes WHERE id = $id;");
if ($verrou)
$bdd->query("UPDATE $table_flottes SET last = ".time()." WHERE id = $id;"); //Obtention d'un vérrou de 10 seconde sur la flotte
$bdd->deconnexion();
if (!empty($flotte))
{
$this->id_flotte = $flotte["id"];
$this->nom = $flotte["nom"];
$this->start_planete = $flotte["start_planete"];
$this->start_type = $flotte["start_type"];
$this->start_time = $flotte["start_time"];
$this->end_planete = $flotte["end_planete"];
$this->end_type = $flotte["end_type"];
$this->end_time = $flotte["end_time"];
$this->ret_planete = $flotte["ret_planete"];
$this->ret_type = $flotte["ret_type"];
$this->ret_time = $flotte["ret_time"];
$this->tactique = $flotte["tactique"];
$this->mission = $flotte["mission"];
$this->vitesse = $flotte["vitesse"];
$this->statut = $flotte["statut"];
$this->last = $flotte["last"];
$this->nb_vais = $flotte["nb_vais"];
foreach($spatialVAR as $vais)
$this->vaisseaux[] = $flotte[$vais];
$this->contenu = array($flotte["contenu_metal"], $flotte["contenu_cristal"], $flotte["contenu_hydrogene"]);
$this->calculer();
}
}
}
function calculer()
{
$this->nb_vais = 0;
//Calcul de la capacité maximale d'embarquement de la flotte
foreach($this->vaisseaux as $key => $vais)
{
$this->nb_vais += $vais;
$this->contenuMax += dSpatial::tailleCales($key) * $vais;
}
}
function load_planete()
{
if (!empty($this->start_planete) && is_numeric($this->start_planete))
{
//On traite l'importation en fonction des types fournis
if ($this->start_type == 0)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "planete" && $planete->id == $this->start_planete)
$this->start_planete = $planete;
else
$this->start_planete = new Planete($this->start_planete);
}
elseif ($this->start_type == 2)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "asteroide" && $planete->id == $this->start_planete)
$this->start_planete = $planete;
else
$this->start_planete = new Asteroide($this->start_planete);
}
}
if (!empty($this->end_planete) && is_numeric($this->end_planete))
{
//On traite l'importation en fonction des types fournis
if ($this->end_type == 0 || $this->ret_type == 1)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "planete" && $planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Planete($this->end_planete);
}
elseif ($this->end_type == 2)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "asteroide" && $planete->id == $this->end_planete)
$this->end_planete = $planete;
else
$this->end_planete = new Asteroide($this->end_planete);
}
}
if (!empty($this->ret_planete) && is_numeric($this->ret_planete))
{
//On traite l'importation en fonction des types fournis
if ($this->ret_type == 0)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "planete" && $planete->id == $this->ret_planete)
$this->ret_planete = $planete;
else
$this->ret_planete = new Planete($this->ret_planete);
}
elseif ($this->ret_type == 2)
{
global $planete;
//Si la planète est la même que celle du joueur actuel, on l'utilise, sinon, on la crée
if (SURFACE == "asteroide" && $planete->id == $this->ret_planete)
$this->ret_planete = $planete;
else
$this->ret_planete = new Asteroide($this->ret_planete);
}
}
}
function creer(surface $start_planete, $tableau, $resultat)
{
$sauv = $start_planete->vaisseaux; //Sauvegarde les vaisseaux de la planète avant le lancement
foreach ($tableau['vaisseaux'] as $key => $vaisseau)
{
$this->vaisseaux[$key] = $vaisseau;
$sauv[$key] -= $vaisseau;
if ($sauv[$key] < 0)
erreur('Vous n\'avez pas assez de vaisseaux sur cette planète pour envoyer cette flotte !', "red", $VAR["menu"]["flotte"]);
}
//Définition des paramètres de la flotte en fonction des données enregistrées en session
$this->nom = $tableau["nom"];
$this->vitesse = $tableau["vitesse"];
$this->mission = $tableau["mission"];
$this->start_planete = $start_planete;
if (SURFACE == "planete")
$this->start_type = 0;
elseif (SURFACE == "asteroide")
$this->start_type = 2;
$this->start_time = time();
//On traite le cas des planètes qui n'existent pas (dans le cas de la mission colonisation)
if ($tableau["mission"] == 2)
{
//On traite le cas des colonisation d'astéroïdes
if ($tableau["end_position"] == "A")
$this->end_type = 3;
else
$this->end_type = 1;
$this->end_planete = $tableau["end_galaxie"].':'.$tableau["end_systeme"].':'.$tableau["end_position"];
}
//On traite le cas des envoie vers les alliances
elseif ($tableau["end_position"] == "A")
{
$this->end_type = 2;
$this->end_planete = $resultat['id'];
}
else
{
$this->end_type = 0;
$this->end_planete = $resultat['id'];
}
if (empty($this->end_planete))
erreur("Planète d'arriver incorrecte !");
//On vérifie qu'il y a assez de place dans les cales des vaisseaux avant l'envoie ainsi que de ressources sur la planète
$this->calculer();
$calc = Flotte::calc_deplacement($start_planete, $tableau["end_galaxie"], $tableau["end_systeme"], $tableau["end_position"], $tableau["vitesse"]/100, $tableau["vaisseaux"], $this->contenuMax - $tableau["embarquer"][0] - $tableau["embarquer"][1] - $tableau["embarquer"][2], false, true);
$this->end_time = $calc[0];
//On double la consomation si on fait un aller-retour
if ($tableau["mission"] == 1 || $tableau["mission"] == 2 || $tableau["mission"] == 4 || $tableau["mission"] == 5)
$calc[1] *= 2;
if ($this->contenuMax < $tableau["embarquer"][0] + $tableau["embarquer"][1] + $tableau["embarquer"][2] + $calc[1])
erreur('Vous ne pouvez pas embarquer autant de ressources, les cales débordent. '.$this->contenuMax, "red", '?p=flotte', 3500);
elseif ($start_planete->metal < $tableau["embarquer"][0] || $start_planete->cristal < $tableau["embarquer"][1] || $start_planete->hydrogene < $tableau["embarquer"][2] + $calc[1])
erreur('Vous n\'avez pas assez de ressources sur cette planète pour envoyer cette flotte.', "red", '?p=flotte', 3500);
$this->contenu = $tableau["embarquer"];
$this->modifFlotte = "INSERT";
//On actualise la planète
$start_planete->metal -= $tableau["embarquer"][0];
$start_planete->cristal -= $tableau["embarquer"][1];
$start_planete->hydrogene -= floor($tableau["embarquer"][2] + $calc[1]);
$start_planete->vaisseaux = $sauv;
$start_planete->addModif("vaisseaux");
$start_planete->addModif("force");
}
static function calc_deplacement($start_planete, $end_galaxie, $end_systeme, $end_position, $vitesse, $vaisseaux, $contenuDispo, $returnArray = false, $returnConso = false)
{
global $VAR;
//Calcul de la longueur du déplacement
$diff_galaxie = abs($start_planete->galaxie - $end_galaxie);
$diff_systeme = abs($start_planete->ss - $end_systeme);
$diff_position = abs($start_planete->position - $end_position);
$diff_centre_position_start = abs(ceil($VAR['nb_amas']/2) - $start_planete->position);
$diff_centre_systeme_start = abs(ceil($VAR['nb_systeme']/2) - $start_planete->ss);
$diff_centre_position_end = abs(ceil($VAR['nb_amas']/2) - $end_position);
$diff_centre_systeme_end = abs(ceil($VAR['nb_systeme']/2) - $end_systeme);
//Calcul du temps de déplacement pour chaque vaisseau
$temps = array(); $conso = array(0, 0, 0);
foreach($vaisseaux as $key => $vais)
{
//S'il n'y a pas de vaisseaux de ce type, on ne calcul pas leur vitesse
if ($vais == 0)
continue;
//Calcul du temps de déplacement entre planètes
if ($start_planete->ss == $end_systeme && $start_planete->galaxie == $end_galaxie)
{
$temps[0][$key] = (1000/dSpatial::vitesseP($key)) * (1 + 0.1 * $diff_position);
$temps[1][$key] = $temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre système
elseif ($start_planete->galaxie == $end_galaxie)
{
$temps[0][$key] = (1000/dSpatial::vitesseP($key)) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (2000/dSpatial::vitesseS($key)) * (2 + 1 * $diff_systeme);
$temps[2][$key] = 0;
}
//Calcul du temps de déplacement entre galaxies
else
{
$temps[0][$key] = (1000/dSpatial::vitesseP($key)) * (1 + 0.1 * ($diff_centre_position_start + $diff_centre_position_end));
$temps[1][$key] = (2000/dSpatial::vitesseS($key)) * (2 + 1 * ($diff_centre_systeme_start + $diff_centre_systeme_end));
$temps[2][$key] = (5000/dSpatial::vitesseG($key)) * (2 + 1.5 * $diff_galaxie);
}
//Calcul du bonus pour le réacteur à combustion
$techR = $start_planete->technologies[1];
if ($techR & 56)
$bonus = 0.7;
elseif ($techR & 24)
$bonus = 0.8;
elseif ($techR & 8)
$bonus = 0.9;
else
$bonus = 1;
$temps[0][$key] *= $bonus * 1/$vitesse;
$conso[0] += $vais * $temps[0][$key] * $bonus / exp($vitesse/5);
//Calcul du bonus pour le réacteur à fusion
$techR = $start_planete->technologies[1];
if ($techR &448)
$bonus = 0.7;
elseif ($techR &192)
$bonus = 0.8;
elseif ($techR &64)
$bonus = 0.9;
else
$bonus = 1;
$temps[1][$key] *= $bonus * 1/$vitesse;
$conso[1] += $vais * $temps[1][$key] * $bonus / exp($vitesse/7.5);
//Calcul du bonus pour le réacteur à fusion de type II
$techR = $start_planete->technologies[1];
if ($techR &3584)
$bonus = 0.7;
elseif ($techR &1536)
$bonus = 0.8;
elseif ($techR &512)
$bonus = 0.9;
else
$bonus = 1;
$temps[2][$key] *= $bonus * 1/$vitesse;
$conso[2] += $vais * $temps[2][$key] * $bonus / exp($vitesse/10);
}
if (!isset($vaisseaux[4]))
$vaisseaux[4] = 0;
if (!isset($vaisseaux[5]))
$vaisseaux[5] = 0;
//Si les chasseurs peuvent rentrer dans les cales des vaisseaux, on les enlèves
if ($contenuDispo - ceil($conso[0]+$conso[1]+$conso[2]) - ($vaisseaux[4] * dSpatial::tailleCales(4) + $vaisseaux[5] * dSpatial::tailleCales(5)) >= ($vaisseaux[4] + $vaisseaux[5]) * 200)
$temps[2][4] = $temps[2][5] = $temps[1][4] = $temps[1][5] = $temps[0][4] = $temps[0][5] = 0;
//On calcul le temps de déplacement maximal
if ($returnArray)
return $temps;
elseif ($returnConso)
return array(max($temps[0]) + max($temps[1]) + max($temps[2]), ceil($conso[0]+$conso[1]+$conso[2]));
else
return (max($temps[0]) + max($temps[1]) + max($temps[2]));
}
function check_mission()
{
//On vérifie qu'un calcul ne soit pas déjà en cours
if ($this->last >= time() - 10)
return false;
elseif ($this->start_time + $this->end_time > time())
return false;
if ($this->statut == 0)
{
switch($this->mission)
{
case 6:
case 7:
$this->stationner();
break;
case 1:
$this->transporter();
break;
case 2:
$this->coloniser();
break;
case 3:
$this->attaquer();
break;
case 4:
$this->recycler();
break;
case 5:
$this->espionner();
break;
}
}
if ($this->statut == 1 && ($this->ret_time > time() || $this->start_time + $this->end_time * 2 <= time()))
$this->retourner();
return true;
}
function stationner()
{
//On décharge les ressources éventuellement contenue
$this->decharger();
//On fait atterir les vaisseaux
foreach ($this->vaisseaux as $key => $vais)
$this->end_planete->vaisseaux[$key] += $vais;
if (!in_array("vaisseaux", $this->end_planete->modif))
$this->end_planete->modif[] = "vaisseaux";
$this->modifFlotte = "DELETE";
}
function transporter()
{
$max = $this->decharger();
//Envoie du MP de confirmation au joueur
$send = new Rapport(2, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$send->addInfo($this->end_planete, 0);
$send->addInfo($max, 1);
$send->sendTransport();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function coloniser()
{
//On vérifie que les coordonnées de la planètes sont bien enregistrée
if (empty($this->end_planete) || is_object($this->end_planete) || !preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([A0-9]{1,2})\]?$#', $this->end_planete))
{
$this->load_planete();
file_log("Erreur de colonisation de la planète : ".$this->end_planete." pour le joueur : ".$this->start_planete->id_user, 2);
send_mp($this->start_planete->id_user, "Erreur de colonisation [F#01]", "Une erreur s'est produite lors de la tentative de colonisation de votre flotte, elle a fait demi-tour.", $this->start_time + $this->end_time);
$this->rappeler();
}
//On vérifie que la planète ne soit pas déjà colonisée
global $table_planete, $table_alliances, $table_alliances_creation, $table_user;
preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([A0-9]{1,2})\]?$#', $this->end_planete, $position);
if (is_numeric($position[3]))
{
$bdd = new BDD();
$p = $bdd->query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
{
$bdd = new BDD();
$p = $bdd->query("SELECT * FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$alliance = $bdd->unique_query("SELECT signatures FROM $table_alliances_creation WHERE fondateur = ".$this->start_planete->id_user.";");
$signaturesExport = implode(' OR id = ', explode(';', substr($alliance["signatures"], 1), -1));
$bdd->deconnexion();
}
$this->load_planete();
if ($p && (!isset($signaturesExport) || count($signaturesExport) < nb_signatures))
{
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(false, 1);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
else
{
if (is_numeric($position[3]))
{
//On crée la planète
$this->end_planete = new Planete(false);
$this->end_planete->galaxie = $position[1];
$this->end_planete->ss = $position[2];
$this->end_planete->position = $position[3];
$this->end_planete->creer($this->start_planete->id_user);
//On définit la limite de ressources pour permettre le déchargement de celles contenues dans les vaisseaux
$this->end_planete->cap = 100000;
}
else
{
//On crée l'astéroide
$this->end_planete = new Asteroide(false);
$this->end_planete->galaxie = $position[1];
$this->end_planete->ss = $position[2];
$this->end_planete->creer($this->start_planete);
}
//Rembousement du carburant non utilisé (la colonisation prévois au départ un allé/retour)
$conso = $this->calc_deplacement($this->start_planete, $position[1], $position[2], $position[3], $this->vitesse, $this->vaisseaux, 0, false, true);
$this->end_planete->hydrogene += $conso[1];
//On enlève un vaisseau de colonisation de la liste
$this->vaisseaux[2]--;
//On fait atterir les vaisseaux et décharger les ressources
$this->decharger();
$this->atterir();
//On envoie un rapport
$rapport = new Rapport(2, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo(array($position[1], $position[2], $position[3]), 0);
$rapport->addInfo(true, 1);
$rapport->send();
if (!is_numeric($position[3]))
{
unset($this->end_planete);
$bdd = new BDD();
$p = $bdd->unique_query("SELECT id FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND fondateur = ".$this->start_planete->id_user.";");
print "UPDATE $table_user SET alliance = '".$p['id']."' WHERE id = $signaturesExport OR id = ".$this->start_planete->id_user.";";
$bdd->query("UPDATE $table_user SET id_alliance = '".$p['id']."' WHERE id = $signaturesExport OR id = ".$this->start_planete->id_user.";");
$bdd->deconnexion();
}
}
}
function recycler()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
$coeff = ($this->contenuMax - $this->contenu[0] - $this->contenu[1] - $this->contenu[2])/($this->end_planete->debris_met + $this->end_planete->debris_cri);
if ($coeff > 1)
$coeff = 1;
$a = floor($this->end_planete->debris_met * $coeff);
$b = floor($this->end_planete->debris_cri * $coeff);
$this->contenu[0] += $a;
$this->contenu[1] += $b;
if (!in_array('contenu', $this->modifFlotte))
$this->modifFlotte[] = 'contenu';
$this->end_planete->debris_met -= $a;
$this->end_planete->debris_cri -= $b;
if (!in_array('debris_met', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_met';
if (!in_array('debris_cri', $this->end_planete->modif))
$this->end_planete->modif[] = 'debris_cri';
//Send link
$rapport = new Rapport(4, $this->start_planete, 0, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo(array($a, $b), 1);
$rapport->send();
$this->statut = 1;
if (!in_array('statut', $this->modifFlotte))
$this->modifFlotte[] = 'statut';
}
function espionner()
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->end_planete))
$this->load_planete();
//Extraction des niveaux technologique des deux adversaires
if (($this->start_planete->technologies[1]& 67108864) == 67108864)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 33554432) == 33554432)
$espionnage_A = 3;
elseif (($this->start_planete->technologies[1]& 16777216) == 16777216)
$espionnage_A = 3;
else
$espionnage_A = 0;
if (($this->start_planete->technologies[1]& 536870912) == 536870912)
$contreespionnage_B = 3;
elseif (($this->start_planete->technologies[1]& 268435456) == 268435456)
$contreespionnage_B = 2;
elseif (($this->start_planete->technologies[1]& 134217728) == 134217728)
$contreespionnage_B = 1;
else
$contreespionnage_B = 0;
//Création du rapport
$rapport = new Rapport(5, $this->start_planete, $this->end_planete, $this->start_time + $this->end_time);
$rapport->addInfo($this->end_planete, 0);
$rapport->addInfo($contreespionnage_B/$espionnage_A/10, 1);
$rapport->addInfo($espionnage_A+2-$contreespionnage_B+1, 2);
$rapport->addInfo($contreespionnage_B, 3);
$rapport->send();
$this->statut = 1;
$this->addModifFlotte("statut");
}
function decharger($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
$max = array(0, 0, 0);
//Si on dépasse les capacités, on laisse les ressources en trop dans le cargo
if ($this->$plan->metal + $this->contenu[0] > $this->$plan->cap)
{
$max[0] = $this->$plan->cap - $this->$plan->metal;
if ($max[0] < 0) $max[0] = 0;
}
else
$max[0] = $this->contenu[0];
$this->$plan->metal += $max[0];
$this->contenu[0] -= $max[0];
if ($this->$plan->cristal + $this->contenu[1] > $this->$plan->cap)
{
$max[1] = $this->$plan->cap - $this->$plan->cristal;
if ($max[1] < 0) $max[1] = 0;
}
else
$max[1] = $this->contenu[1];
$this->$plan->cristal += $max[1];
$this->contenu[1] -= $max[1];
if ($this->$plan->hydrogene + $this->contenu[2] > $this->$plan->cap)
{
$max[2] = $this->$plan->cap - $this->$plan->hydrogene;
if ($max[2] < 0) $max[2] = 0;
}
else
$max[2] = $this->contenu[2];
$this->$plan->hydrogene += $max[2];
$this->contenu[2] -= $max[2];
$this->$plan->addModif("force");
$this->addModifFlotte("contenu");
return $max;
}
function atterir($plan = "end_planete")
{
//Si la planète d'arrivé n'est pas chargée, on charge les planètes
if (is_numeric($this->$plan))
$this->load_planete();
if (isset($this->$plan->vaisseaux[0]))
{
foreach ($this->vaisseaux as $key => $vais)
$this->$plan->vaisseaux[$key] += $vais;
}
else
$this->$plan->vaisseaux = $this->vaisseaux;
$this->$plan->addModif("vaisseaux");
$this->modifFlotte = "DELETE";
}
function rappeler()
{
if ($this->start_time + $this->end_time >= time())
return false;
else
{
$this->end_time = time() - $this->start_time + 10;
$this->mission = 5;
if (!in_array('mission', $this->modifFlotte))
$this->modifFlotte[] = 'mission';
if (!in_array('end_time', $this->modifFlotte))
$this->modifFlotte[] = 'end_time';
return true;
}
}
function retourner()
{
//Si la planète de départ n'est pas chargée, on charge les planètes
if (is_numeric($this->start_planete))
$this->load_planete();
//Si on a demandé une planète particulière au retour
if (!empty($this->ret_time) && !empty($this->ret_planete) && !is_numeric($this->ret_planete))
{
$this->decharger("ret_planete");
$this->atterir("ret_planete");
}
//Si le retour se fait sur la planète source
else
{
$this->decharger("start_planete");
$this->atterir("start_planete");
}
$this->modifFlotte = "DELETE";
}
function addModifFlotte($modif)
{
if (!in_array($modif, $this->modifFlotte))
$this->modifFlotte[] = $modif;
}
function printTime_end()
{
return $this->start_time + $this->end_time;
}
function printTime_ret()
{
if (!empty($this->ret_time))
return $this->ret_time;
elseif ($this->mission == 1 || $this->mission == 4 || $this->mission == 5 || (($this->mission == 3 || $this->mission == 2) && $this->statut != 0))
return $this->start_time + $this->end_time*2;
else
return 0;
}
static function txtMission($mission)
{
switch($mission)
{
case 1:
return "Transporter";
break;
case 2:
return "Coloniser";
break;
case 3:
return "Attaquer";
break;
case 4:
return "Recycler";
break;
case 5:
return "Espionner";
break;
case 6:
case 7:
return "Stationner";
break;
default:
return "Inconnu";
break;
}
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
global $table_flottes;
if ($this->modifFlotte === "DELETE")
{
$bdd = new BDD();
$bdd->query("DELETE FROM $table_flottes WHERE id = ".$this->id_flotte.";");
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : suppr ID = ".$this->id_flotte, 2);
$bdd->deconnexion();
}
else
{
if (empty($this->id_flotte) && $this->modifFlotte == "INSERT")
{
$out1 = ''; $out2 = '';
global $spatialVAR;
foreach ($this->vaisseaux as $key => $vais)
{
if ($vais > 0)
{
$out1 .= ', '.$spatialVAR[$key];
$out2 .= ', '.$vais;
}
}
if (SURFACE == "asteroide")
$sql = "INSERT INTO $table_flottes (id_user, id_alliance, mission, start_time, start_type, start_planete, end_time, end_type, end_planete, vitesse, contenu_metal, contenu_cristal, contenu_hydrogene, tactique, nom, nb_vais$out1) VALUES (0, ".$this->start_planete->id.", '".$this->mission."', '".$this->start_time."', '".$this->start_type."', '".$this->start_planete->id."', '".$this->end_time."', '".$this->end_type."', '".$this->end_planete."', '".$this->vitesse."', '".$this->contenu[0]."', '".$this->contenu[1]."', '".$this->contenu[2]."', '".$this->tactique."', '".$this->nom."', ".$this->nb_vais."$out2);";
else
$sql = "INSERT INTO $table_flottes (id_user, mission, start_time, start_type, start_planete, end_time, end_type, end_planete, vitesse, contenu_metal, contenu_cristal, contenu_hydrogene, tactique, nom, nb_vais$out1) VALUES ('".$this->start_planete->id_user."', '".$this->mission."', '".$this->start_time."', '".$this->start_type."', '".$this->start_planete->id."', '".$this->end_time."', '".$this->end_type."', '".$this->end_planete."', '".$this->vitesse."', '".$this->contenu[0]."', '".$this->contenu[1]."', '".$this->contenu[2]."', '".$this->tactique."', '".$this->nom."', ".$this->nb_vais."$out2);";
if (DEBUG) echo $sql;
$bdd = new BDD();
$bdd->query($sql);
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : insertion flotte", 2);
$bdd->deconnexion();
}
elseif(isset($this->modifFlotte[0]))
{
$out = array();
$bdd = new BDD();
foreach($this->modifFlotte as $modif)
{
if (!is_array($this->{$modif}))
{
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] .= $modif." = ".$this->{$modif};
else
{
$bdd->escape($this->{$modif});
$out[] .= $modif." = '".$this->{$modif}."'";
}
}
else
{
if ($modif == "contenu")
$calc = "resso";
elseif ($modif == "vaisseaux")
$calc = "nomvaisn";
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach(${$calc.'VAR'} as $key => $var)
{
$bdd->escape($this->{$modif}[$key]);
$out[] = ${$calc.'VAR'}[$key]." = ".$this->{$modif}[$key];
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_flottes SET ".implode(', ', $out).", last = 0 WHERE id = ".$this->id_flotte.";";
if (DEBUG)
var_dump($sql);
$bdd->query($sql);
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out)." avec l'ID : ".$this->id_flotte, 2);
}
$bdd->deconnexion();
}
}
}
}
?>

View file

@ -0,0 +1,36 @@
<?php
/**
*
*
*/
class Groupe
{
var $contenu = array(); //Tableau contenant les vaisseaux de l'utilisateur
var $caracteristiques = array();
var $example = array(
array("somme boucliers", "somme pv", "nbVaisseauxInitiaux")
);
var $user; //Classe donnant des informations sur l'utilisateur de la flotte ou l'ID de l'utilisateur
var $camp = 0; //Camp du groupe
var $timestamp = 0; //TImestamp de la dernière attaque
var $actions = array(); //Tableau des actions faite ou à faire
var $action_encours = 0;
/**
* Constructor
*/
function __construct()
{
}
function regenereBoucliers()
{
foreach ($this->caracteristiques as $caracteristique)
{
if ($this->actions[$action_encours][0] == 2)
$
}
}
}
?>

View file

@ -0,0 +1,23 @@
<?php
/**
* PHPMailer language file.
* English Version
*/
$PHPMAILER_LANG = array();
$PHPMAILER_LANG["provide_address"] = 'You must provide at least one ' .
'recipient email address.';
$PHPMAILER_LANG["mailer_not_supported"] = ' mailer is not supported.';
$PHPMAILER_LANG["execute"] = 'Could not execute: ';
$PHPMAILER_LANG["instantiate"] = 'Could not instantiate mail function.';
$PHPMAILER_LANG["authenticate"] = 'SMTP Error: Could not authenticate.';
$PHPMAILER_LANG["from_failed"] = 'The following From address failed: ';
$PHPMAILER_LANG["recipients_failed"] = 'Erreur SMTP: The following ' .
'recipients failed: ';
$PHPMAILER_LANG["data_not_accepted"] = 'Erreur SMTP: Données non acceptées.';
$PHPMAILER_LANG["connect_host"] = 'Erreur SMTP: Impossible de se connecter au serveur de mail.';
$PHPMAILER_LANG["file_access"] = 'Accès au fichier impossible: ';
$PHPMAILER_LANG["file_open"] = 'File Error: Ne peut ouvrir le fichier: ';
$PHPMAILER_LANG["encoding"] = 'Type d\'encodage inconnu : ';
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,878 @@
<?php
//Gestion des dépendances, on importe les classes nécessaires à la classe en cours
include_once("Class/surface.php");
include_once("donnees.php");
/***************************************************************************
* class.planete.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class Planete extends Surface
{
private $timestamp_lastSilo,
$timestamp_lastMineM,
$timestamp_lastMineC,
$timestamp_lastMineH;
public $position,
$nom_planete,
$cases,
$casesRest,
$cap,
$population,
$population_max,
$moral,
$energie,
$energieConso,
$energieCentrale,
$file_tech,
$file_cas,
$file_ter,
$coeff_bat = array(),
$casernes = array(),
$terrestres = array();
/**
* Constructeur
* @param mixed $id id de la planète à importer/coordonnées
* @param bool $first Bloquer l'affichage des messages d'erreurs
*
* @return void
* @access public
*/
function __construct($id, $first = false)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new BDD();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if ($id === false)
$bdd->deconnexion();
elseif (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT * FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
parent::User($plan["id_user"]);
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
if (!empty($plan["isolement"])) $this->isolement = unserialize($plan["isolement"]);
else $this->isolement = array();
$this->nom_planete = $plan["nom_planete"];
$this->image = $plan["image"];
$this->cases = $plan["cases"];
$this->energieCentrale = $plan["energieCentrale"];
$this->debris_met = $plan["debris_met"];
$this->debris_cri = $plan["debris_cri"];
$this->metal = $plan["metal"];
$this->cristal = $plan["cristal"];
$this->hydrogene = $plan["hydrogene"];
$this->population = $plan["population"];
$this->moral = $plan["moral"];
$this->timestamp = $plan["timestamp"];
//Chargement des variables de conversion
global $batimentsVAR, $caserneVAR, $terrestreVAR, $spatialVAR;
$this->casesRest = $this->cases; //Calcul du nombre de cases en même temps
foreach($batimentsVAR as $bat)
{
$this->batiments[] = $plan[$bat];
$this->casesRest -= $plan[$bat];
}
if (!empty($plan["file_bat"]))
$this->file_bat = unserialize($plan["file_bat"]);
else
$this->file_bat = new FileBatiments();
$this->coeff_bat = array($plan["coeff_mine_m"], $plan["coeff_mine_c"], $plan["coeff_mine_h"], $plan["coeff_centrale_s"], $plan["coeff_centrale_f"]);
//On vérifie que les coefficient ne soient pas supérieurs à 1 ou inférieurs à 0
for($i = 0; $i < 5; $i++)
{
if ($this->coeff_bat[$i] > 1)
$this->coeff_bat[$i] = 1;
elseif ($this->coeff_bat[$i] < 0)
$this->coeff_bat[$i] = 0;
}
if (!empty($plan["file_tech"]))
$this->file_tech = unserialize($plan["file_tech"]);
else
$this->file_tech = new FileTechnologies();
foreach($caserneVAR as $cas)
$this->casernes[] = $plan[$cas];
if (!empty($plan["file_cas"]))
$this->file_cas = unserialize($plan["file_cas"]);
else
$this->file_cas = new FileCaserne();
foreach($terrestreVAR as $ter)
$this->terrestres[] = $plan[$ter];
if (!empty($plan["file_ter"]))
$this->file_ter = unserialize($plan["file_ter"]);
else
$this->file_ter = new FileTerrestre();
foreach($spatialVAR as $vais)
$this->vaisseaux[] = $plan[$vais];
if (!empty($plan["file_vais"]))
$this->file_vais = unserialize($plan["file_vais"]);
else
$this->file_vais = new FileSpatial();
//Calcul de la population logée
$this->population_max = (pow($this->batiments[12],1.5)+pow($this->batiments[13],2.1))*1000+3000;
//Détermination des capacités maximales
$this->cap = pow(2, $this->batiments[10]) * 100000;
}
}
/**
* Actualise les ressources de la planète en fonction de la production et termine les files d'attentes.
*
* @return void
* @access public
*/
function actualiser($actuFile = true, $first = false)
{
//Actualisation des files d'attentes
if ($actuFile)
{
$this->file_bat->ready($this);
$this->file_tech->ready($this);
$this->file_cas->ready($this);
$this->file_ter->ready($this);
$this->file_vais->ready($this);
}
if (!empty($this->timestamp_lastSilo))
{
$this->cap = pow(2, $this->batiments[10]-1) * 100000;
$capnouv = pow(2, $this->batiments[10]) * 100000;
$this->addModif("force");
}
//Calcul du temps écoulé depuis la dernière mise à jour de la planète
$temps_ecoule = time() - $this->timestamp;
$ressources = $this->production($temps_ecoule);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->metal + $ressources[0] < $this->cap)
$this->metal += $ressources[0];
else
$this->metal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->metal + $ressources[0] < $capnouv)
$this->metal += $ressources[0];
else
{
$this->alert_ressources[0] = true;
$this->metal = $capnouv;
}
}
else
{
$this->alert_ressources[0] = true;
$this->metal = $this->cap;
}
}
if ($this->cristal + $ressources[1] < $this->cap)
$this->cristal += $ressources[1];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->cristal + $ressources[0] < $this->cap)
$this->cristal += $ressources[0];
else
$this->cristal = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->cristal + $ressources[0] < $capnouv)
$this->cristal += $ressources[0];
else
{
$this->alert_ressources[1] = true;
$this->cristal = $capnouv;
}
}
else
{
$this->alert_ressources[1] = true;
$this->cristal = $this->cap;
}
}
if ($this->hydrogene + $ressources[2] < $this->cap)
$this->hydrogene += $ressources[2];
else
{
//Si les capacités de stockage ont changé depuis la dernière actualisation
if (isset($capnouv))
{
$ressources = $this->production($this->timestamp_lastSilo - $this->timestamp);
if ($this->hydrogene + $ressources[0] < $this->cap)
$this->hydrogene += $ressources[0];
else
$this->hydrogene = $this->cap;
$ressources = $this->production(time() - $this->timestamp_lastSilo);
if ($this->hydrogene + $ressources[0] < $capnouv)
$this->hydrogene += $ressources[0];
else
{
$this->alert_ressources[2] = true;
$this->hydrogene = $capnouv;
}
}
else
{
$this->alert_ressources[2] = true;
$this->hydrogene = $this->cap;
}
}
//Vérification de la date pour faire les actions journalières
if (date('zya') != date('zya', $this->timestamp)) //Mise à jour trois fois par jour : 0h, 1h, 13h
//if (date('zy') != date('zy', $this->timestamp)) //Mise à jour une fois par jour : 0h
{
//On évalue le moral
$this->evalMoral($first);
//Si la population est à 0, on ajoute des habitants
if ($this->population <= 0)
$this->population = 1000;
$popPlus = $this->population * 0.0153^max(1, floor((time()-$this->timestamp)/86400));
if ($this->politique == 2)
$popPlus *= 1.1; //Communisme : 10 % de population qui arrive en plus.
elseif ($this->politique == 3)
$popPlus *= 1.05; //Démocratie : 5 % de population qui arrive en plus.
if ($this->technologies[2] & 4)
$popPlus *= 1.15;
elseif ($this->technologies[2] & 2)
$popPlus *= 1.10;
elseif ($this->technologies[2] & 1)
$popPlus *= 1.05;
$this->population += $popPlus;
$this->addCredits(($this->population/100*exp(0.01)*25) + ($this->population*0.01*$this->batiments[15])); //Première partie : production normale; seconde : batiment commercial
$this->addModif("population");
}
$this->timestamp = time();
}
function setMoral($difference)
{
$this->moral += $difference;
//Ajustement du moral
if ($this->moral > 1)
$this->moral = 1;
elseif ($this->moral < 0)
$this->moral = 0;
$this->addModif("moral");
}
function evalMoral($first = false)
{
$evolution = array();
//Cas de sous-production
if (($this->coeff_bat[0] + $this->coeff_bat[1] + $this->coeff_bat[2])/3 < 0.9)
{
if ($this->politique == 2)
$this->moral -= 0.10; //Communisme : démoralise 2x plus
else
$this->moral -= 0.05;
$this->addModif("moral");
}
//Surpopulation
//Surlogement
//Effets des batiments loisirs et commerces
$this->moral += 0.0025*$this->batiments[15] + 0.1*$this->batiments[16];
//Ajustement du moral en fonction de la politique
if ($this->politique == 1 && $this->moral > 0.7)
$this->moral = 0.7;
//On vérifie qu'on ne dépasse pas le maximum
if ($this->moral > 1)
$this->moral = 1;
if ($this->moral < 0)
$this->moral = 0;
//Isolement si besoin
if ($this->moral < 0.1)
{
//On vérifie qu'il ne s'agit pas de la planète mère
global $table_planete;
$bdd = new Bdd();
$bdd->reconnexion();
$res = $bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = ".$this->id_user." ORDER BY id LIMIT 1;");
$bdd->deconnexion();
if ($res['id'] != $this->id)
{
if ($this->moral <= 0.04)
{
if ($this->moral <= 0.01)
$rand = rand(0,4);
else
$rand = rand(0,20);
//Perte de la planète
if ($rand == 1)
{
$bdd->reconnexion();
$bdd->query("DELETE FROM $table_planete WHERE id = ".$this->id.";");
$bdd->deconnexion();
send_mp($this->id_user, 'Perte de contrôle de '.$this->nom_planete, "Suite à une démoralisation persistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a renversé votre gouvernement en tuant tous vos gouverneurs. Vous perdez donc définitivement le contrôle de cette planète.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révolté contre vous. Vous ne contrôlez plus cette planète.');
}
}
}
elseif ($this->moral <= 0.1)
{
if ($this->moral <= 0.06)
$rand = rand(0,2);
else
$rand = rand(0,10);
//Perte de contrôle temporaire
if ($rand == 1)
{
$debut = time() - rand(0, 3600)*4;
$fin = $debut + 86400;
$this->isolement = array($debut, $fin);
$this->addModif("isolement");
send_mp($this->id_user, 'Perte de contrôle temporaire de '.$this->nom_planete, "Suite à une démoralisation percistante de la population sur la planète ".$this->nom_planete." [".$this->galaxie.":".$this->ss.":".$this->position."], la population a pris le contrôle de votre planète. Vous perdez le contrôle de cette planète le temps que vos gouverneurs reprennent le pouvoir.");
if (!$first)
{
$sess->values['idPlan'] = $res['id'];
erreur('La population de cette planète est tellement démoralisée qu\'elle s\'est révoltée contre vous. Vous perdez temporairement le contrôle de cette planète.');
}
}
}
}
}
}
function checkAndRetireRessources($metal, $cristal, $hydrogene, $credits)
{
if ($this->metal >= $metal && $this->cristal >= $cristal && $this->hydrogene >= $hydrogene && $this->credits >= $credits)
{
$this->metal -= $metal;
$this->cristal -= $cristal;
$this->hydrogene -= $hydrogene;
if (!empty($credits))
{
$this->credits -= $credits;
$this->addModifUser("credits");
}
return true;
}
else
return false;
}
function addRessources($metal, $cristal, $hydrogene, $credits = 0)
{
$perte = 0;
$this->metal += $metal;
if ($this->metal > $this->cap)
{
$perte += $this->metal - $this->cap;
$this->metal = $this->cap;
}
$this->cristal += $cristal;
if ($this->cristal > $this->cap)
{
$perte += $this->cristal - $this->cap;
$this->cristal = $this->cap;
}
$this->hydrogene += $hydrogene;
if ($this->hydrogene > $this->cap)
{
$perte += $this->hydrogene - $this->cap;
$this->hydrogene = $this->cap;
}
if (!empty($credits))
{
$this->credits += $credits;
$this->addModifUser("credits");
}
return $perte;
}
/**
* Vérifie si la planète est isolée ou non
*
* @return boolean
* @access public
*/
function isolement()
{
$return = false;
global $queryPlanetes;
//Détermination du numéro de la planète par rapport aux autres, dans l'ordre de colonisation
$numP = 0;
foreach ($queryPlanetes as $key => $p)
{
if ($p['id'] == $this->id)
$numP = $key + 1;
}
if ($numP >= 11)
{
if (!isset($this->isolement[0]) || (time() > $this->isolement[0] && (!isset($this->isolement[1]) || (time() > $this->isolement[1] && date('dmY') != date('dmY', $this->isolement[0])))))
{
switch($numP)
{
case 11:
$tps = 2;
break;
case 12:
$tps = 4;
break;
case 13:
$tps = 6;
break;
case 14:
$tps = 8;
break;
case 15:
$tps = 12;
break;
case 16:
$tps = 16;
break;
case 17:
$tps = 20;
break;
default:
$tps = 24;
}
$debut = mktime(rand(0, 24-$tps), 0, 0, date('n'), date('j'), date('Y'));
$fin = $debut + $tps * 3600;
$this->isolement[0] = $debut;
if (time() > $this->isolement[0])
$this->isolement[1] = $fin;
$this->addModif("isolement");
}
if (isset($this->isolement[1]) && time() < $this->isolement[1])
$return = true;
}
elseif (!isset($this->isolement[0]))
{
$this->isolement = array(0,0);
$this->addModif("isolement");
}
return $return;
}
/**
* Calcul les ressources produites en fonction de $temps_ecoule
* @param int $temps_ecoule Temps écoulé depuis la dernière actualisation
*
* @return array
* @access public
*/
function production($temps_ecoule, $retarray = false)
{
//Accélération de la production
$temps_ecoule *= VITESSE;
//Si l'on est en auto contrôle des mines, on fixe le rendement de la centrale solaire à 1
if ($this->options& 8)
{
$this->coeff_bat[3] = 1;
$this->coeff_bat[4] = 1;
}
//Calcul de la consomation d'énergie
if ($this->batiments[0] > 0)
$energie_m = ceil(exp(0.28*$this->batiments[0])*10);
else
$energie_m = 0;
if ($this->batiments[1] > 0)
$energie_c = ceil(exp(0.28*$this->batiments[1])*10);
else
$energie_c = 0;
if ($this->batiments[2] > 0)
$energie_h = ceil(exp(0.2849*$this->batiments[2])*13);
else
$energie_h = 0;
if ($this->batiments[3] > 0)
$energie_s = ceil(exp(0.28*$this->batiments[3])*22);
else
$energie_s = 0;
$energie_f = 100 + $this->energieCentrale;
//Calcul de la consomation d'énergie
$this->energieConso = $energie_m * $this->coeff_bat[0] + $energie_c * $this->coeff_bat[1] + $energie_h * $this->coeff_bat[2];
$nrjmx = $energie_m + $energie_c + $energie_h;
//Calcul de la production d'énergie
$this->energie = $energie_s * $this->coeff_bat[3] + $energie_f * $this->coeff_bat[4];
if ($this->energieConso == 0)
$coeff = 0;
else
$coeff = $this->energie / $this->energieConso;
if ($coeff < 0)
$coeff = 0;
elseif ($coeff > 1 && !($this->options& 8))
$coeff = 1;
$Ncoeff = array();
for($i = 0; $i < 3; $i++)
{
$Ncoeff[$i] = $coeff * $this->coeff_bat[$i];
if ($Ncoeff[$i] > 1)
$Ncoeff[$i] = 1;
if ($Ncoeff[$i] < $this->coeff_bat[$i] || ($Ncoeff[$i] > $this->coeff_bat[$i] && $this->options& 16) && $this->batiments[$i] != 0)
{
$this->coeff_bat[$i] = $Ncoeff[$i];
$this->addModif("coeff_bat");
}
}
//Calcul de la consomation d'hydrogène
//if ($this->batiments[4] > 0)
// $conso_h = ((ceil(pow(1.34,($this->batiments[4]-1))*9)/3600)*$temps_ecoule) * $this->coeff_bat[4];
//else
$conso_h = 0;
//Calcul des production de ressources
if ($this->batiments[0] <= 0 || $this->batiments[3] <= 0)
$prod_met = 0.011 * $temps_ecoule;
else
$prod_met = ((ceil(pow(1.1, $this->batiments[0]) * 52 * $this->batiments[0]) / 3600) * $temps_ecoule) * $this->coeff_bat[0];
if ($this->batiments[1] <= 0 || $this->batiments[3] <= 0)
$prod_cri = 0.0055 * $temps_ecoule;
else
$prod_cri = ((ceil(pow(1.1, $this->batiments[1]) * 34 * $this->batiments[1]) / 3600) * $temps_ecoule) * $this->coeff_bat[1];
if ($this->batiments[2] <= 0)
$prod_hy = 0;
else
$prod_hy = ((ceil(pow(1.1, $this->batiments[2]) * 21 * ($this->batiments[2] + 0.7)) / 3600) * $temps_ecoule) * $this->coeff_bat[2];
$this->coeff_bat[3] = 1;
//Augmentation de la production en fonction des technologies
if ($this->technologies[0] &4)
{
$prod_met *= 1.15;
$prod_cri *= 1.15;
$prod_hy *= 1.15;
}
elseif ($this->technologies[0] &2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
elseif ($this->technologies[0] &1)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
//Rendement métal
if ($this->technologies[0] &64)
$prod_met *= 1.3;
elseif ($this->technologies[0] &32)
$prod_met *= 1.2;
elseif ($this->technologies[0] &16)
$prod_met *= 1.1;
//Rendemant cristal
if ($this->technologies[0] &512)
$prod_cri *= 1.3;
elseif ($this->technologies[0] &256)
$prod_cri *= 1.2;
elseif ($this->technologies[0] &128)
$prod_cri *= 1.1;
//Rendement hydrogène
if ($this->technologies[0] &4096)
$prod_hy *= 1.3;
elseif ($this->technologies[0] &2048)
$prod_hy *= 1.2;
elseif ($this->technologies[0] &1024)
$prod_hy *= 1.1;
//Augmentation de la production en fonction du moral
if ($this->moral > 0.9)
{
$prod_met *= 1.05;
$prod_cri *= 1.05;
$prod_hy *= 1.05;
}
elseif ($this->moral > 0.75)
{
$prod_met *= 1.02;
$prod_cri *= 1.02;
$prod_hy *= 1.02;
}
elseif ($this->moral < 0.45)
{
$prod_met *= 0.97;
$prod_cri *= 0.97;
$prod_hy *= 0.97;
}
elseif ($this->moral < 0.25)
{
$prod_met *= 0.94;
$prod_cri *= 0.94;
$prod_hy *= 0.94;
}
//Augmentation de la production en fonction de la politique
if ($this->politique == 2)
{
$prod_met *= 1.10;
$prod_cri *= 1.10;
$prod_hy *= 1.10;
}
//On enlève la consomation d'hydrogène
$prod_hy -= $conso_h;
if ($retarray)
return array(array(ceil($this->coeff_bat[0]*100), ceil($this->coeff_bat[1]*100), ceil($this->coeff_bat[2]*100), ceil($this->coeff_bat[3]*100), ceil($this->coeff_bat[4]*100)), array($prod_met, $prod_cri, $prod_hy + $conso_h, $energie_s*$this->coeff_bat[3], $energie_f*$this->coeff_bat[4]), array($energie_m*$this->coeff_bat[0], $energie_c*$this->coeff_bat[1], $energie_h*$this->coeff_bat[2], $conso_h, ($energie_s*$this->coeff_bat[3] + $energie_f*$this->coeff_bat[4])-($energie_m*$this->coeff_bat[0] + $energie_c*$this->coeff_bat[1] + $energie_h*$this->coeff_bat[2])));
else
return array($prod_met, $prod_cri, $prod_hy);
}
function creer($id_user, $mere = false)
{
global $VAR;
//Définition des paramètres de l'utilisateur pour la planète
$this->id_user = $id_user;
//Génération du nombre de case et de l'image en fonction de la position dans le système
if ($mere)
{
$this->cases = 225;
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']*0.75)
{
$this->cases = mt_rand(200,255);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/2)
{
$this->cases = mt_rand(250,300);
$this->image = mt_rand(1,19);
}
elseif ($this->position > $VAR['nb_planete']/4)
{
$this->cases = mt_rand(175,260);
$this->image = mt_rand(1,19);
}
else
{
$this->cases = mt_rand(150,220);
$this->image = mt_rand(1,19);
}
//Définition des principaux paramètres de la planète
if ($mere)
$this->nom_planete = 'Planète mère';
else
$this->nom_planete = 'Planète colonisée';
$this->metal = 1000;
$this->cristal = 700;
$this->hydrogene = 0;
$this->modif = array("id_user", "nom_planete", "galaxie", "ss", "position", "image", "cases");
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct()
{
if (empty($this->ss) || empty($this->id_user))
return;
if (DEBUG)
var_dump($this);
global $table_planete;
if (empty($this->id))
{
$outNomChamps = array(); $outValeurs = array();
$bdd = new BDD();
foreach($this->modif as $modif)
{
//On gère les champs variables tableaux
if (is_array($modif))
{
$calc = dDonnees::nameVAR($modif[0]);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
$outNomChamps[] = ${$calc.'VAR'}[$modif[1]];
$outValeurs[] = $this->{$modif[0]}[$modif[1]];
}
elseif ($modif == "force")
continue;
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
$outNomChamps[] = $modif;
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$outValeurs[] = $this->{$modif};
else
$outValeurs[] = "'".$this->{$modif}."'";
}
else
{
if (is_array($this->{$modif}) && $modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$outNomChamps[] = $modif;
$outValeurs[] = "'$prep'";
}
else
{
$calc = dDonnees::nameVAR($modif);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
{
$outNomChamps[] = ${$calc.'VAR'}[$j];
$outValeurs[] = $value;
}
}
}
}
$bdd->query("INSERT INTO $table_planete (".implode(', ', $outNomChamps).", hash_planete) VALUES (".implode(', ', $outValeurs).", SHA1(CONCAT('g',planete.galaxie,'s',planete.ss,'p',planete.position)))");
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : outNomChamps = ".serialize($outNomChamps)." ; outValeurs = ".serialize($outValeurs), 2);
$bdd->deconnexion();
}
else
{
$out = array();
$bdd = new BDD();
foreach($this->modif as $modif)
{
//On gère les champs variables tableaux
if (is_array($modif))
{
$calc = dDonnees::nameVAR($modif[0]);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
if (empty(${$calc.'VAR'}))
trigger_error('Impossible de trouver les données pour '.$modif[0], E_USER_ERROR);
$out[] = ${$calc.'VAR'}[$modif[1]]." = ".$this->{$modif[0]}[$modif[1]];
}
elseif ($modif == "force")
$out[] = "timestamp = timestamp";
elseif (!is_array($this->{$modif}) && !is_object($this->{$modif}))
{
$bdd->escape($this->{$modif});
if (is_int($this->{$modif}) || is_float($this->{$modif}))
$out[] = $modif." = ".$this->{$modif};
else
$out[] = $modif." = '".$this->{$modif}."'";
}
else
{
if ($modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out[] = $modif." = '$prep'";
}
else
{
$calc = dDonnees::nameVAR($modif);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
$out[] = ${$calc.'VAR'}[$j]." = ".$value;
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_planete SET timestamp = ".time().", metal = ".$this->metal.", cristal = ".$this->cristal.", hydrogene = ".$this->hydrogene.", ".implode(', ', $out)." WHERE id = ".$this->id.";";
if (DEBUG)
echo '<br /><br />'.$sql;
$bdd->query($sql);
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out)." avec l'ID : ".$this->id, 2);
}
$bdd->deconnexion();
parent::__destruct();
}
}
}
?>

View file

@ -0,0 +1,796 @@
<?php
/*
* pop3.php
*
* @(#) $Header: /home/mlemos/cvsroot/pop3/pop3.php,v 1.23 2009/01/31 04:06:12 mlemos Exp $
*
*/
class pop3_class
{
var $hostname="localhost";
var $port=110;
var $tls=0;
var $quit_handshake=1;
var $error="";
var $authentication_mechanism="USER";
var $realm="";
var $workstation="";
var $join_continuation_header_lines=1;
/* Private variables - DO NOT ACCESS */
var $connection=0;
var $state="DISCONNECTED";
var $greeting="";
var $must_update=0;
var $debug=0;
var $html_debug=0;
var $next_token="";
var $message_buffer="";
var $connection_name = '';
/* Private methods - DO NOT CALL */
Function Tokenize($string,$separator="")
{
if(!strcmp($separator,""))
{
$separator=$string;
$string=$this->next_token;
}
for($character=0;$character<strlen($separator);$character++)
{
if(GetType($position=strpos($string,$separator[$character]))=="integer")
$found=(IsSet($found) ? min($found,$position) : $position);
}
if(IsSet($found))
{
$this->next_token=substr($string,$found+1);
return(substr($string,0,$found));
}
else
{
$this->next_token="";
return($string);
}
}
Function SetError($error)
{
return($this->error=$error);
}
Function OutputDebug($message)
{
$message.="\n";
if($this->html_debug)
$message=str_replace("\n","<br />\n",HtmlSpecialChars($message));
echo $message;
flush();
}
Function GetLine()
{
for($line="";;)
{
if(feof($this->connection))
return(0);
$line.=fgets($this->connection,100);
$length=strlen($line);
if($length>=2
&& substr($line,$length-2,2)=="\r\n")
{
$line=substr($line,0,$length-2);
if($this->debug)
$this->OutputDebug("S $line");
return($line);
}
}
}
Function PutLine($line)
{
if($this->debug)
$this->OutputDebug("C $line");
return(fputs($this->connection,"$line\r\n"));
}
Function OpenConnection()
{
if($this->tls)
{
$version=explode(".",function_exists("phpversion") ? phpversion() : "3.0.7");
$php_version=intval($version[0])*1000000+intval($version[1])*1000+intval($version[2]);
if($php_version<4003000)
return("establishing TLS connections requires at least PHP version 4.3.0");
if(!function_exists("extension_loaded")
|| !extension_loaded("openssl"))
return("establishing TLS connections requires the OpenSSL extension enabled");
}
if($this->hostname=="")
return($this->SetError("2 it was not specified a valid hostname"));
if($this->debug)
$this->OutputDebug("Connecting to ".$this->hostname." ...");
if(($this->connection=@fsockopen(($this->tls ? "tls://" : "").$this->hostname, $this->port, $error, $error_message))==0)
{
switch($error)
{
case -3:
return($this->SetError("-3 socket could not be created"));
case -4:
return($this->SetError("-4 dns lookup on hostname \"$hostname\" failed"));
case -5:
return($this->SetError("-5 connection refused or timed out"));
case -6:
return($this->SetError("-6 fdopen() call failed"));
case -7:
return($this->SetError("-7 setvbuf() call failed"));
default:
return($this->SetError($error." could not connect to the host \"".$this->hostname."\": ".$error_message));
}
}
return("");
}
Function CloseConnection()
{
if($this->debug)
$this->OutputDebug("Closing connection.");
if($this->connection!=0)
{
fclose($this->connection);
$this->connection=0;
}
}
/* Public methods */
/* Open method - set the object variable $hostname to the POP3 server address. */
Function Open()
{
if($this->state!="DISCONNECTED")
return($this->SetError("1 a connection is already opened"));
if(($error=$this->OpenConnection())!="")
return($error);
$greeting=$this->GetLine();
if(GetType($greeting)!="string"
|| $this->Tokenize($greeting," ")!="+OK")
{
$this->CloseConnection();
return($this->SetError("3 POP3 server greeting was not found"));
}
$this->Tokenize("<");
$this->greeting = $this->Tokenize(">");
$this->must_update=0;
$this->state="AUTHORIZATION";
return("");
}
/* Close method - this method must be called at least if there are any
messages to be deleted */
Function Close()
{
if($this->state=="DISCONNECTED")
return($this->SetError("no connection was opened"));
while($this->state=='GETMESSAGE')
{
if(strlen($error=$this->GetMessage(8000, $message, $end_of_message)))
return($error);
}
if($this->must_update
|| $this->quit_handshake)
{
if($this->PutLine("QUIT")==0)
return($this->SetError("Could not send the QUIT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get quit command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not quit the connection: ".$this->Tokenize("\r\n")));
}
$this->CloseConnection();
$this->state="DISCONNECTED";
pop3_class::SetConnection(-1, $this->connection_name, $this);
return("");
}
/* Login method - pass the user name and password of POP account. Set
$apop to 1 or 0 wether you want to login using APOP method or not. */
Function Login($user,$password,$apop=0)
{
if($this->state!="AUTHORIZATION")
return($this->SetError("connection is not in AUTHORIZATION state"));
if($apop)
{
if(!strcmp($this->greeting,""))
return($this->SetError("Server does not seem to support APOP authentication"));
if($this->PutLine("APOP $user ".md5("<".$this->greeting.">".$password))==0)
return($this->SetError("Could not send the APOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get APOP login command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("APOP login failed: ".$this->Tokenize("\r\n")));
}
else
{
$authenticated=0;
if(strcmp($this->authentication_mechanism,"USER")
&& function_exists("class_exists")
&& class_exists("sasl_client_class"))
{
if(strlen($this->authentication_mechanism))
$mechanisms=array($this->authentication_mechanism);
else
{
$mechanisms=array();
if($this->PutLine("CAPA")==0)
return($this->SetError("Could not send the CAPA command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get CAPA command response"));
if(!strcmp($this->Tokenize($response," "),"+OK"))
{
for(;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the supported authentication methods"));
switch($this->Tokenize($response," "))
{
case ".":
break 2;
case "SASL":
for($method=1;strlen($mechanism=$this->Tokenize(" "));$method++)
$mechanisms[]=$mechanism;
break;
}
}
}
}
$sasl=new sasl_client_class;
$sasl->SetCredential("user",$user);
$sasl->SetCredential("password",$password);
if(strlen($this->realm))
$sasl->SetCredential("realm",$this->realm);
if(strlen($this->workstation))
$sasl->SetCredential("workstation",$this->workstation);
do
{
$status=$sasl->Start($mechanisms,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
break;
case SASL_NOMECH:
if(strlen($this->authentication_mechanism))
return($this->SetError("authenticated mechanism ".$this->authentication_mechanism." may not be used: ".$sasl->error));
break;
default:
return($this->SetError("Could not start the SASL authentication client: ".$sasl->error));
}
if(strlen($sasl->mechanism))
{
if($this->PutLine("AUTH ".$sasl->mechanism.(IsSet($message) ? " ".base64_encode($message) : ""))==0)
return("Could not send the AUTH command");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get AUTH command response");
switch($this->Tokenize($response," "))
{
case "+OK":
$response="";
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
for(;!$authenticated;)
{
do
{
$status=$sasl->Step($response,$message,$interactions);
}
while($status==SASL_INTERACT);
switch($status)
{
case SASL_CONTINUE:
if($this->PutLine(base64_encode($message))==0)
return("Could not send message authentication step message");
$response=$this->GetLine();
if(GetType($response)!="string")
return("Could not get authentication step message response");
switch($this->Tokenize($response," "))
{
case "+OK":
$authenticated=1;
break;
case "+":
$response=base64_decode($this->Tokenize("\r\n"));
break;
default:
return($this->SetError("Authentication error: ".$this->Tokenize("\r\n")));
}
break;
default:
return($this->SetError("Could not process the SASL authentication step: ".$sasl->error));
}
}
}
}
if(!$authenticated)
{
if($this->PutLine("USER $user")==0)
return($this->SetError("Could not send the USER command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get user login entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("User error: ".$this->Tokenize("\r\n")));
if($this->PutLine("PASS $password")==0)
return($this->SetError("Could not send the PASS command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get login password entry response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Password error: ".$this->Tokenize("\r\n")));
}
}
$this->state="TRANSACTION";
return("");
}
/* Statistics method - pass references to variables to hold the number of
messages in the mail box and the size that they take in bytes. */
Function Statistics(&$messages,&$size)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("STAT")==0)
return($this->SetError("Could not send the STAT command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get the statistics command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the statistics: ".$this->Tokenize("\r\n")));
$messages=$this->Tokenize(" ");
$size=$this->Tokenize(" ");
return("");
}
/* ListMessages method - the $message argument indicates the number of a
message to be listed. If you specify an empty string it will list all
messages in the mail box. The $unique_id flag indicates if you want
to list the each message unique identifier, otherwise it will
return the size of each message listed. If you list all messages the
result will be returned in an array. */
Function ListMessages($message,$unique_id)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($unique_id)
$list_command="UIDL";
else
$list_command="LIST";
if($this->PutLine("$list_command".($message ? " ".$message : ""))==0)
return($this->SetError("Could not send the $list_command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not get the message listing: ".$this->Tokenize("\r\n")));
if($message=="")
{
for($messages=array();;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message list response"));
if($response==".")
break;
$message=intval($this->Tokenize($response," "));
if($unique_id)
$messages[$message]=$this->Tokenize(" ");
else
$messages[$message]=intval($this->Tokenize(" "));
}
return($messages);
}
else
{
$message=intval($this->Tokenize(" "));
$value=$this->Tokenize(" ");
return($unique_id ? $value : intval($value));
}
}
/* RetrieveMessage method - the $message argument indicates the number of
a message to be listed. Pass a reference variables that will hold the
arrays of the $header and $body lines. The $lines argument tells how
many lines of the message are to be retrieved. Pass a negative number
if you want to retrieve the whole message. */
Function RetrieveMessage($message,&$headers,&$body,$lines)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
for($headers=$body=array(),$line=0;;)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
case "":
break 2;
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
if($this->join_continuation_header_lines
&& $line>0
&& ($response[0]=="\t"
|| $response[0]==" "))
$headers[$line-1].=$response;
else
{
$headers[$line]=$response;
$line++;
}
}
for($line=0;;$line++)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message"));
switch($response)
{
case ".":
return("");
default:
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
break;
}
$body[$line]=$response;
}
return("");
}
/* OpenMessage method - the $message argument indicates the number of
a message to be opened. The $lines argument tells how many lines of
the message are to be retrieved. Pass a negative number if you want
to retrieve the whole message. */
Function OpenMessage($message, $lines=-1)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($lines<0)
{
$command="RETR";
$arguments="$message";
}
else
{
$command="TOP";
$arguments="$message $lines";
}
if($this->PutLine("$command $arguments")==0)
return($this->SetError("Could not send the $command command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message retrieval command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not retrieve the message: ".$this->Tokenize("\r\n")));
$this->state="GETMESSAGE";
$this->message_buffer="";
return("");
}
/* GetMessage method - the $count argument indicates the number of bytes
to be read from an opened message. The $message returns by reference
the data read from the message. The $end_of_message argument returns
by reference a boolean value indicated whether it was reached the end
of the message. */
Function GetMessage($count, &$message, &$end_of_message)
{
if($this->state!="GETMESSAGE")
return($this->SetError("connection is not in GETMESSAGE state"));
$message="";
$end_of_message=0;
while($count>strlen($this->message_buffer)
&& !$end_of_message)
{
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not retrieve the message headers"));
if(!strcmp($response,"."))
{
$end_of_message=1;
$this->state="TRANSACTION";
break;
}
else
{
if(substr($response,0,1)==".")
$response=substr($response,1,strlen($response)-1);
$this->message_buffer.=$response."\r\n";
}
}
if($end_of_message
|| $count>=strlen($this->message_buffer))
{
$message=$this->message_buffer;
$this->message_buffer="";
}
else
{
$message=substr($this->message_buffer, 0, $count);
$this->message_buffer=substr($this->message_buffer, $count);
}
return("");
}
/* DeleteMessage method - the $message argument indicates the number of
a message to be marked as deleted. Messages will only be effectively
deleted upon a successful call to the Close method. */
Function DeleteMessage($message)
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("DELE $message")==0)
return($this->SetError("Could not send the DELE command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get message delete command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not delete the message: ".$this->Tokenize("\r\n")));
$this->must_update=1;
return("");
}
/* ResetDeletedMessages method - Reset the list of marked to be deleted
messages. No messages will be marked to be deleted upon a successful
call to this method. */
Function ResetDeletedMessages()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("RSET")==0)
return($this->SetError("Could not send the RSET command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not get reset deleted messages command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not reset deleted messages: ".$this->Tokenize("\r\n")));
$this->must_update=0;
return("");
}
/* IssueNOOP method - Just pings the server to prevent it auto-close the
connection after an idle timeout (tipically 10 minutes). Not very
useful for most likely uses of this class. It's just here for
protocol support completeness. */
Function IssueNOOP()
{
if($this->state!="TRANSACTION")
return($this->SetError("connection is not in TRANSACTION state"));
if($this->PutLine("NOOP")==0)
return($this->SetError("Could not send the NOOP command"));
$response=$this->GetLine();
if(GetType($response)!="string")
return($this->SetError("Could not NOOP command response"));
if($this->Tokenize($response," ")!="+OK")
return($this->SetError("Could not issue the NOOP command: ".$this->Tokenize("\r\n")));
return("");
}
Function &SetConnection($set, &$current_name, &$pop3)
{
static $connections = array();
if($set>0)
{
$current_name = strval(count($connections));
$connections[$current_name] = &$pop3;
}
elseif($set<0)
{
$connections[$current_name] = '';
$current_name = '';
}
elseif(IsSet($connections[$current_name])
&& GetType($connections[$current_name])!='string')
{
$connection = &$connections[$current_name];
return($connection);
}
return($pop3);
}
/* GetConnectionName method - Retrieve the name associated to an
established POP3 server connection to use as virtual host name for
use in POP3 stream wrapper URLs. */
Function GetConnectionName(&$connection_name)
{
if($this->state!="TRANSACTION")
return($this->SetError("cannot get the name of a POP3 connection that was not established and the user has logged in"));
if(strlen($this->connection_name) == 0)
pop3_class::SetConnection(1, $this->connection_name, $this);
$connection_name = $this->connection_name;
return('');
}
};
class pop3_stream
{
var $opened = 0;
var $report_errors = 1;
var $read = 0;
var $buffer = "";
var $end_of_message=1;
var $previous_connection = 0;
var $pop3;
Function SetError($error)
{
if($this->report_errors)
trigger_error($error);
return(FALSE);
}
Function ParsePath($path, &$url)
{
if(!$this->previous_connection)
{
if(IsSet($url["host"]))
$this->pop3->hostname=$url["host"];
if(IsSet($url["port"]))
$this->pop3->port=intval($url["port"]);
if(IsSet($url["scheme"])
&& !strcmp($url["scheme"],"pop3s"))
$this->pop3->tls=1;
if(!IsSet($url["user"]))
return($this->SetError("it was not specified a valid POP3 user"));
if(!IsSet($url["pass"]))
return($this->SetError("it was not specified a valid POP3 password"));
if(!IsSet($url["path"]))
return($this->SetError("it was not specified a valid mailbox path"));
}
if(IsSet($url["query"]))
{
parse_str($url["query"],$query);
if(IsSet($query["debug"]))
$this->pop3->debug = intval($query["debug"]);
if(IsSet($query["html_debug"]))
$this->pop3->html_debug = intval($query["html_debug"]);
if(!$this->previous_connection)
{
if(IsSet($query["tls"]))
$this->pop3->tls = intval($query["tls"]);
if(IsSet($query["realm"]))
$this->pop3->realm = UrlDecode($query["realm"]);
if(IsSet($query["workstation"]))
$this->pop3->workstation = UrlDecode($query["workstation"]);
if(IsSet($query["authentication_mechanism"]))
$this->pop3->realm = UrlDecode($query["authentication_mechanism"]);
}
if(IsSet($query["quit_handshake"]))
$this->pop3->quit_handshake = intval($query["quit_handshake"]);
}
return(TRUE);
}
Function stream_open($path, $mode, $options, &$opened_path)
{
$this->report_errors = (($options & STREAM_REPORT_ERRORS) !=0);
if(strcmp($mode, "r"))
return($this->SetError("the message can only be opened for reading"));
$url=parse_url($path);
$host = $url['host'];
$pop3 = &pop3_class::SetConnection(0, $host, $this->pop3);
if(IsSet($pop3))
{
$this->pop3 = &$pop3;
$this->previous_connection = 1;
}
else
$this->pop3=new pop3_class;
if(!$this->ParsePath($path, $url))
return(FALSE);
$message=substr($url["path"],1);
if(strcmp(intval($message), $message)
|| $message<=0)
return($this->SetError("it was not specified a valid message to retrieve"));
if(!$this->previous_connection)
{
if(strlen($error=$this->pop3->Open()))
return($this->SetError($error));
$this->opened = 1;
$apop = (IsSet($url["query"]["apop"]) ? intval($url["query"]["apop"]) : 0);
if(strlen($error=$this->pop3->Login(UrlDecode($url["user"]), UrlDecode($url["pass"]),$apop)))
{
$this->stream_close();
return($this->SetError($error));
}
}
if(strlen($error=$this->pop3->OpenMessage($message,-1)))
{
$this->stream_close();
return($this->SetError($error));
}
$this->end_of_message=FALSE;
if($options & STREAM_USE_PATH)
$opened_path=$path;
$this->read = 0;
$this->buffer = "";
return(TRUE);
}
Function stream_eof()
{
if($this->read==0)
return(FALSE);
return($this->end_of_message);
}
Function stream_read($count)
{
if($count<=0)
return($this->SetError("it was not specified a valid length of the message to read"));
if($this->end_of_message)
return("");
if(strlen($error=$this->pop3->GetMessage($count, $read, $this->end_of_message)))
return($this->SetError($error));
$this->read += strlen($read);
return($read);
}
Function stream_close()
{
while(!$this->end_of_message)
$this->stream_read(8000);
if($this->opened)
{
$this->pop3->Close();
$this->opened = 0;
}
}
};
?>

View file

@ -0,0 +1,403 @@
<?php
/**
* Class Rapport
*
* Génération et envoie de rapport de mission de flotte
*
*/
class Rapport
{
var $type = 0;
var $var = array();
var $utilA = 0;
var $utilB = 0;
var $timestamp = 0;
var $titreA = "";
var $titreB = "";
var $rapportA = "";
var $rapportB = "";
/**
* Constructor
* @access protected
*/
function Rapport($type, $utilA, $utilB, $time)
{
$this->type = $type;
$this->utilA = $utilA;
$this->utilB = $utilB;
$this->timestamp = $time;
}
function addInfo($info, $id)
{
$this->var[$id] = $info;
}
function sendRapport()
{
if (!empty($this->utilA) && !empty($this->rapportA))
send_mp($this->utilA->id_user, $this->titreA, $this->rapportA, $this->timestamp);
if (!empty($this->utilB) && !empty($this->rapportB))
send_mp($this->utilB->id_user, $this->titreB, $this->rapportB, $this->timestamp);
}
function send()
{
if ($this->type == '3')
$this->sendCombat();
elseif ($this->type == '1')
$this->sendTransport();
elseif ($this->type == '2')
$this->sendColonisation();
elseif ($this->type == '4')
$this->sendRecyclage();
elseif ($this->type == '5')
$this->sendEspionnage();
elseif ($this->type == '6')
$this->sendAlliance();
elseif ($this->type == '7')
$this->sendAlliance2();
}
function sendEspionnage()
{
global $LANG;
//Différentiation entre les planètes et les astéroides
if (!isset($this->var[0]->nom_planete))
{
$this->titreA = "Rapport d'espionnage de ".$this->var[0]->nom_asteroide." [".$this->var[0]->galaxie.":".$this->var[0]->ss.":A".$this->var[0]->position."]";
$this->rapportA = "<strong>Espionnage de ".$this->var[0]->pseudo." sur ".$this->var[0]->nom_asteroide."[".$this->var[0]->galaxie.":".$this->var[0]->ss.":A".$this->var[0]->position."]</strong><br /><br />";
}
else
{
$this->titreA = "Rapport d'espionnage de ".$this->var[0]->nom_planete." [".$this->var[0]->galaxie.":".$this->var[0]->ss.":".$this->var[0]->position."]";
$this->rapportA = "<strong>Espionnage de ".$this->var[0]->pseudo." sur ".$this->var[0]->nom_planete."[".$this->var[0]->galaxie.":".$this->var[0]->ss.":".$this->var[0]->position."]</strong><br /><br />";
}
if ($this->var[2] < 1)
$this->rapportA .= "<em>Nos sondes n'ont pas pu récolter d'informations sur cette planète.</em>";
else {
//Ressources
if ($this->var[2] > 1)
$this->rapportA .= "<table style=\"margin: auto;\"><tr><th colspan=\"2\">Ressources sur la planète :</th></tr><tr><td>".$LANG[$this->var[0]->race]["ressources"]["noms"]["metal"]." :</td><td>".$this->var[0]->metal."</td></tr><tr><td>".$LANG[$this->var[0]->race]["ressources"]["noms"]["cristal"]." :</td><td>".$this->var[0]->cristal."</td></tr><tr><td>".$LANG[$this->var[0]->race]["ressources"]["noms"]["hydrogene"]." :</td><td>".$this->var[0]->hydrogene."</td></tr></table><br />";
//Bâtiments
if ($this->var[2] > 2)
{
$this->rapportA .= "<table style=\"margin: auto;\"><tr><th>Niveau</th><th>B&acirc;timent</th></tr>";
foreach ($this->var[0]->batiments as $key => $batiment)
{
$this->rapportA .= "<tr><td>".rand($batiment * (1 - $this->var[1]), $batiment * (1 + $this->var[1]))."</td><td>".$LANG[$this->var[0]->race]["batiments"]["noms_sing"][$key]."</td></tr>";
}
$this->rapportA .= "</table><br />";
}
//Flottes en orbite
if ($this->var[2] > 3)
{
}
//Flottes au sol
if ($this->var[2] > 5)
{
$this->rapportA .= "<table style=\"margin: auto;\"><tr><th>Nombre</th><th>Vaisseaux</th></tr>";
foreach ($this->var[0]->vaisseaux as $key => $vaisseau)
{
$this->rapportA .= "<tr><td>".rand($vaisseau * (1 - $this->var[1]), $vaisseau * (1 + $this->var[1]))."</td><td>".$LANG[$this->var[0]->race]["vaisseaux"]["noms_sing"][$key]."</td></tr>";
}
$this->rapportA .= "</table><br />";
}
//Défenses
if ($this->var[2] > 4)
{
$this->rapportA .= "<table style=\"margin: auto;\"><tr><th>Nombre</th><th>Défenses</th></tr>";
foreach ($this->var[0]->terrestres as $key => $unite)
{
if (!dTerrestre::type($key)) $this->rapportA .= "<tr><td>".rand($unite * (1 - $this->var[1]), $unite * (1 + $this->var[1]))."</td><td>".$LANG[$this->var[0]->race]["terrestre"]["noms_sing"][$key]."</td></tr>";
}
$this->rapportA .= "</table><br />";
}
}
if ($this->var[3] >= 1)
{
$this->titreB = "Rapport de contre-espionnage";
if (!isset($this->var[0]->nom_planete))
$this->rapportB = "Nous venons d'apprendre que notre planète : ".$this->var[0]->nom_asteroide."[".$this->var[0]->galaxie.":".$this->var[0]->ss.":A] a été la cible d'un espionnage de la part de ".$this->utilA->pseudo;
else
$this->rapportB = "Nous venons d'apprendre que notre planète : ".$this->var[0]->nom_planete."[".$this->var[0]->galaxie.":".$this->var[0]->ss.":".$this->var[0]->position."] a été la cible d'un espionnage de la part de ".$this->utilA->pseudo;
}
$this->rapportA = $this->rapportA;
}
function sendTransport()
{
global $LANG;
if (!isset($this->var[0]->nom_planete))
{
$titre = 'Transport vers '.$this->var[0]->nom_asteroide.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':A]';
$this->rapportA = 'Vos vaisseaux ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilA->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_asteroide.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':A]</b><br /><br />';
$this->rapportB = 'Les vaisseaux de '.$this->utilA->pseudo.' ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilB->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_asteroide.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':A]</b><br /><br />';
}
else
{
$titre = 'Transport vers '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$this->rapportA = 'Vos vaisseaux ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilA->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
$this->rapportB = 'Les vaisseaux de '.$this->utilA->pseudo.' ont déposé '.$this->var[1][0].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["metal"].', '.$this->var[1][1].' de '.$LANG[$this->utilB->race]["ressources"]["noms"]["cristal"].' et '.$this->var[1][2].' d\''.$LANG[$this->utilB->race]["ressources"]["noms"]["hydrogene"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
}
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($this->rapportA);
$db->escape($this->rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$this->rapportA', '$temps');");
if ($this->utilA->id_user != $this->utilB->id_user) $db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user.", '$titre', '$this->rapportB', '$temps');");
$db->deconnexion();
}
function sendColonisation()
{
$titre = 'Colonisation de ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].']';
if (is_numeric($this->var[0][2]))
{
if ($this->var[1])
$rapport = 'Votre vaisseau a atteint la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] et commence la colonisation.';
else
$rapport = 'Nous n\'avons pas pu coloniser la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] car lorsque nous sommes arrivé sur place, elle était déjà colonisée.';
}
else
{
if ($this->var[1])
$rapport = 'Votre vaisseau a atteint l\'astéroide ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] et commence la colonisation.';
else
$rapport = 'Nous n\'avons pas pu coloniser la planète ['.$this->var[0][0].':'.$this->var[0][1].':'.$this->var[0][2].'] car lorsque nous sommes arrivé sur place, elle était déjà colonisée.';
}
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendRecyclage()
{
global $LANG;
if (!isset($this->var[0]->nom_planete))
{
$titre = 'Recyclage de '.$this->var[0]->nom_asteroide.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':A]';
$rapport = 'Vos vaisseaux récoltent '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].' et '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' sur '.$this->var[0]->nom_asteroide.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':A]</b><br /><br />';
}
else
{
$titre = 'Recyclage de '.$this->var[0]->nom_planete.' ['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']';
$rapport = 'Vos vaisseaux récoltent '.$this->var[1][0].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["metal"].' et '.$this->var[1][1].' de '.$LANG[$this->utilA->race]["ressources"]["noms"]["cristal"].' sur '.$this->var[0]->nom_planete.'['.$this->var[0]->galaxie.':'.$this->var[0]->ss.':'.$this->var[0]->position.']</b><br /><br />';
}
$temps = $this->timestamp;
$db = new BDD();
$db->escape($titre);
$db->escape($rapport);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$titre', '$rapport', '$temps');");
$db->deconnexion();
}
function sendCombat(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$this->rapportA = new Smarty();
$this->rapportB = new Smarty();
$this->rapportA->template_dir = _FCORE.'templates/templates/';
$this->rapportA->compile_dir = _FCORE.'templates/templates_c/';
$this->rapportA->config_dir = _FCORE.'templates/configs/';
$this->rapportA->cache_dir = _FCORE.'templates/cache/';
$this->rapportB->template_dir = _FCORE.'templates/templates/';
$this->rapportB->compile_dir = _FCORE.'templates/templates_c/';
$this->rapportB->config_dir = _FCORE.'templates/configs/';
$this->rapportB->cache_dir = _FCORE.'templates/cache/';
$this->var[4]['pseudo'] = trouvNom($this->var[4]['id_user']);
$this->var[5]['pseudo'] = trouvNom($this->var[5]['id_user']);
$this->rapportA->assign('tour', $this->var[3]);
$this->rapportA->assign('EN', $this->var[4]);
$this->rapportA->assign('flotte', $this->var[5]);
$this->rapportA->assign('vaisseaux1', $this->var[0]);
$this->rapportA->assign('vaisseaux2', $this->var[1]);
$this->rapportA->assign('defenses1', $this->var[2]);
$this->rapportA->assign('vaisseaux3', $this->var[7]);
$this->rapportA->assign('vaisseaux4', $this->var[8]);
$this->rapportA->assign('defenses2', $this->var[9]);
$this->rapportA->assign('termine', $this->var[6][0]);
$this->rapportA->assign('attaquantG', $this->var[6][1]);
$this->rapportA->assign('pillage', $this->var[11]);
$this->rapportA->assign('vaisBC', $nomvais_bc);
$this->rapportA->assign('vaisPV', $nomvais_pv);
$this->rapportA->assign('defBC', $defense_bc);
$this->rapportA->assign('defPV', $defense_pv);
$this->rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$this->rapportA->assign('ressources', $ressourc);
$this->rapportA->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$this->rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$this->rapportA->assign('nomdefEN', $nomterra);
$this->rapportA = $this->rapportA->fetch('game/ATrapport_combat.tpl');
$this->rapportB->assign('tour', $this->var[3]);
$this->rapportB->assign('EN', $this->var[4]);
$this->rapportB->assign('flotte', $this->var[5]);
$this->rapportB->assign('vaisseaux1', $this->var[0]);
$this->rapportB->assign('vaisseaux2', $this->var[1]);
$this->rapportB->assign('defenses1', $this->var[2]);
$this->rapportB->assign('vaisseaux3', $this->var[7]);
$this->rapportB->assign('vaisseaux4', $this->var[8]);
$this->rapportB->assign('defenses2', $this->var[9]);
$this->rapportB->assign('termine', $this->var[6][0]);
$this->rapportB->assign('attaquantG', $this->var[6][1]);
$this->rapportB->assign('matchnul', $this->var[6][2]);
$this->rapportB->assign('pillage', $this->var[11]);
$this->rapportB->assign('vaisBC', $nomvais_bc);
$this->rapportB->assign('vaisPV', $nomvais_pv);
$this->rapportB->assign('defBC', $defense_bc);
$this->rapportB->assign('defPV', $defense_pv);
$this->rapportB->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$this->rapportB->assign('ressources', $ressourc);
$this->rapportB->assign('nomvaisAT', $nomvaisa);
$race = trouvInfo($this->var[4]['id_user'], 'race');
include(_FCORE."../game/noms.php");
$this->rapportB->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$this->rapportB->assign('nomdefEN', $nomterra);
$this->rapportB = $this->rapportB->fetch('game/ENrapport_combat.tpl');
$this->titreA = 'Combat contre '.$this->var[4]['pseudo'];
$this->titreB = 'Combat contre '.$this->var[5]['pseudo'];
$temps = $this->timestamp;
$db = new bdd();
$db->connexion();
$db->escape($this->titreA);
$db->escape($this->titreB);
$db->escape($this->rapportA);
$db->escape($this->rapportB);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$this->titreA', '$this->rapportA', '$temps')");
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilB->id_user."', '$this->titreB', '$this->rapportB', '$temps')");
$db->deconnexion();
}
function show(){
include(_FCORE."../game/vars.php");
include_once(_FCORE."../game/function.php");
require_once(SMARTY_DIR."Smarty.class.php");
$this->rapportA = new Smarty();
$this->rapportA->template_dir = _FCORE.'templates/templates/';
$this->rapportA->compile_dir = _FCORE.'templates/templates_c/';
$this->rapportA->config_dir = _FCORE.'templates/configs/';
$this->rapportA->cache_dir = _FCORE.'templates/cache/';
$this->rapportA->assign('tour', $this->var[3]);
$this->rapportA->assign('EN', $this->var[4]);
$this->rapportA->assign('flotte', $this->var[5]);
$this->rapportA->assign('vaisseaux1', $this->var[0]);
$this->rapportA->assign('vaisseaux2', $this->var[1]);
$this->rapportA->assign('defenses1', $this->var[2]);
$this->rapportA->assign('vaisseaux3', $this->var[7]);
$this->rapportA->assign('vaisseaux4', $this->var[8]);
$this->rapportA->assign('defenses2', $this->var[9]);
$this->rapportA->assign('termine', $this->var[6][0]);
$this->rapportA->assign('attaquantG', $this->var[6][1]);
$this->rapportA->assign('pillage', $this->var[11]);
$this->rapportA->assign('debris', $this->var[12]);
$this->rapportA->assign('infoPLUS', $this->var[14]);
//$this->rapportA->assign('infoPLUS2', $this->var[15]);
$this->rapportA->assign('page', 'simulation');
$this->rapportA->assign('enligne', $this->var[13][0]);
$this->rapportA->assign('infos', $this->var[13][1]);
$this->rapportA->assign('nbinfos', $this->var[13][2]);
$this->rapportA->assign('count', $this->var[13][3]);
$this->rapportA->assign('version', $this->var[13][4]);
$this->rapportA->assign('tpsdejeu', $this->var[13][5]);
$this->rapportA->assign('vaisBC', $nomvais_bc);
$this->rapportA->assign('vaisPV', $nomvais_pv);
$this->rapportA->assign('defBC', $defense_bc);
$this->rapportA->assign('defPV', $defense_pv);
$this->rapportA->assign('nextTour', $this->var[10]);
$race = trouvInfo($this->utilA, 'race');
include(_FCORE."../game/noms.php");
$this->rapportA->assign('ressources', $ressourc);
$this->rapportA->assign('nomvaisAT', $nomvaisa);
$this->rapportA->assign('nomvaisEN', $nomvaisa);
array_splice($nomterra, 0, 8);
$this->rapportA->assign('nomdefEN', $nomterra);
$this->rapportA->assign('race', $race);
return $this->rapportA->fetch('game/SIMrapport_combat.tpl');
return $this->rapportA;
}
function sendAlliance()
{
$this->titreA = 'Déclaration officielle de votre alliance !';
$this->rapportA = 'Félicitations, votre alliance a recueilli suffisament de signature, sa déclaration est maintenant officielle !<br /><br />Vous pouvez dès maintenant administrer votre alliance en vous rendant sur la page Alliance.';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($this->titreA);
$db->escape($this->rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$this->titreA', '$this->rapportA', '$temps')");
$db->deconnexion();
}
function sendAlliance2()
{
$this->titreA = 'Fondation de votre alliance !';
$this->rapportA = 'Pour terminer la création de votre alliance, trouvez 4 joueurs de cette galaxie sans alliance pour leur faire signer votre traité de fondation d\'alliance.<br /><br />Lien de signature : <a href="?p=alliances&amp;q=signer&amp;i='.$this->var[0].'">http://'.$_SERVER['HTTP_HOST'].'/?p=alliances&amp;q=signer&amp;i='.$this->var[0].'</a>';
$temps = $this->timestamp;
$db = new BDD();
$db->escape($this->titreA);
$db->escape($this->rapportA);
$db->query("INSERT INTO ".$this->table." (destinataire, sujet, contenu, temps) VALUES(".$this->utilA->id_user.", '$this->titreA', '$this->rapportA', '$temps')");
$db->deconnexion();
}
}
?>

1039
onyx2/include/Class/smtp.php Normal file

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,43 @@
<?php
include_once("Class/user.php");
/***************************************************************************
* class.SURFACE.php
* -------------------
* begin : Jeudi 21 août 2008
* update : Dimanche 8 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class SURFACE extends User
{
var $id = 0,
$galaxie,
$ss,
$image,
$debris_met,
$debris_cri,
$metal,
$cristal,
$hydrogene,
$alert_ressources = array(false, false, false),
$timestamp,
$file_bat,
$file_vais,
$isolement = false,
$batiments = array(),
$vaisseaux = array(),
$modif = array();
function isolement()
{
return false;
}
function addModif($modif)
{
if (!in_array($modif, $this->modif))
$this->modif[] = $modif;
}
}
?>

View file

@ -0,0 +1,46 @@
<?php
class TinyAsteroide
{
var $id = 0,
$galaxie,
$ss,
$nom_asteroide;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_alliances;
$bdd = new BDD();
//On traite le cas où l'on recoit l'ID ou les coordonnées de l'asteroide
if (is_numeric($id))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):?[Aa]?\]?$#', $id, $position))
{
$aste = $bdd->unique_query("SELECT id, galaxie, ss, nom_asteroide FROM $table_alliances WHERE galaxie = ".$position[1]." AND ss = ".$position[2].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche d\'astéroide incorrect !', E_USER_ERROR);
if (!empty($aste))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $aste["id"];
$this->galaxie = $aste["galaxie"];
$this->ss = $aste["ss"];
$this->nom_asteroide = $aste["nom_asteroide"];
}
}
}
?>

View file

@ -0,0 +1,47 @@
<?php
class TinyPlanete{
var $id = 0,
$galaxie,
$ss,
$position,
$nom_planete;
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function __construct($id)
{
//Récupération du nom des tables utilisées et connexion à la base de données
global $table_planete;
$bdd = new bdd();
//On traite le cas où l'on recoit l'ID ou les coordonnées de la planète
if (is_numeric($id))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE id = $id;");
$bdd->deconnexion();
}
elseif (preg_match('#^\[?([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})\]?$#', $id, $position))
{
$plan = $bdd->unique_query("SELECT id, galaxie, ss, position, nom_planete FROM $table_planete WHERE galaxie = ".$position[1]." AND ss = ".$position[2]." AND position = ".$position[3].";");
$bdd->deconnexion();
}
else
trigger_error('Erreur #04 : Format de recherche de planete incorrect !', E_USER_ERROR);
if (!empty($plan))
{
//Chargement des données depuis le résultat de la base de données
$this->id = $plan["id"];
$this->galaxie = $plan["galaxie"];
$this->ss = $plan["ss"];
$this->position = $plan["position"];
$this->nom_planete = $plan["nom_planete"];
}
}
}
?>

View file

@ -0,0 +1,211 @@
<?php
//Gestion des dépendances
include_once("Class/tinyasteroide.php");
/***************************************************************************
* class.user.php
* ----------------
* begin : Dimanche 7 septembre 2008
* update : Vendredi 27 février 2009
* email : nemunaire@gmail.com
*
*
***************************************************************************/
class User{
var $id_user,
$pseudo,
$auth_level,
$options,
$race,
$alliance,
$id_alliance,
$id_grade_alliance,
$permissions_alliance,
$mv,
$mail,
$envoyerMail,
$last_visite,
$points,
$place_points,
$technologies = array(),
$credits,
$politique,
$politique_lastchange,
$destinationsFavoris,
$amis = array(),
$combatAT_tactique,
$combatDE_tactique,
$modifUser = array();
/**
* Constructeur
* @param int $id id de la planète à importer
*
* @return void
* @access public
*/
function User($id = 0){
if (!empty($id)) {
global $technologiesVAR, $table_user;
$bdd = new bdd();
$bdd->escape($id);
$user = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id;");
$bdd->deconnexion();
if (!empty($user)) {
$this->id_user = $user["id"];
$this->pseudo = $user["pseudo"];
$this->auth_level = $user["auth_level"];
$this->race = $user["race"];
$this->options = intval($user["options"]);
$this->mv = $user["mv"];
$this->id_alliance = $user["id_alliance"];
$this->id_grade_alliance = $user["id_grade_alliance"];
$this->mail = $user["mail"];
$this->envoyerMail = $user["envoyerMail"];
$this->last_visite = $user["last_visite"];
$this->points = $user["points"];
$this->place_points = $user["place_points"];
$this->credits = $user["credits"];
$this->politique = $user["politique"];
$this->politique_lastchange = $user["politique_lastchange"];
if (!empty($user["amis"])) $this->amis = unserialize($user["amis"]);
else $this->amis = array();
if (!empty($user["destinationsFavoris"])) $this->destinationsFavoris = unserialize($user["destinationsFavoris"]);
else $this->destinationsFavoris = array();
$this->combatAT_tactique = $user["combatAT_tactique"];
$this->combatDE_tactique = $user["combatDE_tactique"];
foreach($technologiesVAR as $tech){
$this->technologies[] = intval($user[$tech]);
}
//Si l'ID d'alliance est défini, on charge l'alliance
if (!empty($this->id_alliance))
$this->alliance = new TinyAsteroide($this->id_alliance);
}
else die('Erreur #01 : Utilisateur recherché introuvable dans la base de données. Contactez le support technique ('.$config['mail_support'].') au plus vite en précisant le code d\'erreur.');
}
}
function loadPermissions($fondateur = 0)
{
if ($fondateur == $this->id_user)
$this->permissions_alliance = 1023;
else
{
global $table_alliances_grade;
$bdd = new BDD();
$grade = $bdd->unique_query("SELECT * FROM $table_alliances_grade WHERE id = ".$this->id_grade_alliance.";");
$bdd->deconnexion();
$this->permissions_alliance = intval($grade['auth']);
}
}
function addPoints($metal, $cristal, $hydrogene, $credits = 0, $demolition = false)
{
global $table_bourse_ressources;
//On charge les 3 valeurs boursières
$bdd = new BDD();
$bourse = $bdd->query("SELECT dispo FROM $table_bourse_ressources;");
$bdd->deconnexion();
if (!empty($credits))
{
//TODO Equivalence non prouvée entre $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7); et $credits/bourse_calcPrixBase($bourse[0]["dispo"], 1) * 0.7; dans le but de ne donner que 70% des points
$metal += $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7);
$cristal += $credits/bourse_calcPrixBase($bourse[1]["dispo"], 0.7);
$hydrogene += $credits/bourse_calcPrixBase($bourse[2]["dispo"], 0.7);
}
$points = bourse_calcPrixBase($bourse[0]["dispo"], $metal);
$points += bourse_calcPrixBase($bourse[1]["dispo"], $cristal);
$points += bourse_calcPrixBase($bourse[2]["dispo"], $hydrogene);
if ($demolition)
$this->points -= intval($points);
else
$this->points += intval($points);
$this->addModifUser("points");
}
function addCredits($credits)
{
$this->credits += $credits;
$this->addModifUser("credits");
return 0;
}
function addModifUser($modif)
{
if (!in_array($modif, $this->modifUser))
$this->modifUser[] = $modif;
}
/**
* Destructeur
*
* @return void
* @access public
*/
function __destruct(){
global $table_user;
$out = array();
$bdd = new BDD();
foreach($this->modifUser as $key => $modif)
{
//On gère les champs variables tableaux
if (is_array($modif))
{
$calc = dDonnees::nameVAR($modif[0]);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
if (empty(${$calc.'VAR'}))
trigger_error('Impossible de trouver les données pour '.$modif[0], E_USER_ERROR);
$out[] = ${$calc.'VAR'}[$modif[1]]." = ".$this->{$modif[0]}[$modif[1]];
}
elseif ($modif == "force")
$out[] = " ";
elseif (!is_array($this->{$modif}))
{
$bdd->escape($this->{$modif});
if (is_int($this->{$modif}) || is_float($this->{$modif})) $out[] .= $modif." = ".$this->{$modif};
else $out[] .= $modif." = '".$this->{$modif}."'";
}
else
{
if ($modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments")
{
$prep = serialize($this->{$modif});
$bdd->escape($prep);
$out[] = $modif." = '$prep'";
}
else
{
$calc = dDonnees::nameVAR($modif);
if (!isset(${$calc.'VAR'}))
global ${$calc.'VAR'};
foreach($this->{$modif} as $j => $value)
$out[] = ${$calc.'VAR'}[$j]." = ".$value;
}
}
}
if (!empty($out))
{
$sql = "UPDATE $table_user SET ".implode(', ', $out)." WHERE id = ".$this->id_user.";";
if (DEBUG)
echo '<br /><br />'.$sql;
$bdd->query($sql);
if ($bdd->affected() != 1)
elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out)." avec l'ID ".$this->id_user, 2);
}
$bdd->deconnexion();
}
}
?>