不断显示文本

本文关键字:文本 显示 | 更新日期: 2023-09-27 18:15:58

我是c#编程新手,我的主要目标是制作简单的基于文本的游戏。我目前有一个问题,我的第一个,这是显示玩家的生命值和攻击和怪物的生命值和攻击值。

我希望这些数值能够显示在控制台的顶部,并在每次玩家或怪物的生命值升高或降低时进行更新。我遇到的问题是,我目前仅限于将此显示为与其他函数不同的函数,并且我只能在运行该函数时显示它。

就像我说的,我对c#很陌生,所以我的代码可能真的很笨拙和业余。

   while (monsterHealth > 0 && playerHealthUpgraded > 0) 
        {
            DisplayStats ();
            Console.WriteLine ("You can either 'attack' or 'defend' yourself from the monster.");
            Console.WriteLine ("Attacking will decrease the monster's health by " + playerAttackUpgraded + " and defending yourself from the monster will cut the monster's attack value in half.");
            string input = Console.ReadLine ();
            if (input == "defend" || input == "attack" || input == "stimpak") 
            {
                switch (input) 
                {
                case "attack":
                    Console.Clear ();
                    DisplayStats ();
                    monsterHealth -= playerAttackUpgraded;
                    Console.WriteLine ("You raise your " + playerWeapon + " and fire several shots at the monster");
                    Console.WriteLine ("The monster's HP was lowered to " + monsterHealth + " by your attack.");
                    playerDamage += monsterAttack;

显然"if"answers"while"语句在函数末尾关闭。

现在,我想要在控制台顶部不断显示的东西是"DisplayStats()",它看起来像这样:

   public static void DisplayStats()
    {
        Console.WriteLine ("Player Health: " + playerHealthUpgraded + "     Monster Health: " + monsterHealth);
        Console.WriteLine ("Player Attack: " + playerAttackUpgraded + "     Monster Attack: " + monsterAttack);
        Console.WriteLine (" ");
    }

任何帮助都将非常感激。谢谢你,

liam

不断显示文本

你不能让这些行向后流动。但是,您可以使用console. clear()来清除控制台。所以也许你可以尝试重新绘制游戏循环中的所有内容,就像在其他类型的游戏中一样。

我个人建议制作一个基于表单的游戏,因为你可以做的还有很多。

话虽如此,我认为你的思路是对的。

正如Johnny所说,你可以在每次更新时重新绘制文本。如果需要,您可以将所有文本存储在字符串中,并在重新绘制文本时刷新控制台。

基本上,添加一些方法使写入/清除框架更容易:

private static string frame;
public static void writeLine(string s) {
    frame += s + Environment.NewLine; //I believe "'n" works too
}
public static void write(string s) {
    frame += s;
}
public static void clearFrame() { frame = ""; }
public static void drawFrame() {
    Console.Clear();
    DisplayStats();
    Console.WriteLine(frame);
}
public static void DisplayStats() {
    Console.WriteLine("Player Health: " + playerHealthUpgraded + "'tMonster Health: " + monsterHealth);
    Console.WriteLine("Player Attack: " + playerAttackUpgraded + "'tMonster Attack: " + monsterAttack);
    Console.WriteLine("");
}

那么,你的开关变成:

switch (input) 
{
    case "attack":
        monsterHealth -= playerAttackUpgraded;
        writeLine("You raise your " + playerWeapon + " and fire several shots at the monster");
        writeLine("The monster's HP was lowered to " + monsterHealth + " by your attack.");
        playerDamage += monsterAttack;
        drawFrame();

这样,如果你想,你可以保留你已经有的文本,附加它,或者任何你想做的。