首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >我想使用c#在控制台中水平和垂直居中显示文本

我想使用c#在控制台中水平和垂直居中显示文本
EN

Stack Overflow用户
提问于 2020-04-23 11:10:46
回答 1查看 354关注 0票数 1

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

这是我到目前为止拥有的代码和它的输出。

代码语言:javascript
复制
{
    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

EN

回答 1

Stack Overflow用户

发布于 2020-04-23 13:22:41

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

代码语言:javascript
复制
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;
    }
}

用法:

代码语言:javascript
复制
PrintLinesInCenter("hello", "this is a test", "of centered text");

结果:

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61378701

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档