In: Computer Science
**MATLAB Code only
Please create a MATLAB script that is a TIC-TAC-TOE game. Please keep it simple, but there is no other rules. Thank you.
ANSWER
THIS TIC-TAC-TOE GAME CODE WRITTEN IN MATLAB CODE ONLY ::
THIS GAME INVOLVE Four.m Files Which are Below :
function tictactoe(f_user1,f_user2)
% clear all
% clc
%addpath()
user1=f_user1;
user2=f_user2;
user1wins=0;
user2wins=0;
user2loss=0;
user1loss=0;
ties=0;
user1_forfiet=0;
user2_forfiet=0;
for games=1:1000
%%
board=zeros(3,3);
turn=randi([1 2],1,1);
p=0;
while p==0
turn=turn+1;
if rem(turn,2)~=0
userboard=user1(board,-1);
else
userboard=user2(board,1);
end
p=legalmove(board,userboard,p);
if p~=3
p=winner(userboard);
end
board=userboard;
end
%%
if p==3
if rem(turn,2)==0
user2_forfiet=user2_forfiet+1;
user2loss=user2loss+1;
user1wins=user1wins+1;
else
user1_forfiet=user1_forfiet+1;
user1loss=user1loss+1;
user2wins=user2wins+1;
end
elseif p==2
ties=ties+1;
elseif p==-1
user1wins=user1wins+1;
user2loss=user2loss+1;
else
user2wins=user2wins+1;
user1loss=user1loss+1;
end
end
user1_stats=[user1wins user1loss ties
user1_forfiet]
user2_stats=[user2wins user2loss ties
user2_forfiet]
--------------------------------------------------------------------------------------------------------------------------------------------------
function p=legalmove(board,userboard,p)
if any(size(userboard)~=size(board))
p=3;
elseif sum(sum(abs(board-userboard)))~=1;
p=3;
else
p=p;
end
----------------------------------------------------------------------------------------------------------------------------------------------------
function p = winner(X)
% p = winner(X) returns
% p = 0, no winner yet,
% p = -1, user 1 has won,
% p = 1, user 2 has won,
% p = 2, game is a draw.
for p = [-1 1]
s = 3*p;
win = any(sum(X) == s) || any(sum(X') == s) || ...
sum(diag(X)) == s || sum(diag(fliplr(X))) == s;
if win
return
end
end
p = 2*all(X(:) ~= 0);
-----------------------------------------------------------------------------------------------------------------------------------------------------
function B=game(B,x)
r=randi(3,1);
c=randi(3,1);
while B(r,c) ~= 0
r=randi(3,1);
c=randi(3,1);
end
if B(r,c) == 0
r=randi(1,3);
elseif B(r,c) ~= 0
c=randi(1,3);
end
B(r,c)=x;