Правки 4 лаба

This commit is contained in:
platoff aeeee 2023-11-08 00:15:08 +04:00
parent 91252d99a9
commit bda0646769
9 changed files with 322 additions and 149 deletions

View File

@ -8,7 +8,6 @@ using Tank.Entites;
namespace Tank.DrawingObjects
{
/// Класс, отвечающий за прорисовку и перемещение объекта-сущности
public class DrawingTank : DrawingArmoredCar
{
/// Конструктор
@ -21,8 +20,8 @@ namespace Tank.DrawingObjects
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="width">Ширина картинки</param>
/// <param name="height">Высота картинки</param>
public DrawingTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool wing, bool sportLine, int width, int height) :
public DrawingTank(int speed, double weight, Color bodyColor, Color additionalColor,
bool bodyKit, bool wing, bool sportLine, int width, int height) :
base(speed, weight, bodyColor, width, height, 110, 60)
{
if (Tank != null)
@ -90,7 +89,7 @@ namespace Tank.DrawingObjects
g.DrawRectangle(pen, _startPosX + 40, _startPosY - 10, 20, 5);
// обвесы
if (ArmoredCar.BodyKit) // entityTank
if (ArmoredCar.BodyKit)
{
Brush brAdd = new SolidBrush(ArmoredCar.AdditionalColor);
@ -100,10 +99,9 @@ namespace Tank.DrawingObjects
g.DrawRectangle(pen, _startPosX + 95, _startPosY + 17, 20, 18);
g.FillRectangle(brAdd, _startPosX + 100, _startPosY + 4, 5, 4);
}
// спортивная линия
// линия
if (ArmoredCar.Line)
{
g.FillRectangle(additionalBrush, _startPosX + 75,
@ -115,13 +113,11 @@ namespace Tank.DrawingObjects
}
// багажник
if (ArmoredCar.Trunk) // Tank
if (ArmoredCar.Trunk)
{
g.FillRectangle(additionalBrush, _startPosX + 23, _startPosY + 4, 8, 10);
g.DrawRectangle(pen, _startPosX + 23, _startPosY + 4, 8, 10);
}
}
}
}

View File

@ -9,22 +9,15 @@ namespace Tank.Entites
{
public class EntityTank : EntityArmoredCar
{
/// Скорость
public int Speed { get; private set; }
/// Вес
// public double Weight { get; private set; }
/// Основной цвет
// public Color BodyColor { get; private set; }
/// Дополнительный цвет (для опциональных элементов)
public Color AdditionalColor { get; private set; }
// Признак (опция) наличия обвеса
public bool BodyKit { get; private set; }
// Признак (опция) наличия Багажника
public bool Trunk { get; private set; }
// Признак (опция) наличия гоночной полосы
public bool SportLine { get; private set; }
public bool Line { get; private set; }
/// Шаг перемещения танка
// public double Step => (double)Speed * 200 / Weight;
/// Инициализация полей объекта-класса спортивного автомобиля
/// <param name="speed">Скорость</param>
/// <param name="weight">Вес Танка</param>
@ -32,14 +25,14 @@ namespace Tank.Entites
/// <param name="additionalColor">Дополнительный цвет</param>
/// <param name="bodyKit">Признак наличия обвеса</param>
/// <param name="trunk">Признак наличия багажника</param>
/// <param name="sportLine">Признак наличия гоночной полосы</param>
/// <param name="line">Признак наличия гоночной полосы</param>
public EntityTank(int speed, double weight, Color bodyColor, Color
additionalColor, bool bodyKit, bool trunk, bool sportLine) : base(speed, weight, bodyColor)
additionalColor, bool bodyKit, bool trunk, bool line) : base(speed, weight, bodyColor)
{
AdditionalColor = additionalColor;
BodyKit = bodyKit;
Trunk = trunk;
SportLine = sportLine;
Line = line;
}
}
}

View File

