%tictactoe
clear all

%Initiate the board
A=['-','-','-';'-','-','-';'-','-','-']
tm=0; tu=0; %turns completed

while tm<6 %Matlab turns completed must be less than 6 for a new move
    
%Matlab turn
    fprintf('\nMy turn...\n')
    for k=1:40 %generates up to 40 sets of random numbers;
               %necessary in case Matlab guesses a box that is alreay taken.
        mr=ceil(3*rand); %Matlab row guess
        mc=ceil(3*rand); %Matlab column guess
        if A(mr,mc)=='-' %check that box is not taken
            A(mr,mc)='x'
            break %break for loop
        end %end if
    end %end for loop
tm=tm+1; %increment number of turns taken.

%check if Matlab wins
    for k=1:3
        if A(:,k)=='x'  % any column
            disp('I win! - 3 down.')
            tm=10; %set tm to 10
        elseif A(k,:)=='x' % any row
            disp('I win! - 3 across')
            tm=10;
        elseif A(1,1)=='x' & A(2,2)=='x' & A(3,3)=='x' %diagonal down
            disp('I win! - diagonal.')
            tm=10;
            break
        elseif A(1,3)=='x' & A(2,2)=='x' & A(3,1)=='x' %diagonal up
            disp('I win! - diagonal.')
            tm=10;
            break
        end %end if
    end %end for loop
if tm==5
    disp('Tie. Good game.')
    break
elseif tm==10
    disp('I am good!')
    break
end
    
%User's Turn
    fprintf('\nYour turn...\n')
     for k2=1:40 %loop enough times for user to choose a box that is not taken
        r=input('Enter the row for your move, r: ');
        c=input('Enter the column for your move, c: ');
        if A(r,c)=='-' %check if box is taken
            A(r,c)='o'
            break
        else
            disp('You cannot move there. Try again.')
        end 
    end
tu=tu+1; %increment number of turns taken.

%Check if user wins.
   
    if (A(1,1)=='o' & A(2,1)=='o' & A(3,1)=='o') | ...
            (A(1,2)=='o' & A(2,2)=='o' & A(3,2)=='o') |...
            (A(1,3)=='o' & A(2,3)=='o' & A(3,3)=='o') 
        disp('You win! - 3 down.')
        tm=11; %set tm to 11
    elseif (A(1,1)=='o' & A(1,2)=='o' & A(1,3)=='o') | ...
            (A(2,1)=='o' & A(2,2)=='o' & A(2,3)=='o') |...
            (A(3,1)=='o' & A(3,2)=='o' & A(3,3)=='o') 
        disp('You win! - 3 across.')
        tm=11;
     elseif A(1,1)=='o' & A(2,2)=='o' & A(3,3)=='o'  
        disp('You win! - diagonal.')
        tm=11;
     elseif A(1,3)=='o' & A(2,2)=='o' & A(3,1)=='o'  
        disp('You win! - diagonal.')
        tm=11; 
     end    
if tm==11
    disp('You got lucky.')
    break
end


end %end Matlab while loop