Search code examples
c#c++.netalgorithmbitboard

Converting C++ function to C#


I'm trying to convert c++ funtion to c#, but I'm failing for the second straight hour. Need help:/ The function is taken from this question

bool haswon(unsigned __int64 newboard)
{
    unsigned __int64 y = newboard & (newboard >> 6);
    if (y & (y >> 2 * 6)) // check \ diagonal
        return true;
    y = newboard & (newboard >> 7);
    if (y & (y >> 2 * 7)) // check horizontal -
        return true;
    y = newboard & (newboard >> 8);
    if (y & (y >> 2 * 8)) // check / diagonal
        return true;
    y = newboard & (newboard >> 1);
    if (y & (y >> 2))     // check vertical |
        return true;
    return false;
}

Here's my c# one:

    bool HasWon(ulong newboard)
    {
        ulong y = newboard & (newboard >> 6);
        if ((y & (y >> 2 * 6)) > 0) // check \ diagonal
            return true;
        y = newboard & (newboard >> 7);
        if ((y & (y >> 2 * 7)) > 0) // check horizontal -
            return true;
        y = newboard & (newboard >> 8);
        if ((y & (y >> 2 * 7)) > 0) // check / diagonal
            return true;
        y = newboard & (newboard >> 1);
        if ((y & (y >> 2 * 7)) > 0)    // check vertical |
            return true;
        return false;
    }

But It doesn't work! Looks like a trivial thing, but I'm totally lost. Thanks for help


Solution

  • It looks like a simple copy/paste error. Your last two lines were not shifting y by twice the amount of newboard:

    private static bool isWon(ulong board)
    {
        // Check / diagonal
        ulong y = board & (board >> 8);
        if ((y & (y >> 2 * 8)) > 0) return true;
    
        // Check - horizontal
        y = board & (board >> 7);
        if ((y & (y >> 2 * 7)) > 0) return true;
    
        // Check \ diagonal
        y = board & (board >> 6);
        if ((y & (y >> 2 * 6)) > 0) return true;
    
        // Check | vertical
        y = board & (board >> 1);
        if ((y & (y >> 2)) > 0) return true;
    
        return false;
    }