@ -29,17 +29,24 @@
private void InitializeComponent()
{
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.textBoxStorageName = new System.Windows.Forms.TextBox();
this.listBoxStorages = new System.Windows.Forms.ListBox();
this.ButtonDelObject = new System.Windows.Forms.Button();
this.ButtonAddObject = new System.Windows.Forms.Button();
this.maskedTextBoxNumber = new System.Windows.Forms.MaskedTextBox();
this.ButtonRefreshCollection = new System.Windows.Forms.Button();
this.ButtonRemoveArmoredCar = new System.Windows.Forms.Button();
this.ButtonAddArmoredCar = new System.Windows.Forms.Button();
this.pictureBoxCollection = new System.Windows.Forms.PictureBox();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).BeginInit();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.groupBox2);
this.groupBox1.Controls.Add(this.maskedTextBoxNumber);
this.groupBox1.Controls.Add(this.ButtonRefreshCollection);
this.groupBox1.Controls.Add(this.ButtonRemoveArmoredCar);
@ -51,16 +58,65 @@
this.groupBox1.TabStop = false;
this.groupBox1.Text = "Инструменты";
//
// groupBox2
//
this.groupBox2.Controls.Add(this.textBoxStorageName);
this.groupBox2.Controls.Add(this.listBoxStorages);
this.groupBox2.Controls.Add(this.ButtonDelObject);
this.groupBox2.Controls.Add(this.ButtonAddObject);
this.groupBox2.Location = new System.Drawing.Point(13, 22);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(181, 219);
this.groupBox2.TabIndex = 8;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "Наборы";
//
// textBoxStorageName
//
this.textBoxStorageName.Location = new System.Drawing.Point(27, 18);
this.textBoxStorageName.Name = "textBoxStorageName";
this.textBoxStorageName.Size = new System.Drawing.Size(129, 23);
this.textBoxStorageName.TabIndex = 7;
//
// listBoxStorages
//
this.listBoxStorages.FormattingEnabled = true;
this.listBoxStorages.ItemHeight = 15;
this.listBoxStorages.Location = new System.Drawing.Point(27, 76);
this.listBoxStorages.Name = "listBoxStorages";
this.listBoxStorages.Size = new System.Drawing.Size(129, 94);
this.listBoxStorages.TabIndex = 6;
//
// ButtonDelObject
//
this.ButtonDelObject.Location = new System.Drawing.Point(12, 176);
this.ButtonDelObject.Name = "ButtonDelObject";
this.ButtonDelObject.Size = new System.Drawing.Size(154, 23);
this.ButtonDelObject.TabIndex = 5;
this.ButtonDelObject.Text = "Удалить набор";
this.ButtonDelObject.UseVisualStyleBackColor = true;
this.ButtonDelObject.Click += new System.EventHandler(this.ButtonDelObject_Click);
//
// ButtonAddObject
//
this.ButtonAddObject.Location = new System.Drawing.Point(12, 47);
this.ButtonAddObject.Name = "ButtonAddObject";
this.ButtonAddObject.Size = new System.Drawing.Size(154, 23);
this.ButtonAddObject.TabIndex = 4;
this.ButtonAddObject.Text = "Добавить набор";
this.ButtonAddObject.UseVisualStyleBackColor = true;
this.ButtonAddObject.Click += new System.EventHandler(this.ButtonAddObject_Click);
//
// maskedTextBoxNumber
//
this.maskedTextBoxNumber.Location = new System.Drawing.Point(36, 85);
this.maskedTextBoxNumber.Location = new System.Drawing.Point(40, 295);
this.maskedTextBoxNumber.Name = "maskedTextBoxNumber";
this.maskedTextBoxNumber.Size = new System.Drawing.Size(129, 23);
this.maskedTextBoxNumber.TabIndex = 3;
//
// ButtonRefreshCollection
//
this.ButtonRefreshCollection.Location = new System.Drawing.Point(7, 160);
this.ButtonRefreshCollection.Location = new System.Drawing.Point(13, 389);
this.ButtonRefreshCollection.Name = "ButtonRefreshCollection";
this.ButtonRefreshCollection.Size = new System.Drawing.Size(187, 31);
this.ButtonRefreshCollection.TabIndex = 2;
@ -70,9 +126,9 @@
//
// ButtonRemoveArmoredCar
//
this.ButtonRemoveArmoredCar.Location = new System.Drawing.Point(7, 114);
this.ButtonRemoveArmoredCar.Location = new System.Drawing.Point(13, 324);
this.ButtonRemoveArmoredCar.Name = "ButtonRemoveArmoredCar";
this.ButtonRemoveArmoredCar.Size = new System.Drawing.Size(187, 40);
this.ButtonRemoveArmoredCar.Size = new System.Drawing.Size(181, 40);
this.ButtonRemoveArmoredCar.TabIndex = 1;
this.ButtonRemoveArmoredCar.Text = "Удалить бронированную машину";
this.ButtonRemoveArmoredCar.UseVisualStyleBackColor = true;
@ -80,9 +136,9 @@
//
// ButtonAddArmoredCar
//
this.ButtonAddArmoredCar.Location = new System.Drawing.Point(7, 22);
this.ButtonAddArmoredCar.Location = new System.Drawing.Point(13, 247);
this.ButtonAddArmoredCar.Name = "ButtonAddArmoredCar";
this.ButtonAddArmoredCar.Size = new System.Drawing.Size(187, 42);
this.ButtonAddArmoredCar.Size = new System.Drawing.Size(181, 42);
this.ButtonAddArmoredCar.TabIndex = 0;
this.ButtonAddArmoredCar.Text = "Добавить бронированную машину";
this.ButtonAddArmoredCar.UseVisualStyleBackColor = true;
@ -107,6 +163,8 @@
this.Text = "Набор бронированных машин";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxCollection)).EndInit();
this.ResumeLayout(false);
@ -120,5 +178,10 @@
private Button ButtonAddArmoredCar;
private PictureBox pictureBoxCollection;
private MaskedTextBox maskedTextBoxNumber;
private ListBox listBoxStorages;
private Button ButtonDelObject;
private Button ButtonAddObject;
private GroupBox groupBox2;
private TextBox textBoxStorageName;
}
}

