lucycopp
lucycopp

Reputation: 213

Drawing square/game board c#

I want to create a simple square on C# which will be used as a game board. I am trying to do it using nested loops and have looked into how people make squares this way however I am having difficulty understanding how its done. This is my code so far for the board:

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("*");

It does print out a * if there is no cheese and a C is there is cheese on the board, however its all in a line and doesn't look like a board. Like this:

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

This is the structure for the board if its any help

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

Upvotes: 1

Views: 4163

Answers (3)

Josep Valls
Josep Valls

Reputation: 5560

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("");
            }
}

Upvotes: 2

Gianmarco
Gianmarco

Reputation: 2552

The fact that it is writing all in line is because you are now telling the console to create a new line. Console.write() just append strings inline with the precedent.

You for cycle should also be an y-first cycle, so you will cycle each horizontal value (x) and then pass to a new vertical one.

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

If you don't swap the cycles your result will be wrong, for example in a 3 by 3 square where x goes from 0 to 2, from left to right and y goes from 0 to 2 from top to bottom, you will have:

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
    ...

The result of this will be:

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

That is wrong, it should be:

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

Upvotes: 3

nicomp
nicomp

Reputation: 4657

You need to print a newline after the inner loop but inside the outer loop.

Console.WriteLine("");

Upvotes: 2

Related Questions