c# - 我想使用 C# 将控制台中的文本水平和垂直居中

标签 c# terminal console

我想在游戏结束时将文本居中。现在它位于顶部,我想将它放在屏幕中间

这是我到目前为止的代码及其输出。

{
    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;
}

Current output of the game

最佳答案

您需要弄清楚从哪里开始垂直打印线条:

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

关于c# - 我想使用 C# 将控制台中的文本水平和垂直居中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61378701/

相关文章:

c# - .NET Entity Framework Core 2.0 - 代码优先 - 意外的表关系结果

c - 是否可以为多平台 : embedded or all operating systems? 编写 C 代码和库

c# - 以编程方式设置控制台窗口大小和位置

windows - VSCode 终端之前的命令

C#控制台字体

c# - 使用 LINQ 确定序列不包含任何元素

c# - 如何访问列表中的随机项目?

c# - 有没有办法将 RectTransform 传输到 unity3d 中的相机 ViewPort?

windows - IIS 上等效的 Linux shell

PHP error_log 在 Mac OSX 上将换行符输出为文字 "\n"字符串