i am a CS student trying to build a game about space battle that happen in "real time". i have nailed the base code and it works well with small battles ( less than 20 spaceships ) but the more spaceships i add, the longer the program takes to start the battle.
Here is some relevant code :
class Weapon
{
SpaceShip Ship;
public bool Loaded;
public int Damage;
int Hits;
public int ReloadTime;
public Task ReloadTask;
public void Fire(SpaceShip Target)
{
if (!Loaded)
return;
ReloadTask = Task.Run(() =>
{
UseGun(Target);
});
}
private void UseGun(SpaceShip Target)
{
Loaded = false;
Target?.TakeDamage(Damage);
Hits++;
Thread.Sleep(ReloadTime);
Loaded = true;
}
+ some irrelevant methods
}
class SpaceShip
{
public bool Alive;
public int Armor;
public int MaxArmor;
public string Name;
Weapon[] Weapons;
public SpaceShip Target;
public bool WeaponsActive;
public Weapon WaitForNextReload(int delayMax = -1)
{
var TaskArray = Weapons.Select(x => x.ReloadTask).ToArray();
int index = Task.WaitAny(TaskArray, delayMax);
return (index >= 0) ? Weapons[index] : null;
}
public void FireWeapons()
{
if (Weapons.Length == 0)
return;
Task.Run(() =>
{
foreach (Weapon W in Weapons)
{
W.Fire(Target);
}
while (ValidTarget())
{
Weapon W = WaitForNextReload();
W?.Fire(Target);
}
});
}
private bool ValidTarget()
{
return Alive && Target != null && Target.Alive;
}
+ some irrelevant methods
}
As you can see i use a Task system to simulate each gun reloading in 'real time'. When i have too many Spaceships in a battle, the program will start with no problem, but the Spaceships will stay idle and don't fire at their target even tho their weapons are ready to fire. This delay increase the more Spaceships i have ( each entity can have upward of 10 weapons so 10 tasks x each spaceship ).
While the "waiting" is happenning, my cpu is at 0 - 3% usage.
Is there some invisible overhead with the tasks that slows me down ? How can i do to reduce the wait ?