Connect four diagonal win condition

18 ビュー (過去 30 日間)
Timothy Kirkwood
Timothy Kirkwood 2020 年 11 月 9 日
コメント済み: Timothy Kirkwood 2020 年 11 月 10 日
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

回答 (1 件)

James Tursa
James Tursa 2020 年 11 月 10 日
編集済み: James Tursa 2020 年 11 月 10 日
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 件のコメント
James Tursa
James Tursa 2020 年 11 月 10 日
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.
Timothy Kirkwood
Timothy Kirkwood 2020 年 11 月 10 日
Thanks for the help James!!

サインインしてコメントする。

カテゴリ

Help Center および File ExchangeOperating on Diagonal Matrices についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by