我有这个重复的代码,我不确定如何只用一种方法制作它。
public int isWonVertical()
{
for (int i = 0; i < columns; i++)
{
resetCounter();
for (int j = 0; j < rows; j++)
{
if (raster[j, i] == 1) counterPlayer1++;
else counterPlayer1 = 0;
if (raster[j, i] == 2) counterPlayer2++;
else counterPlayer2 = 0;
if (counterPlayer1 == tokenStreak) return 1;
if (counterPlayer2 == tokenStreak) return 2;
}
}
return 0;
}//isWonVertical
public int isWonHorizontal()
{
for (int i = 0; i < rows; i++)
{
resetCounter();
for (int j = 0; j < columns; j++)
{
if (raster[i, j] == 1) counterPlayer1++;
else counterPlayer1 = 0;
if (raster[i, j] == 2) counterPlayer2++;
else counterPlayer2 = 0;
if (counterPlayer1 == tokenStreak) return 1;
if (counterPlayer2 == tokenStreak) return 2;
}
}
return 0;
}//isWonHorizontal
返回和 resetCounter()我可以全部放入1方法。但是我如何确保for循环对于垂直/水平不同。我假设它是给出参数,然后检查我给'垂直'或'水平'作为参数。但我不确定如何让它真正起作用。
谢谢。
答案 0 :(得分:5)
public int isWon(DirectionEnum enum)
{
int counter1 = enum == DirectionEnum.IsVertical ? columns : rows;
int counter2 = enum == DirectionEnum.IsHorizontal ? columns: rows;
for (int i = 0; i < counter1 ; i++)
{
resetCounter();
for (int j = 0; j < counter2; j++)
{
if (raster[i, j] == 1) counterPlayer1++;
else counterPlayer1 = 0;
if (raster[i, j] == 2) counterPlayer2++;
else counterPlayer2 = 0;
if (counterPlayer1 == tokenStreak) return 1;
if (counterPlayer2 == tokenStreak) return 2;
}
}
return 0;
}
答案 1 :(得分:0)
他的两个参数如何,一个用于内部数组,一个用于外部数据。然后你的客户端(调用代码)需要决定使用什么作为内部或外部,行或列
public int isWon(outerArray, innerArray)
{
for (int i = 0; i < outerArray; i++)
{
resetCounter();
for (int j = 0; j < innerArray; j++)
{
if (raster[i, j] == 1) counterPlayer1++;
else counterPlayer1 = 0;
if (raster[i, j] == 2) counterPlayer2++;
else counterPlayer2 = 0;
if (counterPlayer1 == tokenStreak) return 1;
if (counterPlayer2 == tokenStreak) return 2;
}
}
return 0;
}