Reputation: 13
I'm trying to make a chess-like design into a console using 2D arrays. I made borders with "|" and "-" to design a playfield. However, I have trouble with switching colors of the field ( white | black | white) Here's my code (without the changing of colors on the numbered fields)
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;
}
}
}
I tried using different methods but it always got somehow into the code and broke it. Do you have a good solution?
Thanks in advance!
Upvotes: 1
Views: 1455
Reputation: 1081
You can set alternate by using x % 2 == 0 to determine odd or even element where needed.
for (int x = 0;x < array2.GetLength(1); x++)
{
decidingColors(false);
Console.Write("|");
decidingColors(x % 2 == 0);
Console.Write(array2[i, x]);
}
Upvotes: 1
Reputation: 3130
Your looping may not be printing exactly what you think it is printing. You should add curly braces to your loop with index h
so that your indentation matches the actual logic.
for (int h = 0; h < array2.GetLength(1); h++) {
decidingColors(false);
Console.Write("|" + "-");
}
Upvotes: 2