Beispiel #1
0
        protected override void OnUpdateFrame(FrameEventArgs e)
        {
            _elapsed += e.Time;

            var toRemove = new HashSet <IActor>();
            var view     = new Vector4(0, 0, -2.4f, 0);

            var outOfBoundsAsteroids = 0;
            var removedAsteroids     = 0;

            foreach (var actor in _actors)
            {
                actor.Update(_elapsed, e.Time);
                if ((view - actor.Position).Length > 2)
                {
                    toRemove.Add(actor);
                    if (actor is AsteroidActor)
                    {
                        outOfBoundsAsteroids++;
                    }
                }

                if (!(actor is ICollidable c))
                {
                    continue;
                }
                var collisions = c.CollidesWith(_actors).ToList();

                if (!collisions.Any())
                {
                    continue;
                }
                if (actor == _player)
                {
                    foreach (var a in _actors)
                    {
                        toRemove.Add(a);
                    }

                    _gameOver = true;
                }
                else
                {
                    toRemove.Add(actor);
                    foreach (var asteroid in collisions)
                    {
                        if (!toRemove.Add(asteroid) || !(asteroid is AsteroidActor a))
                        {
                            continue;
                        }
                        _score += a.Points;

                        Console.WriteLine($"Got one! Your score is now {_score}");

                        removedAsteroids++;
                    }
                }
            }

            foreach (var actor in toRemove)
            {
                _actors.Remove(actor);
            }

            if (!_gameOver)
            {
                for (var i = 0; i < removedAsteroids; i++)
                {
                    _actors.Add(_actorFactory.CreateRandomAsteroid());
                    _actors.Add(_actorFactory.CreateRandomAsteroid());
                }

                for (var i = 0; i < outOfBoundsAsteroids; i++)
                {
                    _actors.Add(_actorFactory.CreateRandomAsteroid());
                }
            }
            else if (!_gameOverSpawned)
            {
                _actors.Add(_actorFactory.CreateGameOver());
                _gameOverSpawned = true;
            }

            HandleKeyboard();
        }