Clear Filters
Clear Filters

Info

This question is closed. Reopen it to edit or answer.

Is this psuedocode implementation correct? (TicTacToe)

1 view (last 30 days)
Hello there. I've been at this particular psuedocode set that is made for a tic-tac-toe game for quite sometime, and the MATLAB implementation indicates something wrong in this, but even with the explanation it gives, I still can't seem to figure that's wrong with it. Can anyone help out?
clc
clear
G = [0 0 0; 0 0 0; 0 0 0];
turn = 1;
rand(5)
if rand < 0.5
turn = -1;
end
gameOn = true;
plotTicTacToe(G)
while gameOn == true
if turn < 0
[r,c] = getMove(G,-1);
if r == 0 || c == 0
r = [0,G];
c = [0,G];
end
G(r,c) = -1;
turn = 1;
else
r = input('Give r');
c = input('Give c');
if G(r,c) ~= 0
continue
else
G(r,c) = 1;
turn = -1;
end
end
plotTicTacToe(G)
p = getWinner(G);
if p == 1
disp('You won!')
gameOn = false;
elseif p == -1
disp('Computer won!')
gameOn = false;
elseif p == 2
disp('Draw!')
gameOn = false;
end
end
Here is the rest of the code (functions) needed:
getWinner.m:
function[p1] = getWinner(p)
if p == -1
disp('Computer Wins!')
elseif p == 1
disp('You won!')
elseif p == 2
disp('Draw!')
elseif p == 0
disp('No winner yet.')
end
p1 = p;
getMove.m:
function[G, p] = getMove(r,c)
G = [0 0 0; 0 0 0; 0 0 0];
p = G;
s = 2 * p;
sumG = sum(G);
if sum(G) == s
c = find(sumG == s);
r = find(G(c) == 0);
elseif sum(G,3) == s
c = find(sumG(1,2,3) == s);
r = find(G(r,:) == 0);
elseif sum(diag(G)) == s
r = find(diagG(fliplr) == 0);
c = 4 - r;
else
r = 0;
c = 0;
end
plotTicTacToe.m:
function plotTicTacToe(G)
% plotTicTacToe(G) plot the Tic-tac-toe matrix on the command window
clc
fprintf(' \n');
fprintf(' | |\n');
fprintf(' %s | %s | %s \n', getSymb(G(1)), ...
getSymb(G(4)), ...
getSymb(G(7)));
fprintf(' ---+---+---\n');
fprintf(' %s | %s | %s \n', getSymb(G(2)), ...
getSymb(G(5)), ...
getSymb(G(8)));
fprintf(' ---+---+---\n');
fprintf(' %s | %s | %s \n', getSymb(G(3)), ...
getSymb(G(6)), ...
getSymb(G(9)));
fprintf(' | |\n');
fprintf(' \n');
end
Also getSymb.m (To get X,O,):
function[s] = getSymb(s)
disp('-1 = X, 1 = O, 0 = Empty Space');
p = input('Give me your mark: ');
if p == -1
s = 'X';
elseif p == 1
s = 'O';
elseif p == 0
s = ' ';
end
str = s;
Can anyone help out with corrections?
  3 Comments
Matt Amador
Matt Amador on 3 Nov 2017
It's just a repost. I am in dire need of help with this.

Answers (0)

This question is closed.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!