Connect four diagonal win condition

23 views (last 30 days)
Timothy Kirkwood
Timothy Kirkwood on 9 Nov 2020
Commented: Timothy Kirkwood on 10 Nov 2020
Hi there,
Newbie here and have been lurking these forums learning all sorts of new things, so thanks in advance for all that.
Currently working on programming a simple two player game of connect four. Currently all works fine, im just having trouble implementing a win condition for either diagonals.
All of the following code sits within a while loop and works fine. However i cant see where im going wrong bellow, Thanks again!
the code i have is :
%diagonal win negative grad
rows=6
columns = 7
fours = 1:3
for r = 1:(rows-3)
for c = 1:(columns-3)
if board(r,c) == board((r+fours),(c+fours))
winner = board(r,c);
endCondition = 1;
end
end
end

Answers (1)

James Tursa
James Tursa on 10 Nov 2020
Edited: James Tursa on 10 Nov 2020
board((r+fours),(c+fours)) is not the diagonal going from board(r,c) to board(r+3,c+3). It is the 2D sub-matrix containing everything in the intersection of rows in (r+fours) and columns in (c+fours).
Also note that your intended loop only looks for diagonals going "down and right". But a winning condition can go "up and right" also, so you will need additional logic for that case.
You can get the diagonals you want with linear indexing. E.g., for the "down and right" diagonal:
[M,N] = size(board);
connect = 4; % number of connected values needed for win
xstart = r + (c-1)*N; % starting linear index of the board(r,c) element
x = xstart + (0:connect-1)*(M+1); % linear indexes of diagonal elements going down and right
dr = board(x); % the diagonal elements going down and right
And for the "up and right" case:
x = xstart + (0:connect-1)*(M-1); % linear indexes of diagonal elements going up and right
ur = board(x); % the diagonal elements going up and right
In each case you would need to have your loop indexing correct so you don't run off the side of the board array.
  3 Comments
James Tursa
James Tursa on 10 Nov 2020
Yes. When you have a vector in only one of the index spots, you get a vector result and things work as you expected. But when you have a vector in both index spots, you get a 2D matrix result, and that is why your logic failed as you suspect.
I have shown you a way to extract the diagonal elements you want all at once, but of course you could simply write another inner loop to accomplish your goals.

Sign in to comment.

Categories

Find more on Operating on Diagonal Matrices 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!