This document contains the code for a tic-tac-toe game. It defines functions to check for a tie or win based on rows, columns, or diagonals of the board. It also contains functions to print the board, get user moves, and update the board. The main code uses these functions in a loop to run the game until there is a win or tie.
This document contains the code for a tic-tac-toe game. It defines functions to check for a tie or win based on rows, columns, or diagonals of the board. It also contains functions to print the board, get user moves, and update the board. The main code uses these functions in a loop to run the game until there is a win or tie.
1 function tictactoe 2 M = zeros(3); 3 p = -1; c = 'O X'; 4 disp('TIC-TAC-TOE!'); 5 while true 6 p = -p; printBoard(M); 7 fprintf('Player %c''s move:\n',c(p + 2)); 8 mR = input('Enter row number (1-3): '); 9 mC = input('Enter col number (1-3): '); 0 if checkRC(mR,mC,M) == 0 1 fprintf('Invalid move!\n'); p = -p; 2 else 3 M = changeRC(mR,mC,p,M); 4 if checkCol(M) || checkRow(M) || ... 5 checkDiag1(M) || checkDiag2(M), 6 fprintf('Player %c wins!\n',c(p + 2)); 7 break; 8 end 9 if checkTie(M) 0 fprintf('It''s a tie!\n'); 1 break; 2 end 3 end 4 end 5 printBoard(M); 6 function F = checkTie(M) 7 F = sum(sum(abs(M))) == 9; 8 end 9 function F = checkRC(R,C,M) 0 F = R > 0 && R < 4 && C > 0 ... 1 && C < 4 && M(R,C) == 0; 2 end 3 function F = changeRC(R,C,N,M) 4 M(R,C) = N; F = M; 5 end 6 function F = checkCol(M) 7 F = max(abs(sum(M,1))) == 3; 8 end 9 function F = checkRow(M) 0 F = max(abs(sum(M,2))) == 3; 1 end 2 function F = checkDiag1(M) 3 F = abs(trace(M)) == 3; 4 end 5 function F = checkDiag2(M) 6 F = abs(sum(M([3 5 7]))) == 3; 7 end 8 9 0 function printBoard(M) 1 b = [' +-+-+-+';' | | | |'; 2 ' +-+-+-+';' | | | |'; 3 ' +-+-+-+';' | | | |'; 4 ' +-+-+-+']; 5 b(2:2:6,4:2:8) = c(M + 2); 6 disp(b); 7 end 8 end 9 0