1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
| using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace lab2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Cockroach workCockroach;//рабочий Таракан - активный Таракан, который будет выполнять алгоритм
PictureBox workpb;//рабочее поле PictureBox - поле на которой будет рабочий Таракан
List<Cockroach> LC;//Список для хранения созданных Тараканов
List<PictureBox> PB;//Список для хранения созданных объектов PictureBox
private int AlgStep=0;
private void Form1_Load(object sender, EventArgs e)
{
LC = new List<Cockroach>();
PB = new List<PictureBox>();
}
private void NewBtn_Click(object sender, EventArgs e)
{
Cockroach cockroach = new Cockroach(new Bitmap("cockroach1.jpg"));
PictureBox p = new PictureBox();
cockroach.Show(p, Field);
p.MouseMove += new MouseEventHandler(IMouseMove);
p.MouseDown += new MouseEventHandler(IMouseDown);
PB.Add(p);
LC.Add(cockroach);
workCockroach = cockroach;
workpb = p;
int[] a = new int[10];
}
private void IMouseDown(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
int k = PB.IndexOf(sender as PictureBox);//запоминаем номер нажатого компонента PictureBox
workpb = sender as PictureBox;//объявляет его рабочим
workCockroach = LC[k];//по найденному номеру находим Таракана в списке
}
}
private void IMouseMove(object sender, MouseEventArgs e)
{
if (e.Button == MouseButtons.Left)
{
PictureBox picture = sender as PictureBox;
picture.Tag = new Point(e.X, e.Y);//запоминаем координаты мыши на момент начала перетаскивания
picture.DoDragDrop(sender, DragDropEffects.Move);//начинаем перетаскивание ЧЕГО и с КАКИМ ЭФФЕКТОМ
}
}
private void panel1_DragDrop(object sender, DragEventArgs e)
{
}
private void panel1_DragEnter(object sender, DragEventArgs e)
{
}
private void UpBtn_Click(object sender, EventArgs e)
{
Algorithm.Items.Add((sender as Button).Text);
}
private void Field_DragDrop(object sender, DragEventArgs e)
{
//извлекаем PictureBox
PictureBox picture = (PictureBox)e.Data.GetData(typeof(PictureBox));
Panel pan = sender as Panel;
//получаем клиентские координаты в момент отпускания кнопки
Point pointDrop = pan.PointToClient(new Point(e.X, e.Y));
//извлекаем клиентские координаты мыши в момент начала перетскивания
Point pointDrag = (Point)picture.Tag;
//вычисляем и устанавливаем Location для PictureBox в Panel
pointDrop.Offset(-pointDrag.X, -pointDrag.Y);
picture.Location = pointDrop;
//при перетаскиваем изменяет свойства X и Y Таракана
foreach (Cockroach t in LC)
if (t == workCockroach)
{
t.X = picture.Location.X;
t.Y = picture.Location.Y;
workCockroach.X = picture.Location.X;
workCockroach.Y = picture.Location.Y;
break;
}
picture.Parent = pan;
}
private void Field_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(PictureBox)))
{
e.Effect = DragDropEffects.Move;
}
}
private void RunBtn_Click(object sender, EventArgs e)
{
AlgStep = 0;
timerAlgorithm.Start();
}
private void timerAlgorithm_Tick(object sender, EventArgs e)
{
if (AlgStep == Algorithm.Items.Count) //конец алгоритма
{
timerAlgorithm.Stop(); //выключение таймера
}
else//выполнение команды из списка
{
string s = (string)Algorithm.Items[AlgStep];
Algorithm.SetSelected(AlgStep, true);
if (s == "Step")
workCockroach.Step(Field.CreateGraphics(),workpb);
else
if (s == "PenUp")
workCockroach.PenDown = false;
else
if (s == "PenDown") workCockroach.PenDown = true;
else
workCockroach.ChangeTrend(s[0]);
workCockroach.RePaint(workpb);
AlgStep++;
}
}
private void ClearBtn_Click(object sender, EventArgs e)
{
Algorithm.Items.Clear();
}
private void button3_Click(object sender, EventArgs e)
{
int i = Algorithm.SelectedIndex;
Algorithm.Items.RemoveAt(Algorithm.SelectedIndex);
if (i< Algorithm.Items.Count)
Algorithm.SetSelected(i, true);
}
}
}
namespace lab2
{
class Cockroach //Класс таракан
{
enum direction : byte { Up, Right, Down, Left };
//Для описания Таракана достаточно трех полей: изображения, направления и шага
Bitmap Image;
direction trend = direction.Right;
const int step = 30;
public bool PenDown = false;
//Конструктор с параметром – изображение
public Cockroach(Bitmap _Image)
{
Image = _Image;
}
//Методы-свойства X и Y – вычисление координат
public int X
{
set;
get;
}
public int Y
{
set;
get;
}
//Изображение объекта Таракан в PictureBox – используется при изменении направления Таракана
public void RePaint(PictureBox p)
{
p.Bounds = new Rectangle(X, Y, Image.Width, Image.Height);//создание новых границ изображения для PictureBox
p.Image = Image;
}
//Изображение Таракана на поле
public void Show(PictureBox p, Panel owner)
{
X = (owner.Width - Image.Width) / 2;
Y = (owner.Height - Image.Height) / 2;
RePaint(p);
owner.Controls.Add(p);// добавляем PictureBox к элементу Panel
}
//Выполнение шага в заданном направлении
public void Step(Graphics g, PictureBox pb)
{
SolidBrush brush = new SolidBrush(Color.Black);
switch (trend)
{
case direction.Right: {
X += step;
this.RePaint(pb);
if (PenDown == true)
g.FillEllipse(brush, pb.Location.X+pb.Size.Width/2-step, pb.Location.Y + pb.Size.Height / 2, 3,3);
} break;
case direction.Down:
{
Y += step;
this.RePaint(pb);
if (PenDown == true)
g.FillEllipse(brush, pb.Location.X + pb.Size.Width / 2, pb.Location.Y + pb.Size.Height / 2-step, 3, 3);
}
break;
case direction.Left:
{
X -= step;
this.RePaint(pb);
if (PenDown == true)
g.FillEllipse(brush, pb.Location.X + pb.Size.Width / 2 + step, pb.Location.Y + pb.Size.Height / 2, 3, 3);
}
break;
case direction.Up:
{
Y -= step;
this.RePaint(pb);
if (PenDown == true)
g.FillEllipse(brush, pb.Location.X + pb.Size.Width / 2 , pb.Location.Y + pb.Size.Height / 2+ step, 3, 3);
}
break;
}
}
//Изменение направления, параметр – первая буква направления
public void ChangeTrend(char c)
{
direction newtrend = trend;
for (direction y = direction.Up; y <= direction.Left; y++)
if (char.ToLower(c) == char.ToLower(y.ToString()[0]))
{
newtrend = y;
break;
}
switch (trend)
{
case direction.Up:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
}
break;
case direction.Right:
switch (newtrend)
{
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
}
break;
case direction.Down:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Left: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
}
break;
case direction.Left:
switch (newtrend)
{
case direction.Right: Image.RotateFlip(RotateFlipType.Rotate180FlipNone); break;
case direction.Down: Image.RotateFlip(RotateFlipType.Rotate270FlipNone); break;
case direction.Up: Image.RotateFlip(RotateFlipType.Rotate90FlipNone); break;
}
break;
}
trend = newtrend;
}
}
} |