Я хочу центрировать текст в консоли по горизонтали и вертикали, используя c# - PullRequest
0 голосов
/ 23 апреля 2020

Я хочу центрировать текст, когда моя игра заканчивается. Прямо сейчас он идет сверху, и я хотел бы поместить его в середину экрана

Это код, который у меня есть, и его вывод.

{
    SoundEffect();
    Console.SetCursorPosition(0, 0);
    Console.ForegroundColor = ConsoleColor.Red;//Text color for game over

    //Assign string output when game is over, player points and enter key 
    String textGameOver = "Game Over!";
    String playerPoints = "Your points are:";
    String enterKey = "Press enter to exit the game!";

    //Output to show on screen
    Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (textGameOver.Length / 2)) + "}", textGameOver));
    int userPoints = (snakeElements.Count - 4) * 100 - negativePoints;//points calculated for player
    userPoints = Math.Max(userPoints, 0); //if (userPoints < 0) userPoints = 0;

    //Output to show player score on screen 
    Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (playerPoints.Length / 2)) + "}", playerPoints + userPoints));

    SavePointsToFile(userPoints);//saving points to files


    //exit game only when enter key is pressed
    Console.WriteLine(String.Format("{0," + ((Console.WindowWidth / 2) + (enterKey.Length / 2)) + "}", enterKey));
    while (Console.ReadKey().Key != ConsoleKey.Enter) {}
    return 1;
}

Текущий выход игры

1 Ответ

1 голос
/ 23 апреля 2020

Вам необходимо выяснить, с чего начать печать строк по вертикали:

private static void PrintLinesInCenter(params string[] lines)
{
    int verticalStart = (Console.WindowHeight - lines.Length) / 2; // work out where to start printing the lines
    int verticalPosition = verticalStart;
    foreach (var line in lines)
    {
        // work out where to start printing the line text horizontally
        int horizontalStart = (Console.WindowWidth - line.Length) / 2;
        // set the start position for this line of text
        Console.SetCursorPosition(horizontalStart, verticalPosition);
        // write the text
        Console.Write(line);
        // move to the next line
        ++verticalPosition;
    }
}

Использование:

PrintLinesInCenter("hello", "this is a test", "of centered text");

Результат:

enter image description here

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...