private void OnShotHandler(object sender, Bullet bullet) { Tank tank = sender as Tank; if (tank != null) { foreach (var tmp in tanksCollection) { if (tmp.Key == tank.GetHashCode()) { Position bulletPosition = new Position(); GetDesirePosition(ref bulletPosition, tank, bullet.GetDirection()); BulletOnMap newBullet = new BulletOnMap(); newBullet.Bullet = bullet; newBullet.Position = bulletPosition; // check if the bullet doesnt exist in the collection if (!bulletsCollection.ContainsKey(tmp.Key)) { bulletsCollection.Add(tmp.Key, newBullet); } } } } }
// all right #region Timer Handler // called each time to controll bullets movement private void TimerElapsed(object sender, ElapsedEventArgs e) { if (bulletsCollection.Count > 0) { // to collect bullets and delete it after foreach List <BulletOnMap> toDelete = new List <BulletOnMap>(); // to collect bullets and then change it in bulletsCollection List <BulletOnMap> toChange = new List <BulletOnMap>(); foreach (var bullet in bulletsCollection) { // check if bullet intersects with an object // if true decrement hp and remove bullet foreach (var tank in tanksCollection) { if ((bullet.Value.Position.X == tank.Value.Position.X) && (bullet.Value.Position.Y == tank.Value.Position.Y) && (bullet.Key != tank.Key)) { tank.Value.Tank.HPImprove((-1) * bullet.Value.Bullet.GetDamage()); toDelete.Add(bullet.Value); } } // delete current position and change it to the new toDelete.Add(bullet.Value); // object to change BulletOnMap tmp = bullet.Value; switch (bullet.Value.Bullet.GetDirection()) { case Directions.Down: { tmp.Position.Y--; break; } case Directions.Up: { tmp.Position.Y++; break; } case Directions.Right: { tmp.Position.X++; break; } case Directions.Left: { tmp.Position.X--; break; } } // chech if bullet intersects with a wall // if true then remove if (map.IsEmpty(tmp.Position.X, tmp.Position.Y)) { // intersect bounds if (map.xLenth > tmp.Position.X && map.yLenth > tmp.Position.Y && tmp.Position.X >= 0 && tmp.Position.Y >= 0) { toChange.Add(tmp); } } else { // delete bullet from the map toDelete.Add(bullet.Value); } } // remove all bullets from toDelete list foreach (var remove in toDelete) { if (bulletsCollection.Remove(remove.Bullet.GetHashCode())) { // delete bullet from the map Visualizer.Render(' ', remove.Position.X, remove.Position.Y, System.Console.BackgroundColor); } } // change bullets foreach (var change in toChange) { bulletsCollection[change.Bullet.GetHashCode()] = change; Visualizer.Render(change.Bullet.GetSkin(), change.Position.X, change.Position.Y, change.Bullet.GetColor()); } } }