Scadian Force
Scadian Force

Reputation: 21

How to set up timer for 2 different variables?

How to simulate combat in the Console app, when you have two different intervals? Make a 2nd timer?

private static Timer aTimer;

my interval values would be reflected in 2 int variables, meaning Attacks per second.

int myAttackSpeed = 95; //Multiplied by 10 converts to milliseconds intervals
int yourAttackSpeed = 92; //as more than one attack per second
//You should make more attacks at the same time I do. Fewer milliseconds to attack = more attacks.

How to make both intervals work at the same time and type something to the screen? Only with text to the screen would be satisfied, and later try the timer's output to reflect real changes happening.

How to have different methods running or repeating when they have different intervals?Or should I look into multithreading for such an idea?

Upvotes: 2

Views: 104

Answers (1)

timur
timur

Reputation: 14567

You might find it easier to leverage Timer Elapsed events for this:

public class Example { 
    private static Timer t1;
    private static Timer t2;
    int myAttackSpeed = 95;    
    yourAttackSpeed = 92;

    public static void Main() 
    { 
        t1 = new System.Timers.Timer {
            Interval = myAttackSpeed*10,
            Enabled = true,
            Elapsed += OnT1Elapsed
        };

        t2 = new System.Timers.Timer {
            Interval = yourAttackSpeed*10,
            Enabled = true,
            Elapsed += OnT2Elapsed
        };

        Console.WriteLine("Press the Enter key to exit the program at any time... ");    
        Console.ReadLine(); 
    } 

    private static void OnT1Elapsed(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("My attack"); 
     }

    private static void OnT2Elapsed(Object source, System.Timers.ElapsedEventArgs e)
    {
        Console.WriteLine("Your attack"); 
     }
}

In real projects your probably should deduplicate repeating code and tidy up, but I'm hoping this illustrates my point for you to keep going

Upvotes: 2

Related Questions