简体   繁体   中英

Can I update C# console output in realtime without constantly writing to it?

I am creating a simple fighting game console application and I have a health property on my Player objects, that is updated in the Fight method.

I wonder if it is possible to show the health variable, in real-time in the console without calling a method that updates the console more than once.

Here is my main method which starts the fight, and displays the health output of each player.

 public static void StartFight(Player p1, Player p2) {
   Console.Clear();
   Title(" BATTLE ");
   Console.WriteLine($"{p1.name} Health: {p1.health} ");
   Console.WriteLine($"{p2.name} Health: {p2.health} ");

   // Loop giving each player a chance to attack
   // and block each turn until 1 dies
   while (true) {
     if (Fight(p1, p2)) {
       Title(" GAME OVER! ");
       PlayAgain();
       break;
     }

     if (Fight(p2, p1)) {
       Title(" GAME OVER! ");
       PlayAgain();
       break;
     }
   }
 }

Is it possible to write to the console in real-time so that I don't have to keep doing Console.WriteLine($"{p1.name} Health: {p1.health} "); ?

No - if you are displaying to console, there is no way to have a realtime updating of the UI without calling a method more than once to update the console.

Other UIs have ways to do this using events, bindings etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM