【问题标题】:I want to center the text in console both horizontally and vertically using c#我想使用 c# 将控制台中的文本水平和垂直居中
【发布时间】:2020-04-23 03:10:46
【问题描述】:

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

这是我目前拥有的代码及其输出。

{
    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

【问题讨论】:

  • 您为什么将代码作为图像提供?我发现调试它们真的很难。 “我面临的问题是……” 告诉我们您想做什么,但没有告诉我们您在Stack Overflow 上发现的 sn-p 遇到了什么问题.
  • 图片中的代码在这里是不可接受的。请参阅this Meta post 了解众多原因的列表。请edit您的帖子以文本形式包含实际代码,并正确格式化以提高可读性。编辑时单击答案工具栏中的? 按钮可获得格式帮助。
  • 垂直居中是否有问题?您拥有根据字符串的字符宽度 (s.Width) 获取水平起始位置的代码。如何根据要打印的行数获得垂直起始位置?
  • 您“参考”的question 是所问问题的答案...所以我将其用作重复项。您可能想edit 提出问题,以澄清您在实施该问题的建议时遇到哪些问题,以便可以考虑重新打开(不要忘记将代码也显示为文本)
  • 好的,我将其添加为代码。

标签: c# terminal console


【解决方案1】:

您需要确定从哪里开始垂直打印线条:

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

结果:

【讨论】:

    猜你喜欢
    • 2015-09-25
    • 2013-07-27
    • 2012-01-01
    • 2014-03-31
    • 2012-03-14
    • 2017-06-28
    • 1970-01-01
    • 2022-01-09
    相关资源
    最近更新 更多