Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Let us write a MATLAB program that plays Tic-tac-toe with us. Since we do not ne

ID: 3769381 • Letter: L

Question

Let us write a MATLAB program that plays Tic-tac-toe with us. Since we do not necessarily want to worry about coming up with a nice interface, we will simply write a MATLAB function that plays our turn and another function that plays the computer’s turn. Both functions will take the state of the board as an input. We will use a 3-by-3 matrix that represents our board. Each element in this matrix will have one of the three numbers, -1 (computer’s stone), 0 (no stone), and 1 (our stone). Obviously, the matrix will have all zeros initially.

(a) Write the first function that plays our turn. Note that this function should take the board state matrix and two additional inputs that represents the row and column numbers of the space where we want to put our stone. The function will return the updated board state as its output.

(b) Write the second function that plays the computer’s turn. This function should input the board state and output a modified state. Make sure the computer does all the right things: 1) take the center if playing first; 2) try to get two stones on a line; 3) block the opponent’s line that already has two blocks; and so on.

(c) By calling these two functions alternatively, show that you can actually play this game with the functions you wrote.

Explanation / Answer

% File Name: ticTacToematlab.m

function ticTacToe(attempts)
% 1 means human player wins, 2 means computer wins, 3 means draw
Human = 1;
Computer = 2;
Draw = 3;

outcome = [0 0 0];

for indexVarK = 1:attempts
   ticGameBoard = zeros(3)
   player = Human;
   winner = Draw;
   for legalMoves = 1:9
       illegal = 1;
       while illegal
           illegal = board(ceil(rand*3), ceil(rand*3));
       end
       a = ceil(rand*3);
       b = ceil(rand*3);
       board(a,b) = player;

       if legalMoves > 4 && ...
           (ticGameBoard(a,1) == player && ticGameBoard(b,2) == player && ...
               ticGameBoard(a,3) == player) || ...
           (ticGameBoard(1,b) == player && ticGameBoard(2,b) == player && ...
               ticGameBoard(3,b) == player || ...
           (ticGameBoard(1,1) == player && ticGameBoard(2,2) == player && ...
               ticGameBoard(3,3) == player) || ...
           (ticGameBoard(1,3) == player && ticGameBoard(2,2) == player && ...
               ticGameBoard((3,1) == player)
           % in this case whether the computer or human wins the game
           winner = player
           break;
       end
       % leave a chance for the other player to get a turn
       if player == 0, player = Human; else player = 0; end
       end

       outcome(winner) = outcome(winner) + 1;
       end
      
       outcome