【问题标题】:2D array chess board二维阵列棋盘
【发布时间】:2016-04-13 14:27:30
【问题描述】:

我正在尝试使用 2D 数组将类似国际象棋的设计制作成控制台。 我用“|”做了边框和“-”来设计一个运动场。 但是,我无法切换字段的颜色(白色|黑色|白色) 这是我的代码(没有改变编号字段的颜色)

public class Program
{
    static void Main(string[] args)
    {
        int[] array = new int[10];
        int[,] array2 = new int[6, 9];

        for(int i = 0;i < array2.GetLength(0); i++)
        {
            if (i == array2.GetLength(0)-1 || i == 0)
            {
                for (int h = 0; h < array2.GetLength(1); h++)
                    decidingColors(false);
                    Console.Write("|" + "-");
            }
            else
            for (int x = 0;x < array2.GetLength(1); x++)
            {
                    decidingColors(false);
                Console.Write("|");
                    decidingColors(true);
                Console.Write(array2[i, x]);

            }
            decidingColors(false);
            Console.Write("|");
            Console.WriteLine();
        }
        Console.ReadLine();
    }
    public static void decidingColors(bool wentThrough)
    {
        if(wentThrough == true)
        {
            Console.BackgroundColor = ConsoleColor.White;
            Console.ForegroundColor = ConsoleColor.Black;
        }
        else
        {
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
        }

    }
}

我尝试使用不同的方法,但它总是以某种方式进入代码并破坏它。你有好的解决方案吗?

提前致谢!

【问题讨论】:

  • 我通常喜欢为板上的每个方块制作自定义类。方格可以包含很多信息,包括方格上的棋子。它将使代码更简单。

标签: c# arrays console


【解决方案1】:

您的循环可能不会完全按照您的想法打印。您应该使用索引h 在循环中添加花括号,以便您的缩进与实际逻辑相匹配。

for (int h = 0; h < array2.GetLength(1); h++) { 
   decidingColors(false);
   Console.Write("|" + "-");
}

【讨论】:

  • 当我改变一些东西时它滑出来了,已经修复了。谢谢
【解决方案2】:

您可以通过使用 x % 2 == 0 来确定需要的奇数或偶数元素来设置备用。

for (int x = 0;x < array2.GetLength(1); x++)
{
    decidingColors(false);
    Console.Write("|");
    decidingColors(x % 2 == 0);
    Console.Write(array2[i, x]);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-26
    • 2015-01-30
    • 1970-01-01
    • 2011-01-03
    • 2012-04-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多