View File

@ -15,24 +15,48 @@ namespace Tank
{
public partial class FormArmoredCarCollection : Form
{
private readonly TanksGenericCollection<DrawingArmoredCar,DrawingObjectArmoredCar> _tanks;
private readonly TanksGenericStorage _storage;
public FormArmoredCarCollection()
{
InitializeComponent();
_tanks = new TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>
(pictureBoxCollection.Width, pictureBoxCollection.Height);
_storage = new TanksGenericStorage(pictureBoxCollection.Width, pictureBoxCollection.Height);
}
private void ReloadObjects()
{
int index = listBoxStorages.SelectedIndex; listBoxStorages.Items.Clear();
for (int i = 0; i < _storage.Keys.Count; i++)
{
listBoxStorages.Items.Add(_storage.Keys[i]);
}
if (listBoxStorages.Items.Count > 0 && (index == -1 || index >= listBoxStorages.Items.Count))
{
listBoxStorages.SelectedIndex = 0;
}
else if (listBoxStorages.Items.Count > 0 && index > -1 && index < listBoxStorages.Items.Count)
{
listBoxStorages.SelectedIndex = index;
}
}
private void ButtonAddArmoredCar_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
FormTank form = new();
if (form.ShowDialog() == DialogResult.OK)
{
if (_tanks + form.SelectedTank != -1)
if (obj + form.SelectedTank)
{
MessageBox.Show("Объект добавлен");
pictureBoxCollection.Image = _tanks.ShowTanks();
pictureBoxCollection.Image = obj.ShowTanks();
}
else
{
@ -43,16 +67,25 @@ namespace Tank
private void ButtonRemoveArmoredCar_Click(object sender, EventArgs e)
{
if (MessageBox.Show("Удалить объект?", "Удаление", MessageBoxButtons.YesNo, MessageBoxIcon.Question)
== DialogResult.No)
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ?? string.Empty];
if (obj == null)
{
return;
}
if (MessageBox.Show("Удалить объект?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No)
{
return;
}
int pos = Convert.ToInt32(maskedTextBoxNumber.Text);
if (_tanks - pos != null)
if (obj - pos != null)
{
MessageBox.Show("Объект удален");
pictureBoxCollection.Image = _tanks.ShowTanks();
pictureBoxCollection.Image = obj.ShowTanks();
}
else
{
@ -62,7 +95,47 @@ namespace Tank
private void ButtonRefreshCollection_Click(object sender, EventArgs e)
{
pictureBoxCollection.Image = _tanks.ShowTanks();
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
var obj = _storage[listBoxStorages.SelectedItem.ToString() ??
string.Empty];
if (obj == null)
{
return;
}
pictureBoxCollection.Image = obj.ShowTanks();
}
private void ButtonAddObject_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(textBoxStorageName.Text))
{
MessageBox.Show("Не все данные заполнены", "Ошибка",MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
_storage.AddSet(textBoxStorageName.Text);
ReloadObjects();
}
private void ListBoxObjects_SelectedIndexChanged(object sender, EventArgs e)
{
pictureBoxCollection.Image = _storage[listBoxStorages.SelectedItem?.ToString() ?? string.Empty]?.ShowTanks();
}
private void ButtonDelObject_Click(object sender, EventArgs e)
{
if (listBoxStorages.SelectedIndex == -1)
{
return;
}
if (MessageBox.Show($"Удалить объект { listBoxStorages.SelectedItem}?", "Удаление",
MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
_storage.DelSet(listBoxStorages.SelectedItem.ToString() ?? string.Empty);
ReloadObjects();
}
}
}
}

View File

@ -9,10 +9,10 @@ namespace Tank
public partial class FormTank : Form
{
/// Ïîëå-îáúåêò äëÿ ïðîðèñîâêè îáúåêòà
private DrawingArmoredCar? _Tank; // DrawingArmoredCar DrawingTank
private DrawingArmoredCar? _Tank;
/// Ñòðàòåãèÿ ïåðåìåùåíèÿ
private AbstractStrategy? _abstractStrategy;
public DrawingArmoredCar? SelectedTank { get; private set; } // DrawingArmoredCar DrawingTank
public DrawingArmoredCar? SelectedTank { get; private set; }
public FormTank()
{
InitializeComponent();

View File

@ -12,110 +12,71 @@ namespace Tank.Generics
/// <typeparam name="T"></typeparam>
internal class SetGeneric<T> where T : class
{
/// <summary>
/// Массив объектов, которые храним
/// </summary>
private readonly T?[] _places;
/// <summary>
/// Количество объектов в массиве
/// </summary>
public int Count => _places.Length;
/// <summary>
/// Конструктор
/// </summary>
/// <param name="count"></param>
private readonly List<T?> _places;
public int Count => _places.Count;
private readonly int _maxCount;
public SetGeneric(int count)
{
_places = new T?[count];
_maxCount = count;
_places = new List<T?>(_maxCount);
}
/// <summary>
/// Добавление объекта в набор
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <returns></returns>
public int Insert(T tank)
public bool Insert(T tank)
{
int index = -1;
for (int i = 0; i < _places.Length; i++)
{
if (_places[i] == null)
{
index = i;
break;
return Insert(tank, 0);
}
}
if (index < 0)
{
return -1;
}
for (int i = index; i > 0; i--)
{
_places[i] = _places[i - 1];
}
_places[0] = tank;
return 0;
}
/// <summary>
/// Добавление объекта в набор на конкретную позицию
/// </summary>
/// <param name="car">Добавляемый автомобиль</param>
/// <param name="position">Позиция</param>
/// <returns></returns>
public int Insert(T tank, int position)
{
if (position < 0 || position >= Count)
return -1;
if (_places[position] == null)
{
_places[position] = tank;
return position;
}
int index = -1;
for (int i = position; i < Count; i++)
{
if (_places[i] == null)
{
index = i; break;
}
}
if (index < 0)
return -1;
for (int i = index; index > position; i--)
{
_places[i] = _places[i - 1];
}
_places[position] = tank;
return position;
}
/// <summary>
/// Удаление объекта из набора с конкретной позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public bool Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
public bool Insert(T tank, int position)
{
if (position < 0 || position >= _maxCount)
return false;
}
_places[position] = null;
if (Count >= _maxCount)
return false;
_places.Insert(0, tank);
return true;
}
/// <summary>
/// Получение объекта из набора по позиции
/// </summary>
/// <param name="position"></param>
/// <returns></returns>
public T? Get(int position)
public bool Remove(int position)
{
// проверка позиции
if (position < 0 || position >= Count)
if (position < 0 || position > _maxCount)
return false;
if (position >= Count)
return false;
_places.RemoveAt(position);
return true;
}
public T? this[int position]
{
get
{
if (position < 0)
{
return null;
}
return _places[position];
}
set
{
if (position < 0)
{
return;
}
_places[position] = value;
}
}
public IEnumerable<T?> GetTanks(int? maxTanks = null)
{
for (int i = 0; i < _places.Count; ++i)
{
yield return _places[i];
if (maxTanks.HasValue && i == maxTanks.Value)
{
yield break;
}
}
}
}
}

View File

@ -57,14 +57,13 @@ namespace Tank.Generics
/// <param name="collect"></param>
/// <param name="obj"></param>
/// <returns></returns>
public static int operator +(TanksGenericCollection<T, U> collect, T?
obj)
public static bool operator +(TanksGenericCollection<T, U> collect, T? obj)
{
if (obj == null)
{
return -1;
return false;
}
return collect._collection.Insert(obj);
return (bool)collect?._collection.Insert(obj);
}
/// <summary>
/// Перегрузка оператора вычитания
@ -72,16 +71,16 @@ namespace Tank.Generics
/// <param name="collect"></param>
/// <param name="pos"></param>
/// <returns></returns>
public static bool operator -(TanksGenericCollection<T, U> collect, int
pos)
public static T? operator -(TanksGenericCollection<T, U> collect, int pos)
{
T? obj = collect._collection.Get(pos);
T? obj = collect._collection[pos];
if (obj != null)
{
return collect._collection.Remove(pos);
collect._collection.Remove(pos);
}
return false;
return obj;
}
/// <summary>
/// Получение объекта IMoveableObject
/// </summary>
@ -89,8 +88,9 @@ namespace Tank.Generics
/// <returns></returns>
public U? GetU(int pos)
{
return (U?)_collection.Get(pos)?.GetMoveableObject;
return (U?)_collection[pos]?.GetMoveableObject;
}
/// <summary>
/// Вывод всего набора объектов
/// </summary>
@ -128,16 +128,16 @@ namespace Tank.Generics
/// <param name="g"></param>
private void DrawObjects(Graphics g)
{
int width = _pictureWidth / _placeSizeWidth;
int height = _pictureHeight / _placeSizeHeight;
for (int i = 0; i < _collection.Count; i++)
int i = 0;
foreach (var tank in _collection.GetTanks())
{
DrawingArmoredCar? tank = _collection.Get(i);
if (tank != null)
{
tank.SetPosition(i % width * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
tank.SetPosition((i % (_pictureWidth / _placeSizeWidth)) * _placeSizeWidth, (i / (_pictureWidth / _placeSizeWidth)) * _placeSizeHeight);
tank.DrawTransport(g);
}
i++;
}
}
}

View File

@ -0,0 +1,88 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tank.Generics;
using Tank.DrawingObjects;
using Tank.MovementStrategy;
namespace Tank.Generics
{
/// <summary>
/// Класс для хранения коллекции
/// </summary>
internal class TanksGenericStorage
{
/// <summary>
/// Словарь (хранилище)
/// </summary>
readonly Dictionary<string, TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>> _tankStorages;
/// <summary>
/// Возвращение списка названий наборов
/// </summary>
public List<string> Keys => _tankStorages.Keys.ToList();
/// <summary>
/// Ширина окна отрисовки
/// </summary>
private readonly int _pictureWidth;
/// <summary>
/// Высота окна отрисовки
/// </summary>
private readonly int _pictureHeight;
public TanksGenericStorage(int pictureWidth, int pictureHeight)
{
_tankStorages = new Dictionary<string,TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>>();
_pictureWidth = pictureWidth;
_pictureHeight = pictureHeight;
}
/// <summary>
/// Добавление набора
/// </summary>
/// <param name="name">Название набора</param>
public void AddSet(string name)
{
if (_tankStorages.ContainsKey(name))
{
return;
}
else
{
_tankStorages[name] = new TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>(_pictureWidth, _pictureHeight);
}
}
/// <summary>
/// Удаление набора
/// </summary>
/// <param name="name">Название набора</param>
public void DelSet(string name)
{
if (_tankStorages.ContainsKey(name))
{
_tankStorages.Remove(name);
}
else
{
return;
}
}
/// <summary>
/// Доступ к набору
/// </summary>
/// <param name="ind"></param>
/// <returns></returns>
public TanksGenericCollection<DrawingArmoredCar, DrawingObjectArmoredCar>?
this[string ind]
{
get
{
if (_tankStorages.ContainsKey(ind))
{
return _tankStorages[ind];
}
return null;
}
}
}
}

View File

@ -3,7 +3,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// using Tank.Drawnings;
using Tank.DrawingObjects;
namespace Tank.MovementStrategy