PIbd-21_Valitov_D.F_Sailboa.../Sailboat/MapWithSetBoatsGeneric.cs
2023-04-14 21:28:29 +04:00

141 lines
4.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Sailboat
{
class MapWithSetBoatsGeneric<T, U> where T : class, IDrawingObject
where U : AbstractMap
{
private readonly int _pictureWidth;
private readonly int _pictureHeight;
private readonly int _placeSizeWidth = 210;
private readonly int _placeSizeHeight = 90;
private readonly SetBoatsGeneric<T> _setBoats;
private readonly U _map;
public MapWithSetBoatsGeneric(int picWidth, int picHeight, U map)
{
int width = picWidth / _placeSizeWidth;
int height = picHeight / _placeSizeHeight;
_setBoats = new SetBoatsGeneric<T>(width * height);
_pictureWidth = picWidth;
_pictureHeight = picHeight;
_map = map;
}
public static int operator +(MapWithSetBoatsGeneric<T, U> map, T boat)
{
return map._setBoats.Insert(boat);
}
public static T operator -(MapWithSetBoatsGeneric<T, U> map, int position)
{
return map._setBoats.Remove(position);
}
public Bitmap ShowSet()
{
Bitmap bmp = new(_pictureWidth, _pictureHeight);
Graphics gr = Graphics.FromImage(bmp);
DrawBackground(gr);
DrawBoats(gr);
return bmp;
}
public Bitmap ShowOnMap()
{
Shaking();
for (int i = 0; i < _setBoats.Count; i++)
{
var ship = _setBoats.Get(i);
if (ship != null)
{
return _map.CreateMap(_pictureWidth, _pictureHeight, ship);
}
}
return new(_pictureWidth, _pictureHeight);
}
public Bitmap MoveObject(Direction direction)
{
if (_map != null)
{
return _map.MoveObject(direction);
}
return new(_pictureWidth, _pictureHeight);
}
private void Shaking()
{
int j = _setBoats.Count - 1;
for (int i = 0; i < _setBoats.Count; i++)
{
if (_setBoats.Get(i) == null)
{
for (; j > i; j--)
{
var boat = _setBoats.Get(j);
if (boat != null)
{
_setBoats.Insert(boat, i);
_setBoats.Remove(j);
break;
}
}
if (j <= i)
{
return;
}
}
}
}
private void DrawBackground(Graphics g)
{
Pen pen = new(Color.Brown, 3);
g.FillRectangle(Brushes.Aqua, 0, 0, _pictureWidth, _pictureHeight);
for (int i = 0; i < _pictureWidth / _placeSizeWidth; i++)
{
for (int j = 0; j < _pictureHeight / _placeSizeHeight + 1; ++j)
{//линия рамзетки места
g.DrawLine(pen, i * _placeSizeWidth, j * _placeSizeHeight, i * _placeSizeWidth + _placeSizeWidth / 2, j * _placeSizeHeight);
}
g.DrawLine(pen, i * _placeSizeWidth, 0, i * _placeSizeWidth, (_pictureHeight / _placeSizeHeight) * _placeSizeHeight);
}
}
private void DrawBoats(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
int currentWidth = 0;
int currentHeight = 0;
for (int i = 0; i < _setBoats.Count; i++)
{
_setBoats.Get(i)?.SetObject(currentWidth * _placeSizeWidth,
currentHeight * _placeSizeHeight,
_pictureWidth, _pictureHeight);
_setBoats.Get(i)?.DrawingObject(g);
if (currentWidth < width - 1)
{
currentWidth++;
}
else
{
currentHeight++;
currentWidth = 0;
}
if (currentHeight > height) return;
}
}
}
}