From f9cd9df25c16afb334a1a82945b21f16fee704a4 Mon Sep 17 00:00:00 2001
From: Mathieu Loiseau <mlois_-gr@yahoo.fr>
Date: Mon, 8 May 2017 19:34:04 +0200
Subject: [PATCH] score & traces augur start

---
 controllers/diviner.class.php        | 97 ++++------------------------
 controllers/traces.handler.class.php | 44 ++++++++++---
 models/userlvl.class.php             | 10 ++-
 score_traces.api.php                 |  2 +-
 views/diviner.game.html              | 27 +-------
 5 files changed, 57 insertions(+), 123 deletions(-)

diff --git a/controllers/diviner.class.php b/controllers/diviner.class.php
index b51440f..cc76e9d 100755
--- a/controllers/diviner.class.php
+++ b/controllers/diviner.class.php
@@ -2,6 +2,8 @@
 require_once("./models/item.factory.class.php");
 require_once("./models/card.class.php");
 require_once("./models/userlvl.class.php");
+require_once("./controllers/traces.handler.class.php");
+/**/include_once("debug.php");
 
 class diviner_game
 {
@@ -11,12 +13,12 @@ class diviner_game
 	private $lang = array();
 	private $motadeviner='';
 	private $nivcarte = '';
+	private $th ;
 
 
 	private $userlang = '';
 	private $user= '';
 	private $diviner= '';
-	private $pointsSanction ='';
 
 	private $raisin ='';
 	private $res2 = '';
@@ -27,8 +29,6 @@ class diviner_game
 	private $score='';
 
 
-	private $carteValide = false;
-
 	private $adresse = '';
 	private $reussie = 'en cours';
 	private $mess='';
@@ -43,7 +43,6 @@ class diviner_game
 	{
 		if ( $this->init() )
         {
-			$this->sanctionLastPartie();
 			if($this->selectpartie()){
 				$this->update();
 			}
@@ -59,80 +58,19 @@ class diviner_game
 		$this->user = user::getInstance();
 		$this->diviner = $this->user->id;
 
-		//récupération des points de sanction (not handled by ScoreValues et tant pis)
-		$this->pointsSanction = loosePointsDevin;
-
-
 		if(isset($_SESSION["langDevin"])){
 			$this->userlang = $_SESSION["langDevin"];
 		}
 		else{
 			$this->userlang = $this->user->langGame;
 		}
-		unset($_SESSION["motDeviner"]); //permet de supprimer la sécurité qui empêche le joueur de s'ajouter des points à l'infini
-		unset($_SESSION["timeOutOracle"]); //permet de supprimer la sécurité qui empêche le joueur d'enlever des points à l'oracle à l'infini
-
+		$this->th = new TracesHandler();
 		return true;
 	}
 
-	private function sanctionLastPartie()
-	{ // fonction qui permet de vérifier l'état de la dernière partie et de sanctionner le joueur de 5 pts s'il a quitté la partitatut = "en cours")
-		include_once('./sys/load_iso.php');
-		$lang_iso = new IsoLang();
-	    $db =  db::getInstance();
-		$sql =  "SELECT *
-			FROM parties WHERE idDevin = \"".$this->diviner."\"
-			ORDER BY parties.tpsDevin DESC
-			LIMIT 1";
-			$res=$db->query($sql);
-			$this->sanction = mysqli_fetch_assoc($res);
-
-		if($this->sanction['reussie'] == "en cours"){
-
-		   $sql = "SELECT *
-            	FROM sanctionCarte
-                WHERE idDevin ='".$this->diviner."' AND enregistrementID='".$this->sanction['enregistrementID']."'";
-                $res = $db->query($sql);
-                $this->existSanction = mysqli_num_rows($res);
-				if($this->existSanction == 0){
-					//Ajout de la carte sanctionné dans la BDD
-					$sql = "INSERT INTO sanctionCarte
-					(idDevin,enregistrementID)
-					VALUES (".$this->diviner.",".$this->sanction['enregistrementID'].")";
-
-                   	if( $res = $db->query($sql)){
-						$sql = "SELECT scoreDevin, scoreGlobal
-						FROM score
-						WHERE userid ='".$this->diviner."' AND langue='" . $lang_iso->french_for($this->userlang) . "'";
-						$res = $db->query($sql);
-						$this->score = mysqli_fetch_assoc($res);
-
-						if ($this->score['scoreDevin'] >= $this->pointsSanction) { #à modifier avec un fichier config
-
-
-							$this->score['scoreDevin']-=$this->pointsSanction;
-							$this->score['scoreGlobal']-=$this->pointsSanction;
-
-							$sql='UPDATE score
-							SET scoreDevin="'.$this->score['scoreDevin'].'", scoreGlobal ="'.$this->score['scoreGlobal'].'"
-							WHERE userid="'.$this->diviner.'" AND langue="' . $lang_iso->french_for($this->userlang) . '"';
-							$res=$db->query($sql);
-							array_push($this->lang,"sanction");
-						}
-						else
-						{
-					 		array_push($this->lang,"sanction_without_points");
-
-						}
-		      	    }
-				}
-		}
-	}
-
 	private function selectpartie(){
 		$res = false;
 		try{
-			/**/include_once("debug.php");
 			$recordingFactory = new ItemFactory($this->diviner,$this->user->langGame);
 			$this->raisin = $recordingFactory->get_recording(ItemFactory::VALID_RECORDING_NOT_ME);
 			if(is_object($this->raisin)){
@@ -148,6 +86,7 @@ class diviner_game
 					$this->time = $sv->get_augur_time($this->user->userlvl, $this->raisin->duration);
 
 					// récupération du pseudo de l'oracle pour savoir qui on écoute
+					require_once("./sys/db.class.php");
 					$db = db::getInstance();
 					$sql = 'SELECT username
 							FROM user WHERE userid ="'.$this->raisin->idOracle.'"';
@@ -176,25 +115,15 @@ class diviner_game
 		catch(Exception $e){
 			array_push($this->errors,'NoGame');
 		}
-		$this->setcarteValide($res);
 		return $res;
 	}
 
-	private function update()
-	{
-		//Insertion des informations dans la table parties
-		//connexion à  la bd
-			$db = db::getInstance();
-
-			 $sql = 'INSERT INTO parties
-				(enregistrementID,idDevin,tpsDevin,reussie)
-					VALUES(' .
-						$db->escape((string) $this->raisin->enregistrementID).','.
-						$db->escape((string) $this->diviner) . ','.
-						'CURRENT_TIMESTAMP,'.
-						$db->escape((string) $this->reussie).')';
-				$db->query($sql);
-			return false;
+	private function update(){
+		//update dans ce contexte, crée uniquement une nouvelle partie
+		//la vue appellera diviner timeout/result selon la situation
+		$this->th->augur_start_play($this->raisin->enregistrementID,
+											 $this->raisin->OracleLang,
+											 $this->raisin->nivcarte);
 	}
 
 	private function display()
@@ -203,10 +132,6 @@ class diviner_game
 
         return true;
 	}
-
-    public function setcarteValide ($state){
-		$this->carteValide=$state;
-	}
 }
 
 ?>
diff --git a/controllers/traces.handler.class.php b/controllers/traces.handler.class.php
index a4ac0a1..3f6d086 100644
--- a/controllers/traces.handler.class.php
+++ b/controllers/traces.handler.class.php
@@ -14,7 +14,6 @@ class TracesHandler{
 	private $druid = false;
 	private $augur = false;
 	private $queries;
-	private $recording;
 	private $user;
 	private $lang_iso;
 	private $sv;//game handler
@@ -45,7 +44,7 @@ class TracesHandler{
 		array_push($this->queries, $query);
 	}
 
-	public function oracle_see_card($card, $gameLevel){
+	public function oracle_see_card($card){
 		try{
 			$lang = $this->lang_iso->any_to_iso($card->get_lang());
 			$user_level = $this->user->get_lang_lvl($lang);
@@ -54,15 +53,15 @@ class TracesHandler{
 		}
 		//once a card is seen it is stored in db for score and next play
 		$this->reinit_queries();
-		$stakes = array("V" => $this->sv->get_stake($gameLevel, $card->get_level(), $user_level, true),
-							 "D" => $this->sv->get_stake($gameLevel, $card->get_level(), $user_level, false));
+		$stakes = array("V" => $this->sv->get_stake($this->user->userlvl, $card->get_level(), $user_level, true),
+							 "D" => $this->sv->get_stake($this->user->userlvl, $card->get_level(), $user_level, false));
 			//create recording
 		$this->add_query("INSERT INTO `enregistrement` (`idOracle`, `OracleLang`, `carteID`, `nivcarte`, `nivpartie`, `validation`, `miseD`, `miseV`)
 					 VALUES ('".$this->user->id."','".
 									$lang."', '".
 									$card->get_id()."', '".
 									$card->get_level()."', '".
-									$gameLevel."','given up', '".$stakes['D']."', '".$stakes['V']."');");
+									$this->user->userlvl."','given up', '".$stakes['D']."', '".$stakes['V']."');");
 		//score
 		$this->add_query("SET @recording_id = LAST_INSERT_ID();");
 		$this->add_query("UPDATE `stats` SET `score_oracle`=`score_oracle`+(SELECT ".$this->sv->get_recording_score_sql_formula()." FROM `enregistrement` WHERE `enregistrementID`=@recording_id), `nbAbandons_oracle`=`nbAbandons_oracle`+1, `nbJeux_oracle`=`nbJeux_oracle`+1 WHERE `userid`='".$this->user->id."' AND `langue`='$lang';");
@@ -200,8 +199,6 @@ class TracesHandler{
 			false
 		));
 		//TODO, il faudrait des notifications de réhabilitation / révocation, mais de toute façon il y a pas vraiment la fonctionnalité…
-		/**/require_once("debug.php");
-		/**/myLog("<h2>Druid action</h2><pre>".print_r($this->queries, true)."</pre>");
 		if(!$this->db->transaction($this->queries)){
 			$res = false;
 			throw new Exception("“".print_r($this->queries,true)."” could not be performed.\n".$this->db->get_error());
@@ -214,18 +211,47 @@ class TracesHandler{
 
 	//so that if the augur reloads to give up without loss there's a penalty
 	//and not for oracle
-	public function augur_start_play(){
-
+	public function augur_start_play($rec_id, $rec_lang, $rec_level){
+		$this->reinit_queries();
+		$user_level = $this->user->get_lang_lvl($this->lang_iso->any_to_iso($rec_lang));
+		$stake = $this->sv->get_augur_divination_stake($this->user->userlvl, $rec_level, $user_level);
+		//create game
+		$this->add_query("INSERT INTO `parties` (`enregistrementID`, `idDevin`, `mise`, `nivPartie`, `nivCarte`) VALUES ('$rec_id', '".$this->user->id."', '$stake', '".$this->user->userlvl."', '$rec_level');");
+		//update stats
+		$this->add_query("UPDATE `stats` SET `nbEnregistrements_devin` = `nbEnregistrements_devin`+1, `sommeMises_devin`=`sommeMises_devin`+$stake WHERE `userid`='".$this->user->id."';");
+		$this->add_query("UPDATE `stats` SET `score_devin`='".$this->sv->get_augur_score_formula()."' WHERE `userid`='".$this->user->id."';");
+		$this->add_query($this->notif->addNotifGAME($this->user->id,
+		$this->messages['Augur_playing'],
+		$this->messages['img_oracle'],
+		$this->messages['notif']['Augur_playing']));
+		if(!$this->db->transaction($this->queries)){
+			$res = false;
+			throw new Exception("“".print_r($this->queries,true)."” could not be performed.\n".$this->db->get_error());
+		}
+		else{
+			$res = true;
+		}
+		return $res;
 	}
 
 	//don't find (end timer, either by giving up or not)
 	//augur & oracle
 	public function augur_loss(){
+		//update partie + durée (NULL = vidé le chrono) réussite non
+		//stats devin cf. start play (→ on ne change pas)
+
+		//enr + 1 tentative
+		//stats oracle +1 lecture → update score
+
 
 	}
 
 	//augur (and oracle) win
 	public function augur_win(){
+		//update partie + durée réussite oui
+		//stats devin : +1 nbMotsTrouves_devin + mise / update score
+		//enr +1 tentative + 1 succès
+		//oracle +1 lecture +1 succès → update score.
 
 	}
 }?>
diff --git a/models/userlvl.class.php b/models/userlvl.class.php
index 5666156..039acd0 100755
--- a/models/userlvl.class.php
+++ b/models/userlvl.class.php
@@ -49,7 +49,7 @@ class ScoreValues{
 				)
 			)
 		)";
-
+	const AUGUR_SCORE_FORMULA = "ROUND(`nbMotsTrouves_devin`/`nbEnregistrements_devin`*`sommeMises_devin`)";
 	private static $DRUID_STRINGS = array(0 => 'invalid',
 												1 => 'valid');
 
@@ -147,6 +147,10 @@ class ScoreValues{
 		return self::RECORDING_SCORE_FORMULA;
 	}
 
+	public function get_augur_score_formula(){
+		return self::AUGUR_SCORE_FORMULA;
+	}
+
 	public function get_stake($game_lvl, $card_lvl, $user_lvl, $won=true){
 		if(!is_int($game_lvl)){
 			$game_lvl = $this->unify_Lvl($game_lvl);
@@ -183,7 +187,9 @@ class ScoreValues{
 		return round($res);
 	}
 
-
+	public function get_augur_divination_stake($game_lvl, $card_lvl, $user_lvl){
+		return $this->get_stake($game_lvl, $card_lvl, $user_lvl, true);
+	}
 
 //quick and dirty rules consistance
 	public function forbid_count_to_string($lang){
diff --git a/score_traces.api.php b/score_traces.api.php
index 14b3dc8..5ffce17 100644
--- a/score_traces.api.php
+++ b/score_traces.api.php
@@ -20,7 +20,7 @@ else{
 					$th = new TracesHandler();
 					require_once('./models/card.class.php');
 					$card = new Card($_GET["card_id"]);
-					if($th->oracle_see_card($card, $_GET["game_level"])){
+					if($th->oracle_see_card($card)){
 						$res = true;
 						$msg = "";
 					}
diff --git a/views/diviner.game.html b/views/diviner.game.html
index 88c7b22..5eb96d3 100755
--- a/views/diviner.game.html
+++ b/views/diviner.game.html
@@ -1,4 +1,3 @@
-<script type="text/javascript" src="controllersJS/popup.js"></script>
 <script type="text/javascript" src="controllersJS/timer.js"></script>
 
 <?php $title = 'Devin';
@@ -21,7 +20,7 @@ function pressurise(){
 }
 
 function finChrono(){
-	document.location.href="index.php?mode=diviner.timeout"
+	document.location.href="index.php?mode=diviner.timeout&duration="+monChrono.getElapsedTime();
 	if(!monChrono.isRunning()){
 		$('#countdown').css('background-color', 'white');
 		$('#countdown').html("Buzz Buzz");
@@ -38,29 +37,7 @@ function give_up(){
 <div id="main-container">
 	<div id="jrForm">
 		<div class="form-jr">
-
-				 <?php
-				 //Si l'utilisateur a quitté la partie précédente
-				 if ( $this->lang ) {
-				 	foreach ($this->lang as $mess){
-				 	?>
-				 	<!--Popup Overlay -->
-					<div id="facebox">
-						<div class="content">
-							<div style="padding:5px;">
-								<h2><?php echo $lang['Becareful']; ?></h2><br/><h3><?php echo $lang[$mess]; ?></h3>
-								<button class="close" style="cursor: pointer; background:#000; color:white; text-align:center; font-weight:bold; position:absolute; bottom:20%; left:50%; padding:0 2px; width:200px; height:30px; line-height:20px">OK</button>
-								<div class="resume">&nbsp;</div>
-							</div>
-						</div>
-					</div>
-					<!-- Fin Popup -->
-				 	<?php
-				 	}
-				 	?>
-				 	<script>popUp();</script>
 				<?php
-				 }
 				// S'il y a des erreurs dans la class diviner.class.php
 				 if ( $this->errors ) {
 				 ?>
@@ -127,7 +104,7 @@ function give_up(){
 
 	//if (document.getElementById('motadeviner').value == document.getElementById('mot').value ) {
 		if (motentre == motadeviner) {
-				document.location.href="index.php?mode=diviner.result";
+				document.location.href="index.php?mode=diviner.result&duration="+monChrono.getElapsedTime();
 			}
 	// Si le devin donne une réponse fausse, on vide la zone de texte
 		else {
-- 
GitLab