Terminating a game of tic tac toe if two entries are entered in the same cell
Show older comments
As the title suggests, i am finishing up making a game of tic tac toe , and want to write some code at the end that will terminae/end the game if the players try and put more than one X or o in each space. This is what I have currently .
TTCboard = zeros(3,3);
% for creating the standard tic-tac-toe board in green
figure
plot([0 3],[-1 -1], 'g','linewidth',1);% creates top horizontal line in board
hold on
plot([2 2],[0 -3], 'g','linewidth',1)% creates right-most vertical line
plot([0 3],[-2 -2], 'g','linewidth',1)% creates bottom horizontal line
plot([1 1],[0 -3], 'g','linewidth',1)% creates left-most vertical line
axis off % keeps the X & y-axis off, creating a better looking natural board
hold off% ensures later commands are added to existing board
xticks([0 1 2 3]); yticks([0 1 2 3]);
xticklabels([]); yticklabels([]);
player = 'X' % designates the first player as X
while true % when it is player x's turn,
fprintf('%s click to place a piece\n', player); % creates X in the cell clicked on
[x, y] = ginput(1);
x = floor(x)+0.43 ;
y = floor(y)+0.5;
text(x,y,player, 'horizontalalignment', 'center', "FontSize",24);% gives specific parameters to the X on the board
xticks([0 1 2 3]); yticks([0 1 2 3]);
xticklabels([]); yticklabels([]);
player2 = 'O' % Designates the 2nd players turn
while true
fprintf('%s click to place a piece\n', player2);
[x, y] = ginput(1);
x = floor(x)+0.43 ;
y = floor(y)+0.5;
text(x,y,player2, 'horizontalalignment', 'center', "FontSize",24);
break;
end
end
1 Comment
John Chilleri
on 15 Mar 2021
One possibility is to create an additional 3x3 matrix of zeros, and whenever an X or O is added, change the corresponding entry to 1. Then implement a simple check before placing Xs and Os that ensures the matrix entry is 0 (meaning available).
Accepted Answer
More Answers (0)
Categories
Find more on Strategy & Logic 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!