Beginner chess rook movement interruption in function [duplicate]

拜拜、爱过 提交于 2019-12-12 00:33:02

问题


How can I make a function to find if there are any letters (pieces) in between the king and the rook? I don't understand how to make the function stop when it finds something in between. Because as of now it shows that the king is in check even though it is not.

My function moves 1 by 1 in the x and y axis on a 2 dimensional char array until it either finds something colliding (not an empty space ( !='*')) or until it ends and finds a king ('k')

void rook_white(piece A[])                                      // does WR check BK
{
    bool check = false;
    for(int x=0; x<8; x++)
    {
        for(int y=0; y<8; y++)
        {
            if ((!A[t_i].field[m_x-x][m_y] == '*') || (!A[t_i].field[m_x+x][m_y] == '*') ||
                    (!A[t_i].field[m_x][m_y+y] == '*') || (!A[t_i].field[m_x][m_y-y] == '*'))
            {
                break;
            }
            if( A[t_i].field[m_x-x][m_y] == 'k' || A[t_i].field[m_x+x][m_y] == 'k' ||
                    A[t_i].field[m_x][m_y+y] == 'k' || A[t_i].field[m_x][m_y-y] == 'k')
            {
                check = true;
            }
        }
    }
    if (check == true)
    {
        ofstream fr(FVR,ios::app);
        fr << "Black is in check " << t_i << endl;
    }
}

The input file is something along the lines like this:

********
***k****
********
********
***p****
********
********
***R****

k being the black king
R being the white rook
p being the black pawn


回答1:


Your logic looks totally wrong.

But one thing you seem to misunderstand is that break only breaks out of one loop; you're still inside the outer loop, and that loop keeps going.

If you need to break out of more than one loop at a time, that's one of the standard modern uses of goto:

    for(...) {
        for(...) {
            if(reason) { goto loop_exit; }
        }
    }
    // If I wanted to do something special on normal termination, it goes here
loop_exit:
    // Stuff to be done after exiting the loop goes here.

(the label loop_exit can be called more or less anything, although something informative helps with readability)

As a bonus, I've also annotated the above code to demonstrate another modern use of goto: to emulate the for-else construct, where there's a block of code that should only happen when the loop exits normally.

But just to emphasize the point, making this change will not make your function correct, because as I said, it looks like the logic is totally wrong.



来源:https://stackoverflow.com/questions/33268987/beginner-chess-rook-movement-interruption-in-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!