Welcome to the 8th PHP Coding Puzzle !

Tic Tac Toe Game

Game Description

Tic Tac Toe is a two-player game played on a 3×3 grid. The two players take turns placing their marks (‘X’ or ‘O’) on the grid. The first player to get three of their marks in a row (horizontally, vertically, or diagonally) wins the game. If all the spaces on the grid are filled and no player has won, the game is a tie.

Requirements

Write a PHP function called ticTacToe that allows two players to play a game of Tic Tac Toe. The function should display the current state of the board after each move, prompt the current player for their move (row and column), validate the move, update the board with the move, check if the game is over, and switch to the other player if the game is not over.

The function should use a two-dimensional array to represent the board. Each element of the array can be ‘X’, ‘O’, or ‘ ‘ (space), representing a mark on the board or an empty space.

The function should return the winning player (‘X’ or ‘O’) or ‘Tie’ if the game is a tie.

Example Usage

$result = ticTacToe();
if ($result == 'Tie') {
  echo "It's a tie!\n";
} else {
  echo "Player $result wins!\n";
}

Example Output

   1   2   3
1    |   |   
  ---+---+---
2    |   |   
  ---+---+---
3    |   |   
Player X's turn.
Enter row (1-3): 1
Enter column (1-3): 1
   1   2   3
1  X |   |   
  ---+---+---
2    |   |   
  ---+---+---
3    |   |   
Player O's turn.
Enter row (1-3): 2
Enter column (1-3): 2
   1   2   3
1  X |   |   
  ---+---+---
2    | O |   
  ---+---+---
3    |   |   
Player X's turn.
Enter row (1-3): 1
Enter column (1-3): 2
Invalid move. Please try again.
Player X's turn.
Enter row (1-3): 1
Enter column (1-3): 3
   1   2   3
1  X | X | O 
  ---+---+---
2    | O |   
  ---+---+---
3    |   |   
Player O's turn.
Enter row (1-3): 2
Enter column (1-3): 1
   1   2   3
1  X | X | O 
  ---+---+---
2  O | O |   
  ---+---+---
3    |   |   
Player X's turn.
Enter row (1-3): 3
Enter column (1-3): 1
   1   2   3
1  X | X | O 
  ---+---+---
2  O | O |   
  ---+---+---
3  X |   |   
Player X wins!

The solution is already available in the next page 😉 Feel free to share with us your solution here in comments or Github.

LEAVE A REPLY

Please enter your comment!
Please enter your name here