/// <summary> /// Find best step for escaping /// </summary> private Position FindBestStepToEscape(Herbivore herbivore, Field field) { var maxDistance = double.MinValue; var bestStep = new Position(0, 0); var nextStep = new Position(); for (nextStep.X = -herbivore.MaxSpeed; nextStep.X <= herbivore.MaxSpeed; nextStep.X++) { for (nextStep.Y = -herbivore.MaxSpeed; nextStep.Y <= herbivore.MaxSpeed; nextStep.Y++) { var newPosition = herbivore.Position.Clone().Add(nextStep); if (!_validator.PositionIsOutOfField(field, newPosition) && (!_validator.PositionIsTaken(field, newPosition) || herbivore.Position.Equals(newPosition))) { var distance = _calculations.Distance(newPosition, herbivore.ClosestEnemy.Position); if (distance > maxDistance) { maxDistance = distance; bestStep = nextStep.Clone(); } } } } return(bestStep); }
/// <summary> /// Get step in a random direction /// </summary> private Position GetRandomStep(Animal carnivore, Field field) { Position nextStep; bool moveIsValide; do { nextStep = _random.GetRandomStep(carnivore.MaxSpeed); var newPosition = nextStep.Clone().Add(carnivore.Position); moveIsValide = !_validator.PositionIsOutOfField(field, newPosition) && (!_validator.PositionIsTaken(field, newPosition) || carnivore.Position.Equals(newPosition)); } while (!moveIsValide); return(nextStep); }
/// <summary> /// Get free position on the field. If field is full , throw InvalidOperationException. /// </summary> private Position GetFreePosition(Field field) { if (field.HasFreeSpace == false) { throw new InvalidOperationException("Field has no free space"); } Position newPosition; do { newPosition = new Position(_random.Get(field.Width), _random.Get(field.Height)); } while (_validator.PositionIsTaken(field, newPosition)); return(newPosition); }