77 lines
1.9 KiB
C#

using Battleship.Exceptions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Battleship.Generics
{
internal class SetGeneric<T>
where T : class
{
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetGeneric(int count)
{
_maxCount = count;
_places = new List<T?>(_maxCount);
}
public bool Insert(T ship)
{
return Insert(ship, 0);
}
public bool Insert(T ship, int position)
{
if (position < 0 || position >= _maxCount)
throw new ShipNotFoundException(position);
if (Count >= _maxCount)
throw new StorageOverflowException(_maxCount);
_places.Insert(0, ship);
return true;
}
public bool Remove(int position)
{
if (position < 0 || position > _maxCount || position >= Count)
throw new ShipNotFoundException(position);
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0 || position >= Count)
return null;
return _places[position];
}
set
{
if (position < 0 || position > _maxCount || Count == _maxCount)
return;
_places[position] = value;
}
}
public IEnumerable<T> GetShips(int? maxShips = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxShips.HasValue && i == maxShips.Value)
{
yield break;
}
}
}
}
}