# 问题内容:

am currently working on a Gomoku game for windows and am using MFC. Am currently working on the winning algorithm for diagonals. My horizontal and vertical work just fine. Am hoping someone can help shade some light on where my logic is wrong. here is the code:

``````bool CMainFrame::isWinner(int player){
for (int row = 0; row < data.size(); row++) {
for (int col = 0; col < data.size(); col++) {
if (data[row][col].color == player && data[row + 1][col + 1].color == player && data[row + 2][col + 2].color == player && data[row + 3][col + 3].color == player && data[row + 4][col + 4].color == player) {
CheckForGameOver(player); //function that simply shows message box of winning piece
return true;
}
}
}
}
``````

It only works in the diagonal connected to the top left corner. Fairly new to programming so any help will greatly be appreciated.

## 问题评论:

Don’t use numbers like `15` in your loops, use meaningful named constants, or derive the value from the size of your data. A Go board is 19 x 19, so I’m not sure your test stays in bounds.
thanks for the response. my board is 15 X 15. oh I just edited out my data.size(). I use it in my code but it still doesn’t seem to change anything.
– Elijah
1 hour ago
Then you are definitely going out of bounds.
what may be the reason that the only diagonal that works is the one that starts from the top left corner?
– Elijah
1 hour ago
sorry I don’t understand how it goes out of bounds. do you mind explaining it to me?
– Elijah
58 mins ago

# 答案:

## 答案1:

The rules of this game is that 5 items should match in a row, or in a column, or in a diagonal line. Just compare each row, column, and diagonal line to see if 5 items match, and return true. Otherwise the function should return false.

``````bool won(std::vector<std::vector<data_t>> &data)
{
for(size_t row = 0; row < data.size(); row++)
for(size_t col = 0; col < data.size() - 5; col++)
{
int win = 0;
for(int i = 1; i < 5; i++)
if(data[row][col].color == data[row][col + i].color)
win++;
if(win == 4) //<-indicates 5 items matched in a row
return true;
}

//switch row and column:
for(size_t col = 0; col < data.size() - 5; col++)
for(size_t row = 0; row < data.size(); row++)
{
int win = 0;
for(int i = 1; i < 5; i++)
if(data[row][col].color == data[row + i][col].color)
win++;
if(win == 4) //<-indicates 5 items matched in a column
return true;
}

//check diagonal lines from top-left to bottom-right
for(size_t col = 0; col < data.size() - 5; col++)
for(size_t row = 0; row < data.size() - 5; row++)
{
int win = 0;
for(int i = 1; i < 5; i++)
if(data[row][col].color == data[row + i][col + i].color)
win++;
if(win == 4)
return true;
}

//lastly check diagonal lines from top-right to bottom-left

return false;
}
``````

## 原文地址：

https://stackoverflow.com/questions/47754747/gomoku-diagonal-winning-condition