I am creating a game sort of a thing, and I need enemys to attack at random times. How would I do this? I can post my code if necessary.
Printable View
I am creating a game sort of a thing, and I need enemys to attack at random times. How would I do this? I can post my code if necessary.
You generate random numbers using the Random class. You could use a random number as the Interval for a Timer, then make your enemy attack from the Elapsed event handler. You might do something like this:This assumes that you have declared an Enemy class with an Attack method.VB Code:
Private enemyTimers As New Dictionary(Of Timers.Timer, Enemy) Private attackTimeGenerator As New Random Private Sub AddNewEnemy() Dim t As New Timers.Timer t.AutoReset = True Me.SetAttackInterval(t) AddHandler t.Elapsed, AddressOf Timer_Elapsed Dim e As New Enemy Me.enemyTimers.Add(t, e) End Sub Private Sub Timer_Elapsed(ByVal sender As Object, ByVal e As System.Timers.ElapsedEventArgs) Dim t As Timers.Timer = DirectCast(sender, Timers.Timer) 'Set a new attack interval. Me.SetAttackInterval(t) 'Make the enemy associated with this timer attack. Me.enemyTimers(t).Attack() End Sub Private Sub SetAttackInterval(ByVal t As Timers.Timer) 'Make the associated enemy attack in a random amount of time from 1 to 10 seconds. t.Interval = Me.attackTimeGenerator.NextDouble * 9000.0R + 1000.0R End Sub
It sounds like a good idea, though I have a question.
Where in that code is the part where I tell the program what to do if there is a new ene,y. I need it to update a label with a new enemy.
I have like
Dim enemy As Integer
Then on the Tick event (I think) I add,
enemy = enemy + 1
enemylbl.Text = enemy
Here's a hint:Quote:
Originally Posted by jmcilhinney
As of now my attack method is this:
VB Code:
enemy = enemy + 1 enemylbl.Text = enemy
My code is an example of the principle. The principle is that you use a Dictionary to store Timers and the objects that represent the enemies that those Timers correspond to. What those objects are is up to you. When the Timer Elapses you set a new Interval and you use the Dictionary to get the object that represents the enemy that corresponds to the Timer that just Elapsed. You then use that object to do what is required to represent an attack from that enemy. That's the principle. Now it's up to you to adapt that principle to whatever specific circumstances you have.
Another alternative would be to use a single Timer object, probably with a smaller Interval. You could then use the Random object to choose a period to wait before the next attack and also to choose a random index. That random index would then be used to get an enemy from an array or collection, who would then attack.
Can you show a code example for this? Because this seems like the best way to do it...Quote:
Originally Posted by jmcilhinney