Home > Net >  Update a variable in a method that is called only once
Update a variable in a method that is called only once

Time:10-04

First thing fist, I'm a newbie in the C# field and I want to ask you a question.

I am creating a simple fight game application using Console and I have a health variable that is updated in the fight method.

I also have a method that is only called once, before the fight, and I wonder if it is possible to show the health variable, updated, in the method that is only called once (like a real time update).

Is that possible to do?

This is fight function:

 public static bool Fight(Player p1, Player p2)
    {
        // One player attacks, the other one blocks
        double damageGiven = p1.Attack();
        double damageBlocked = p2.Block();

        // Calculate the damage taken from the attack after block it
        // If I do an attack with 100 power and then block it with 90 power, the damage given is 10 power
        double damageTaken = damageGiven - damageBlocked;

        if (damageTaken > 0)
        {
            p2.health -= damageTaken;
        }
        else
        {
            damageTaken = 0;
        }

        Console.WriteLine($" {p1.name} attacks {p2.name} and deals {damageTaken} of damage!");
        Console.WriteLine($" {p2.name} has {p2.health} of health!\n");

        if (p2.health <= 0)
        {
            Console.WriteLine($" {p2.name} has died! The winner is {p1.name}!\n");
            return true;
        }
        else
        {
            return false;
        }
    }

And here is where I want to update the variable like in real time (in that Console.WriteLines):

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

CodePudding user response:

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.

  • Related