tictactie moka test

<?php class TicTcaToe { // $moves is 2 dimension array to record the moves by player // [ 0,0 0,1 0,2] // [ 1,0 1,1 1,2] // [ 2,0 2,1 2,2] // $scores is to save the players score by transform the 2 dimension // array into 2 dimention array with the first key is x or y // y0 y1 y2 // x0 [ 0,0 0,1 0,2] // x1 [ 1,0 1,1 1,2] // x2 [ 2,0 2,1 2,2] public $moves; public $boardSize; public $player2Id; public $player1Id; public $playerWinId; public $scores; public $gameOver; public function __construct($boardSize, $player1Id, $player2Id) { $this->boardSize = $boardSize; $this->player1Id = $player1Id; $this->player2Id = $player2Id; $this->scores = [ $player1Id => ['x' => [], 'y' => [] ], $player2Id => ['x' => [], 'y' => [] ], ]; $this->gameOver = false; } public function makeMove($playerId, $posX, $posY){ // check if the game already won/end if($this->gameOver) { echo "The game already won by Player $playerId !"; return false; } // check the player ID given is match with the initiation if(! isset($this->scores[$playerId])) return false; // check if position available on board if($posX < 0 || $posX >= $this->boardSize || $posY < 0 || $posY >= $this->boardSize) return false; // record the moves on board if(!isset($this->moves[$posX])) { $this->moves[$posX] = []; } $this->moves[$posX][$posY] = $playerId; // adding moveto scores if(! isset($this->scores[$playerId]['x'][$posX])){ $this->scores[$playerId]['x'][$posX] = 0; } if(! isset($this->scores[$playerId]['y'][$posY])){ $this->scores[$playerId]['y'][$posY] = 0; } // increment player scores by 1 $this->scores[$playerId]['x'][$posX]++; $this->scores[$playerId]['y'][$posY]++; if($this->scores[$playerId]['x'][$posX] == $this->boardSize || $this->scores[$playerId]['y'][$posY] == $this->boardSize){ $this->gameOver = true; $playerWinId =$playerId; echo "Player $playerId win the game! \n"; return true; } echo "Player $playerId make move on $posX, $posY! \n"; return true; } } // [ 1 1 2] // [ 2 1 2] // [ 1 1 2] // [ 0,0 0,1 0,2] // [ 1,0 1,1 1,2] // [ 2,0 2,1 2,2] $game = new TicTcaToe(3, 1, 2); $game->makeMove(1, 0, 0); // Player 1 make move on 0, 0 $game->makeMove(2, 0, 2); // Player 2 make move on 0, 2 $game->makeMove(1, 0, 1); // Player 1 make move on 0, 1 $game->makeMove(2, 1, 0); // Player 2 make move on 1, 0 $game->makeMove(1, 1, 1); // Player 1 make move on 1, 1 $game->makeMove(2, 1, 2); // Player 2 make move on 1, 2 $game->makeMove(1, 2, 0); // Player 1 make move on 2, 0 $game->makeMove(2, 2, 2); // var_dump($game->scores); // Player 2 win the game $game->makeMove(1, 2, 1); // The game already won the game by Player 2

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.