我有这个重复的代码,但是我不确定如何只用一种方法就能做到。

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


我可以将returns和resetCounter()全部放入1种方法中。但是,如何确保for循环对于垂直/水平而言是不同的。我假设是通过提供参数,然后检查是否将“垂直”或“水平”作为参数。但是我不确定如何使它真正起作用。

谢谢。

最佳答案

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;
    }

关于c# - 重复2种方法制成1种方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29921019/

10-12 05:17