'Magic box game C#

This is an example that we took about building a magic box game in Console app, it supposed to take the size from the user, then produce a matrix of the size that the user has enterd, filled with the numbers starting with 1 to the size acoording to this role:

  • first number(1) should be written at the first row, in the middle col
  • then we will check if the recently entered num % size not equal to 0;then we will minmize the row, col and put the second number
  • if (num% size ==0) row++

Example output screen of size 3:

enter image description here

Console.Clear();
int number;

do
{
    Console.Write("Please Enter Odd Number :");
    number=int.Parse(Console.ReadLine());
} while (number % 2 == 0);

Console.Clear();
Console.SetCursorPosition(25, 3);

int col = 0;
int row = 1;
double x = (number / 2) + 1;
col = (int)x;

Console.SetCursorPosition(col*3 + 25, row + 3);
Console.Write(1);

for (int i = 1; i < number*number; i++)
{
    if (i % number != 0)
    {
        if (col==1)
        {
            col = number;
        }
        else
        {
            col--;
        }

        if (row == 1)
        {
            row = number;
        }
        else
        {
            row--;
        }

        Console.SetCursorPosition(col*3 + 25, row+3);
        Console.Write(i+1); 
    }
    else if (i % number == 0)
    {
        if (row == number)
        {
            row = 1;
        }
        else
        {
            row++;
        }

        Console.SetCursorPosition(col *3+ 25, row + 3);
        Console.Write(i+1); 
    }
}

Console.SetCursorPosition(27, 27);

What i really don’t understand is when we set the position, why it multiple col times 3+ 25?!



Solution 1:[1]

I think that centralises the output display leaving gaps between columns

Solution 2:[2]

Try printing out values of your variables to check when and why they change their values. It usually helps.

Solution 3:[3]

This is because you want to write the matrix on a certain location the screen.

This: Console.SetCursorPosition(col*3 + 25, row + 3);

Will put the first element on:

x = 1*3 + 25 = 28
y = 1 + 3 = 4

The next at:

x = 2*3 + 25 = 28
y = 1 + 3 = 4

The *3 will create a 'tab' and the + 25 will translate it.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Graham
Solution 2 TS_
Solution 3