joueur=$joueurQuiCommence; $this->grille=array(); $this->grille[]=array(0,0,0); $this->grille[]=array(0,0,0); $this->grille[]=array(0,0,0); } // Q 1.4 public function nbTours() { $nb=0; foreach($this->grille as $ligne) foreach($ligne as $cellule) if($cellule>0) $nb+=1; return $nb; } // Q 1.5 public function aQuiLeTour() { if($this->nbTours()%2==0) return $this->joueur; else return 3-$this->joueur; } // Q 1.6 public function partieGagnee() { for($i=0; $i<3; $i+=1) { // Test de la ligne $i if( $this->grille[$i][0]==$this->grille[$i][1] && $this->grille[$i][0]==$this->grille[$i][2] && $this->grille[$i][0]>0) return $this->grille[$i][0]; // Test de la colonne $i if( $this->grille[0][$i]==$this->grille[1][$i] && $this->grille[0][$i]==$this->grille[2][$i] && $this->grille[0][$i]>0) return $this->grille[0][$i]; } // Test des deux diagonales en même temps if(( ($this->grille[1][1]==$this->grille[0][0] && $this->grille[1][1]==$this->grille[2][2]) || ($this->grille[1][1]==$this->grille[2][0] && $this->grille[1][1]==$this->grille[0][2]) ) && $this->grille[1][1]>0) return $this->grille[1][1]; // Sinon, personne n'a gagné return 0; } // Q 1.7 public function cocheCase($joueur, $c, $l) { if($this->aQuiLeTour() == $joueur && !$this->partieGagnee()) $this->grille[$l][$c] = $joueur; } // Aide au débuggage public function _debug() { echo ""; } } // Exemple d'utilisation de notre classe : $p1 = new Morpion(1); echo "

État initial de notre objet

"; $p1->_debug(); $p1->cocheCase(1, 0, 0); echo "

État après que le joueur 1 ait coché la case 0,0

"; $p1->_debug(); $p1->cocheCase(2, 0, 1); echo "

État après que le joueur 2 ait coché la case 0,1

"; $p1->_debug(); $p1->cocheCase(1, 1, 0); $p1->cocheCase(2, 0, 2); $p1->cocheCase(1, 2, 0); echo "

État après quelques coups supplémentaires

"; $p1->_debug(); // Une autre partie ? $p2 = new Morpion(1); // Une partie dans laquelle le joueur 2 commence ? $p3 = new Morpion(2);