Is this psuedocode implementation correct? (TicTacToe)
1 view (last 30 days)
Show older comments
Hello there. I've been at this particular psuedocode set 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?
Here is my attempted code:
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
2 Comments
Walter Roberson
on 2 Nov 2017
We do not have your plotTicTacToe or getMove or getWinner so we cannot execute the code to see what error message you are getting that you do not understand.
Answers (1)
Eric
on 6 Nov 2017
Did you implement these functions yourself? They seem to be all mixed up. For example, plotTicTacToe is asking for inputs, getMove is checking for winners, and getWinner is doing the winner displaying unnecessarily.
Here is some advice:
- plotTicTacToe: Should only display the board as it currently is in G, and should not change G (i.e. through getSymb)
- getMove: Get the next move. This depends on the second argument, i.e., whether it is the computer's turn (turn<0) or the player's. If the players, you will need to ask them where to play. If the computer's, this is where you would put the AI, from simple (using a randi to pick a valid spot) or complex (checking the board in order to go for wins or block wins). Either way, should output the row and column to place the play in.
- getWinner: Should check all rows/columns/diagonals for three in a row from the same player and declare that player the winner by what is output: -1 (com), 0 (none yet), 1 (player), 2 (tie).
- getSymb: Unnecessary.
Once you get these functions straightened out, let us know if you are still running into problems.
1 Comment
Eric
on 6 Nov 2017
I will add that lines 11-13 would be unnecessary if you choose the com's move well in your getMove function. Also, upon a second look, it seems you take care of the player's moves in the main function, so getMove is only for the computer's move.
See Also
Categories
Find more on Whos in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!