Tic Tac Toe Matrix Check
8 views (last 30 days)
Show older comments
Hello everyone. I'm VERY new to MatLab and the world of coding and I'm confused as to how I move forward from where I am at the moment. My problem is this: I've got a Tic-Tac-Toe game where the computer starts by randomly selecting a spot in a 3x3 matrix. I then make my turn, and the computer goes again and so forth. However, The computer will at times pick a spot that is already taken, and I'm wondering how I can write a statement that will tell the computer to check the matrix for spot's that are available and not taken?
my code for CPU making a move:
CPUMove = randsample(11:19,1);
switch (CPUMove)
case 11
Board (1,1) = 0;
case 12
Board (1,2) = 0;
case 13
Board (1,3) = 0;
case 14
Board (2,1) = 0;
case 15
Board (2,2) = 0;
case 16
Board (2,3) = 0;
case 17
Board (3,1) = 0;
case 18
Board (3,2) = 0;
case 19
Board (3,3) = 0;
end
Code for Player to make a move:
X = input (' Human Player, make your move. Pick a spot on the board 1-9: ');
switch (X)
case 1
Board(1,1) = 1;
case 2
Board (1,2) = 1;
case 3
Board (1,3) = 1;
case 4
Board (2,1) = 1;
case 5
Board (2,2) = 1;
case 6
Board (2,3) = 1;
case 7
Board (3,1) = 1;
case 8
Board (3,2) = 1;
case 9
Board (3,3) = 1;
end
if Board (1,1) == 0
Board (1,1) ~= 1;
elseif Board (1,2) == 0
Board (1,2) ~= 1;
elseif Board (1,3) == 0
Board (1,3) ~= 1;
elseif Board (2,1) == 0
Board (2,1) ~= 1;
elseif Board (2,2) == 0
Board (2,2) ~= 1;
elseif Board (2,3) == 0
Board (2,3) ~= 1;
elseif Board (3,1) == 0
Board (3,1) ~= 1;
elseif Board (3,2) == 0
Board (3,2) ~= 1;
elseif Board (3,3) == 0
Board (3,1) ~= 1;
end
0 Comments
Answers (1)
Jan
on 20 Sep 2017
Edited: Jan
on 20 Sep 2017
Note that
Board (1,1) ~= 1;
Compares the contents of this elements to be different from 1, but nothing is assigned. Therefore this line, and the complete block of code, is useless.
A simplification of the first part:
CPUMove = randsample(11:19,1);
switch (CPUMove)
case 11
Board (1,1) = 0;
...
is:
CPUMove = randsample(11:19,1);
Board(CPUMove - 10) = 0;
But then the fields on the board are ordered columnwise, such that CPUMove=12 means Board(2,1).
This can be applied to the other part also.
2 Comments
Jan
on 21 Sep 2017
Board = NaN(3,3);
disp(Board);
CPUMove = 4;
Board(CPUMove) = 0;
disp(Board);
YouMove = 5;
Board(YouMove) = 1;
disp(Board);
Clear? You can use "linear indexing" to avoid the bunch of switch branches.
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!