Федеральное агенство воздушного транспорта (росавиация)
ФЕДЕРАЛЬНОЕ ГОСУДАРСТВЕННОЕ БЮДЖЕТНОЕ ОБРАЗОВАТЕЛЬНОЕ УЧРЕЖДЕНИЕ ВЫСШЕГО ОБРАЗОВАНИЯ
«МОСКОВСКИЙ ГОСУДАРСТВЕННЫЙ ТЕХНИЧЕСКИЙ УНИВЕРСИТЕТ ГРАЖДАНСКОЙ АВИАЦИИ» (МГТУ ГА)
Кафедра вычислительных машин, комплексов, сетей и систем.
Лабораторная работа защищена с оценкой ____________________
____________________
(подпись преподавателя, дата)
ЛАБОРАТОРНАЯ РАБОТА №2
по дисциплине «Современные технологии программирования».
Вариант 16
Тема: «Эволюционный подход к разработке программ.»
Выполнила студентка группы ИС2-1
Магальник Екатерина Борисовна
Руководитель: Гаранин Сергей Александрович
МОСКВА – 2023
3.1 Цель лабораторной работы
Целью лабораторной работы является:
- освоение принципов поэтапного проектирования и реализации приложения;
- овладение методологией интерактивности и постепенного увеличения функциональности программного продукта, когда решения, принятые на очередном этапе, существенно влияют на последующие этапы проектирования
3.3 Задание на выполнение лабораторной работы
Разработать Windows-приложение в соответствием с вариантом задания. Для создания графического интерфейса пользователя с помощью платформы .NET использовать технологию - Window Forms.
Для создания проекта использовать среду разработки Visual Studio и язык программирования C#.
Использовать эволюционный подход при разработке программного обеспечения.
Листинг программы:
Файл Form1.Designers.cs:
namespace лаба_2_3_сем_шарп
{
partial class Form1
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
int M = 12, N = 12;
RandomMatrix matr;
Position pos;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
class Position
{
public int x, y;
public Position(int xi, int yi) { x = xi; y = yi; }
public Position(Position p) { x = p.x; y = p.y; }
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(Form1));
label1 = new Label();
dataGridView1 = new DataGridView();
button1 = new Button();
((System.ComponentModel.ISupportInitialize)dataGridView1).BeginInit();
SuspendLayout();
//
// label1
//
resources.ApplyResources(label1, "label1");
label1.Name = "label1";
//
// dataGridView1
//
resources.ApplyResources(dataGridView1, "dataGridView1");
dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
dataGridView1.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
dataGridView1.ColumnHeadersVisible = false;
dataGridView1.Name = "dataGridView1";
dataGridView1.RowHeadersVisible = false;
dataGridView1.RowTemplate.Height = 29;
dataGridView1.CellContentClick += dataGridView1_CellContentClick;
//
// button1
//
resources.ApplyResources(button1, "button1");
button1.Name = "button1";
button1.UseVisualStyleBackColor = true;
button1.Click += button1_Click;
//
// Form1
//
resources.ApplyResources(this, "$this");
AutoScaleMode = AutoScaleMode.Font;
Controls.Add(button1);
Controls.Add(dataGridView1);
Controls.Add(label1);
Name = "Form1";
Load += Form1_Load;
((System.ComponentModel.ISupportInitialize)dataGridView1).EndInit();
ResumeLayout(false);
PerformLayout();
}
class RandomMatrix
{
int mm, nn;
public sbyte[,] matrix; //ссылка на массив элементов
public RandomMatrix(int m, int n)
{
mm = m;
nn = n;
matrix = new sbyte[m, n];
Random gen = new Random();
for (int i = 0; i < m; i++)
{
for (int j = 0; j < n; j++)
{
matrix[i, j] = (sbyte)gen.Next(2);
}
}
}
public Position[] region(Position p)
{ // ближайшие ячейки
Position[] res = null;
if (p.x > 0 & p.x < nn - 1 & p.y > 0 & p.y < mm - 1)
{
res = new Position[5];
res[0] = new Position(p);
res[1] = new Position(p.x + 1, p.y);
res[2] = new Position(p.x, p.y - 1);
res[3] = new Position(p.x - 1, p.y);
res[4] = new Position(p.x, p.y + 1);
}
if (p.x == 0 & p.y == 0)
{
res = new Position[3]
{new Position(p), new Position(p.x+1, p.y), new Position(p.x, p.y+1)};
}
if (p.x == nn - 1 & p.y == 0)
{
res = new Position[3]
{new Position(p), new Position(p.x-1, p.y), new Position(p.x, p.y+1)};
}
if (p.x == nn - 1 & p.y == mm - 1)
{
res = new Position[3]
{new Position(p), new Position(p.x-1, p.y), new Position(p.x, p.y-1)};
}
if (p.x == 0 & p.y == mm - 1)
{
res = new Position[3]
{new Position(p), new Position(p.x+1, p.y), new Position(p.x, p.y-1)};
}
if (p.x == 0 & p.y != 0 & p.y != mm - 1)
{
res = new Position[4]
{new Position(p), new Position(p.x+1, p.y),
new Position(p.x, p.y+1), new Position(p.x, p.y-1)};
}
if (p.x == nn - 1 & p.y != 0 & p.y != mm - 1)
{
res = new Position[4]
{new Position(p), new Position(p.x-1, p.y),
new Position(p.x, p.y+1), new Position(p.x, p.y-1)};
}
if (p.y == 0 & p.x != nn - 1 & p.x != 0)
{
res = new Position[4]
{new Position(p), new Position(p.x+1, p.y),
new Position(p.x-1, p.y), new Position(p.x, p.y+1)};
}
if (p.y == mm - 1 & p.x != nn - 1 & p.x != 0)
{
res = new Position[4]
{new Position(p), new Position(p.x+1, p.y),
new Position(p.x-1, p.y), new Position(p.x, p.y-1)};
}
// Проверка найденных позиций:
int r = 0;
for (int k = 0; k < res.Length; k++)
{
if (matrix[res[0].y, res[0].x] ==
matrix[res[k].y, res[k].x]) r++;
}
Position[] temp = new Position[r];
for (int k = 0, j = 0; k < res.Length; k++)
if (matrix[res[0].y, res[0].x] == matrix[res[k].y, res[k].x])
temp[j++] = res[k];
return temp;
} // region()
public void spot(Position p, ref Position[] res)
{
int size = res.Length;
Position[] temp = res;
res = new Position[size + 1];
temp.CopyTo(res, 0);
res[size] = p;
Position[] path = region(p);
foreach (Position g in path)
matrix[g.y, g.x] += 2; // Помечаем выделенные элементы
for (int i = 1; i < path.Length; i++)
{
matrix[path[i].y, path[i].x] -= 2;
spot(path[i], ref res);
}
return;
} // spot()
}
#endregion
private Label label1;
private DataGridView dataGridView1;
private Button button1;
}
}
Файл Form1.cs:
using System;
using System.Windows.Forms;
namespace лаба_2_3_сем_шарп //называется по имени проекта, иначе нельзя
{
public partial class Form1 : Form
{
public Form1()
{
matr = new RandomMatrix(M, N);
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
dataGridView1.ColumnCount = N;
dataGridView1.RowCount = M;
dataGridView1.Rows[0].Cells[0].Selected = false; //снимаем выделение
for (int i = 0; i < M; i++)
{
for (int j = 0; j < N; ++j)
{
dataGridView1[j, i].Value = matr.matrix[i, j] == 0 ? "0" : "1";
}
}
}
private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
// Ищем выделенную ячейку (K - количество выделенных):
int K = 0;
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
if (dataGridView1.Rows[i].Cells[j].Selected == true)
{
pos = new Position(j, i); K++;
}
if (K == 0)
{
MessageBox.Show("There is no cell selected!");
return;
}
if (K > 1)
{
MessageBox.Show("Select one cell only!");
for (int i = 0; i < M; i++)
for (int j = 0; j < N; j++)
dataGridView1.Rows[i].Cells[j].Selected = false;
return;
}
else
{
MessageBox.Show("x ="+pos.x +" y ="+pos.y);
Position[] cla = new Position[0];
matr.spot(pos, ref cla);
foreach (Position s in cla)
{
dataGridView1.Rows[s.y].Cells[s.x].Selected = true;
matr.matrix[s.y, s.x] -= 2;
} // foreach
} // else
MessageBox.Show("x ="+pos.x +" y =" +pos.y);
} // button1_Click()
}
}
Файл Form1.cs [Designers]:
Результат работы программы:
