I have a 5x5 2D array of type Boolean and I want to check for vertical, horizontal, and diagonal bingo.
If values at those specific cells are set to "true", I get a bingo. Otherwise, I continue to play the game. I was looking for help to improve, or get feedback to completely re-haul this method for checking for a Bingo.
public int checkForBingo(int rowID, int colID)
{
bool winner = false;
for (int i = 0; i < 4; i++)
{
//checking verts and horiz
if (winner = (boardState[i, 0]) == true && (boardState[i, 1] == true)
&& (boardState[i, 2] == true) && (boardState[i, 3] == true)
&& (boardState[i, 4] == true))
break;
else if (winner = (boardState[0, i] == true) && (boardState[1, i] == true)
&& (boardState[2, i] == true) && (boardState[3, i] == true) &&
(boardState[4, i] == true))
break;
//checking diagonals
if (!winner)
{
if (boardState[2, 2] == true)
if ((winner = (boardState[0, 0] == true) && (boardState[1, 1] == true) &&
(boardState[3, 3] == true) && (boardState[4, 4] == true)))
break;
else if (!(winner = (boardState[0, 4] == true) && (boardState[1, 3] == true) &&
(boardState[3, 1] == true) && (boardState[4, 0] == true)))
break;
}
}
return 0;
}
For loop run from i=0 to 3 That means it's checking 4 rows only and in if condition you are checking for all 5 columns which is right. Change your for loop condition to
i <= 4
A few thing to note:
for (int i = 0; i < 5; i++)
less than 5 ( arrays are 0 based)You dont need to check for == true, a boolean value can be simple encapsulated in a if statement such as:
if (boardState[0, 4] && boardState[1, 3] && boardState[3, 1] && boardState[4, 0])
if
could lead to unwanted behavior(side effects) easy to forget is there. CheckForBingo
For comparison and learning purpose(myself included) I have written the method like this:
public bool CheckForBingo(bool[,] boardState)
{
bool haveWeWon = false;
//check horizotal
for (int i = 0; i < 5; i++)
{
haveWeWon = true;
for (int y = 0; y < 5; y++)
{
if (!boardState[i, y])
{
haveWeWon = false;
break;
}
}
if(haveWeWon)
{
return haveWeWon;
}
}
if (!haveWeWon)
{
//check vertical
for (int i = 0; i < 5; i++)
{
haveWeWon = true;
for (int y = 0; y < 5; y++)
{
if (boardState[y, i])
{
haveWeWon = false;
break;
}
}
if (haveWeWon)
{
return haveWeWon;
}
}
}
//check the middle - if false dont bother checking diagonal
if (boardState[2, 2])
{
if (!haveWeWon)
{
//check top left diagonal
for (int i = 0; i < 5; i++)
{
haveWeWon = true;
if (!boardState[i, i])
{
haveWeWon = false;
break;
}
}
if (haveWeWon)
{
return haveWeWon;
}
}
if (!haveWeWon)
{
//check top right diagonal
for (int i = 4; i >= 0; i--)
{
haveWeWon = true;
if (!boardState[i, i])
{
haveWeWon = false;
break;
}
}
if (haveWeWon)
{
return haveWeWon;
}
}
}
return false;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.