绘图方块/游戏板c#

本文关键字:游戏 方块 绘图 | 更新日期: 2023-09-27 18:25:57

我想在C#上创建一个简单的正方形,用作游戏板。我正在尝试使用嵌套循环来完成这项工作,并研究了人们如何以这种方式制作正方形,但我很难理解它是如何完成的。这是我迄今为止为董事会编写的代码:

for (int x = 0; x < 8; x = x + 1)
            for (int y = 0; y < 8; y = y + 1)
                if (board[x, y] == SquareState.gotCheese)
                    Console.Write("C");
                else
                    Console.Write("*");

如果没有奶酪,它确实会打印出一个*,而C表示板上有奶酪,但它都是一行,看起来不像板。像这样:

*****************C*******

如果这对有任何帮助的话,这就是板的结构

static SquareState[,] board = new SquareState[8, 8];

绘图方块/游戏板c#

它是在一行中写入所有内容的,这是因为您现在正在告诉控制台创建一个新行。Console.write()只是将字符串与先例内联。

您的循环也应该是y-first循环,所以您将循环每个水平值(x),然后传递到一个新的垂直值。

    for (int y = 0; y < 8; y++){
        for (int x = 0; x < 8; x++){
            if (board[x, y] == SquareState.gotCheese)
                Console.Write("C");
            else
                Console.Write("*");
         }
         Console.WriteLine();
    }

如果你不交换周期,你的结果将是错误的,例如,在一个3乘3的正方形中,x从0到2,从左到右,y从上到下从0到2中,你将得到:

External FOR entering x = 0
    Internal FOR entering y = 0
        writing the 'cell' (0, 0)
    Internal FOR entering y = 1
        writing the 'cell' (0, 1)
    Internal FOR entering y = 2
        writing the 'cell' (0, 2)
    writing a new line
External FOR entering x = 1
    ...

这样做的结果将是:

(0,0)(0,1)(0,2)
(1,0)(1,1)(1,2)
(2,0)(2,1)(2,2)

这是错误的,应该是:

--------------------> x
(0,0)(1,0)(2,0)    |
(0,1)(1,1)(2,1)    |
(0,2)(1,2)(2,2)    |
                   V y

您需要在内部循环之后但在外部循环内部打印一条换行符。

Console.WriteLine(");

for (int x = 0; x < 8; x = x + 1){
            for (int y = 0; y < 8; y = y + 1){
                if (board[x, y] == SquareState.gotCheese)
                    Console.Write("C");
                else
                    Console.Write("*");
            Console.WriteLine("");
            }
}