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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
| unit Graph;
uses GraphABC;
type
TColor = Color;
TPoint = Point;
type
///Предоставляет процедуры и функции для работы с растровой графикой.
TDraw = class
public
class procedure RDrawLine(x, y, x1, y1: real) := Line(Round(x), Round(y), Round(x1), Round(y1));
class procedure RDrawRect(x, y, x1, y1: real) := DrawRectangle(Round(x), Round(y), Round(x1), Round(y1));
class procedure RFillRect(x, y, x1, y1: real) := FillRectangle(Round(x), Round(y), Round(x1), Round(y1));
class procedure RDrawAndFillRect(x, y, x1, y1: real) := Rectangle(Round(x), Round(y), Round(x1), Round(y1));
class procedure RDrawEllipse(x, y, x1, y1: real) := DrawEllipse(Round(x), Round(y), Round(x1), Round(y1));
class procedure RFillEllipse(x, y, x1, y1: real) := FillEllipse(Round(x), Round(y), Round(x1), Round(y1));
class procedure RDrawAndFillEllipse(x, y, x1, y1: real) := Ellipse(Round(x), Round(y), Round(x1), Round(y1));
end;
type
ActionEnum = (Up, Down);
///Класс аргументов события.
TEventArgs = class
private
_ActionType: ActionEnum;
public
///Тип события
property ActionType: ActionEnum read _ActionType;
constructor(act: ActionEnum);
begin
_ActionType := act;
end;
end;
type
MouseClickEnum = (NoneClick, RightCLick, LeftClick);
///Предоставляет аргументы событий OnMouseClick, OnMouseMove.
TMouseEventArgs = class(TEventArgs)
private
_ClickState: MouseClickEnum;
_MoveState: boolean;
_X, _Y: integer;
public
///Нажатая/отжатая кнопка мыши
property MouseButton: MouseClickEnum read _ClickState;
///Указывает двигалась ли мышь на момент наступления события
property MoveState: boolean read _MoveState;
///X координата курсора на момент наступления события
property X: integer read _X;
///Y координата курсора на момент наступления события
property Y: integer read _Y;
constructor(cs: MouseClickEnum; act: ActionEnum; ms: boolean; cx, cy: integer);
begin
inherited Create(act);
_ClickState := cs;
_MoveState := ms;
_X := cx;_Y := cy;
end;
function ToString() := Format('event: {0}, {1}', _X, _Y);
procedure Print() := Write(ToString());
procedure Println() := Writeln(ToString());
end;
type
///Предоставляет аргументы событий OnKeyDown, OnKeyUp.
TKeyEventArgs = class(TEventArgs)
private
_KeyCode: integer;
public
///Код клавиши
property KeyCode: integer read _KeyCode;
constructor(kc: integer; act: ActionEnum);
begin
inherited Create(act);
_KeyCode := kc;
end;
function ToString() := Format('event: {0}', _KeyCode);
procedure Print() := Write(ToString());
procedure Println() := Writeln(ToString());
end;
type
///Стиль объекта.
TObjectStyle = record
public
_BorderColor, _FillColor: TColor;
_BorderWidth: integer;
public
///Цвет границы
property BorderColor: TColor read _BorderColor write _BorderColor;
///Цвет заливки
property FillColor: TColor read _FillColor write _FillColor;
///Толщина границы
property BorderWidth: integer read _BorderWidth write _BorderWidth;
constructor(bc: TColor := clBlack; fc: TColor := clWhite; bw: integer := 1);
begin
BorderColor := bc;
FillColor := fc;
BorderWidth := bw;
end;
///Устанавливает настройки пера и кисти в соответствии с настройками данного объекта.
procedure SetSettingsBySelf();
begin
SetPenColor(_BorderColor);
SetBrushColor(_FillColor);
SetPenWidth(_BorderWidth);
end;
end;
type
///Представляет тип процедуры, вызываемой при событиях OnMouseClick, OnMouseMove.
TOnMouseActionFunc = procedure(sender: object; eventArgs: TMouseEventArgs);
///Представляет тип процедуры, вызываемой при событиях OnKeyDown, OnKeyUp.
TOnKeyActionFunc = procedure(sender: object; eventArgs: TKeyEventArgs);
type
///Главный игровой класс.
TGameObjectBox = class
public
///Событие нажатия кнопки мыши
event OnMouseClick: TOnMouseActionFunc;
///Событие движения курсора
event OnMouseMove: TOnMouseActionFunc;
///Событие нажатия клавиши
event OnKeyDown: TOnKeyActionFunc;
///Событие отжатия клавиши
event OnKeyUp: TOnKeyActionFunc;
private
_A, _B: TPoint;
function PointIsInBox(p: TPoint) := (p.X >= _A.X) and (p.X <= _B.X) and (p.Y >= _A.Y) and (p.Y <= _B.Y);
public
///Первая вершина прямоугольника
property A: TPoint read _A write _A;
///Вторая вершина прямоугольника
property B: TPoint read _B write _B;
constructor(pA, pB: TPoint);
begin
A := pA;B := pB;
end;
///Указывает пересекаются ли границы объектов класса TGameObjectBox.
function IsCollidedWith(box: TGameObjectBox) := PointIsInBox(box.A) or PointIsInBox(box.B);
procedure TryOnMouseClick(e: TMouseEventArgs);
begin
if OnMouseClick <> nil then
OnMouseClick(self, e);
end;
procedure TryOnMouseMove(e: TMouseEventArgs);
begin
if OnMouseMove <> nil then
OnMouseMove(self, e);
end;
procedure TryOnKeyDown(e: TKeyEventArgs);
begin
if OnKeyDown <> nil then
OnKeyDown(self, e);
end;
procedure TryOnKeyUp(e: TKeyEventArgs);
begin
if OnKeyUp <> nil then
OnKeyUp(self, e);
end;
end;
type
///Тип игрового объекта.
TGameObject = class(TGameObjectBox)
private
_ObjectStyle: TObjectStyle;
_IsVisible: boolean;
public
///Стиль объекта
property ObjectStyle: TObjectStyle read _ObjectStyle write _ObjectStyle;
///Видим ли объект
property IsVisible: boolean read _IsVisible write _IsVisible;
constructor(oS: TObjectStyle);
begin
ObjectStyle := oS;
IsVisible := true;
end;
///Перерисовывает объект (вызывается автоматически).
procedure Draw(); virtual;
begin
if not _IsVisible then exit;
_ObjectStyle.SetSettingsBySelf();
end;
end;
///Тип отрезка.
TGameLine = class(TGameObject)
public
constructor(pA, pB: TPoint);
begin
A := pA;B := pB;
IsVisible := true;
end;
///Перерисовывает объект (вызывается автоматически).
procedure Draw(); override;
begin
inherited Draw();
TDraw.RDrawLine(_A.X, _A.Y, _B.X, _B.Y);
end;
end;
///Тип прямоугольника.
TGameRect = class(TGameObject)
public
constructor(pA, pB: TPoint);
begin
A := pA;B := pB;
IsVisible := true;
end;
///Перерисовывает объект (вызывается автоматически).
procedure Draw(); override;
begin
inherited Draw();
TDraw.RDrawAndFillRect(_A.X, _A.Y, _B.X, _B.Y);
end;
end;
///Тип прямоугольника.
TGameEllipse = class(TGameObject)
public
constructor(pA, pB: TPoint);
begin
A := pA;B := pB;
IsVisible := true;
end;
///Перерисовывает объект (вызывается автоматически).
procedure Draw(); override;
begin
inherited Draw();
TDraw.RDrawAndFillEllipse(_A.X, _A.Y, _B.X, _B.Y);
end;
end;
type
///Управляет игровым процессом.
TGame = class
private
class _Objects: List<TGameObject>;
class _Background: TColor;
class function GetItem(i: integer) := _Objects[i];
class function GetCount() := _Objects.Count;
public
class property Items[i: integer]: TGameObject read GetItem;default;
///Цвет фона сцены
class property Background: TColor read _Background write _Background;
///Количество объектов
class property Count: integer read GetCount;
class constructor();
begin
if _Objects = nil then
begin
_Objects := new List<TGameObject>();
_Background := clWhite;
end
end;
class procedure RedrawAll();
begin
if Window.Height = 0 then exit;
try
ClearWindow(_Background);
for var i := 0 to Pred(_Objects.Count) do
lock _Objects[i] do
_Objects[i].Draw();
Redraw();
except
on System.Exception do end;
end;
///Добавляет объект на сцену.
class procedure Add(obj: TGameObject) := _Objects.Add(obj);
///Удаляет объект со сцены.
class procedure Remove(obj: TGameObject) := _Objects.Remove(obj);
end;
function MouseClickEnumFromCode(mb: integer): MouseClickEnum;
begin
case mb of
0: Result := MouseClickEnum.NoneClick;
1: Result := MouseClickEnum.LeftClick;
2: Result := MouseClickEnum.RightCLick
else raise new System.Exception('Неизвестный код.');
end;
end;
///Обработчик события OnMouseDown.
procedure MouseDown(x, y, mb: integer);
begin
var SystemMouseEventArgs := new TMouseEventArgs(MouseClickEnumFromCode(mb), ActionEnum.Down, false, x, y);
for var i := 0 to Pred(TGame.Count) do
TGame[i].TryOnMouseClick(SystemMouseEventArgs);
end;
///Обработчик события OnMouseUp.
procedure MouseUp(x, y, mb: integer);
begin
var SystemMouseEventArgs := new TMouseEventArgs(MouseClickEnumFromCode(mb), ActionEnum.Up, false, x, y);
for var i := 0 to Pred(TGame.Count) do
TGame[i].TryOnMouseClick(SystemMouseEventArgs);
end;
///Обработчик события OnMouseMove.
procedure MouseMove(x, y, mb: integer);
begin
var SystemMouseEventArgs := new TMouseEventArgs(MouseClickEnumFromCode(mb), ActionEnum.Up, true, x, y);
for var i := 0 to Pred(TGame.Count) do
TGame[i].TryOnMouseMove(SystemMouseEventArgs);
end;
///Обработчик события OnKeyDown.
procedure KeyDown(key: integer);
begin
var SystemKeyEventArgs := new TKeyEventArgs(key, ActionEnum.Down);
for var i := 0 to Pred(TGame.Count) do
TGame[i].TryOnKeyDown(SystemKeyEventArgs);
end;
///Обработчик события OnKeyUp.
procedure KeyUp(key: integer);
begin
var SystemKeyEventArgs := new TKeyEventArgs(key, ActionEnum.Up);
for var i := 0 to Pred(TGame.Count) do
TGame[i].TryOnKeyUp(SystemKeyEventArgs);
end;
initialization
LockDrawing();
TGame.Create();
OnMouseDown := MouseDown;
OnMouseUp := MouseUp;
OnMouseMove := MouseMove;
OnKeyDown := KeyDown;
OnKeyUp := KeyUp;
finalization
while true do
TGame.RedrawAll();
end. |