aboutsummaryrefslogtreecommitdiff
path: root/Занимательное программирование/7/5_snake/Unit1.pas
blob: a26f2004ddcf337cac070144a6c1595ec2d53265 (plain)
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
unit Unit1;

{$MODE objfpc}{$H+}

interface

uses
  LCLType, SysUtils, Classes, Graphics, Controls, Forms, ExtCtrls, StdCtrls;

type
  TForm1 = class(TForm)
    Screen: TImage;
    ImageList: TImageList;
    Label1: TLabel;
    SnakeLenLabel: TLabel;
    procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
    procedure FormActivate(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;

type Coords = record { Координаты клетки }
  x, y: Integer
end;

const
  { Размеры поля }
  FieldHeight = 30;
  FieldWidth = 40;
  { Скорость игры }
  MSecsPerFrame = 150;
  CellSize = 32;

var
  Form1: TForm1;
  Snake: array[1..FieldHeight * FieldWidth] of Coords; { Удав }
  SnakeLength: Integer; { Длина удава }
  dx, dy: Integer; { Текущее направление }
  Background, Body: TBitmap; { Элементы игрового поля }
  Head, Tail: array[1..4] of TBitmap;
  FirstRun: Boolean = true; { Индикатор первого запуска }
  Number: Coords; { Положение текущей цифры }
  CurNumber: Integer; { и ее значение }

implementation

{$R *.lfm}

{-------------------------------------------------------------------}
{ Загрузка картинок (элементов игры) }
procedure LoadBitmaps;
var
  i: Integer;
begin
  Background := TBitmap.Create;
  Body := TBitmap.Create;

  for i := 1 to 4 do
  begin
    Head[i] := TBitmap.Create;
    Tail[i] := TBitmap.Create
  end;
  Form1.ImageList.GetBitmap(10, Head[1]);
  Form1.ImageList.GetBitmap(11, Head[2]);
  Form1.ImageList.GetBitmap(12, Head[3]);
  Form1.ImageList.GetBitmap(13, Head[4]);
  Form1.ImageList.GetBitmap(14, Tail[1]);
  Form1.ImageList.GetBitmap(15, Tail[2]);
  Form1.ImageList.GetBitmap(16, Tail[3]);
  Form1.ImageList.GetBitmap(17, Tail[4]);
  Form1.ImageList.GetBitmap(9, Body);

  Background.SetSize(CellSize, CellSize);
  Background.Canvas.Brush.Color := clLtGray;
  Background.Canvas.FillRect(0, 0, CellSize, CellSize)
end;

{-------------------------------------------------------------------}
{ Освобождение памяти }
procedure FreeBitmaps;
var
  i: Integer;
begin
  Background.Free;
  Body.Free;
  for i := 1 to 4 do
  begin
    Head[i].Free;
    Tail[i].Free
  end
end;

{-------------------------------------------------------------------}
{ Очистка экрана }
procedure ClearField;
var i, j: Integer;
begin
  for i := 0 to FieldWidth do
    for j := 0 to FieldHeight do
      Form1.Screen.Canvas.Draw(i * CellSize, j * CellSize, Background)
end;

{-------------------------------------------------------------------}
{ Инициализация удава }
procedure InitSnake;
begin
  SnakeLength := 3; { Изначально длина равна трем (голова, тело и хвост) }
  { Координаты сегментов }
  Snake[1].x := 0;
  Snake[2].x := 1;
  Snake[3].x := 2;
  Snake[1].y := 0;
  Snake[2].y := 0;
  Snake[3].y := 0;
  { Изначально удав ползет вправо }
  dx := 1;
  dy := 0;
  { Рисуем удава }
  Form1.Screen.Canvas.Draw(0, 0, Tail[2]);
  Form1.Screen.Canvas.Draw(CellSize, 0, Body);
  Form1.Screen.Canvas.Draw(CellSize * 2, 0, Head[2])
end;

{-------------------------------------------------------------------}
{ Определение статуса клетки (удав/свободно) }
function IsSnake(X, Y: Integer) : Boolean;
var i: Integer;
begin
  IsSnake := false;
  for i := 1 to SnakeLength do
    if (Snake[i].x = X) and (Snake[i].y = Y) then
      IsSnake := true
end;

{-------------------------------------------------------------------}
{ Разместить случайную цифру (на игровом поле) }
procedure PlaceNumber;
var Temp: TBitmap;
begin
  Temp := TBitmap.Create; { Временыый объект для хранения картинки }
  repeat
    Number.x := Random(FieldWidth); { Выбираем случайные координаты }
    Number.y := Random(FieldHeight)
  until not isSnake(Number.x, Number.y); { пока они не окажутся допустимыми }

  CurNumber := 1 + Random(9); { Выбираем случайное значение цифры }
  { Рисуем цифру на экране }
  Form1.ImageList.GetBitmap(CurNumber - 1, Temp);
  Form1.Screen.Canvas.Draw(CellSize * Number.x, CellSize * Number.y, Temp);
  Temp.Free
end;

{-------------------------------------------------------------------}
{ Обработка клавиш }
procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState);
begin
  case Key of
    VK_LEFT:
      begin
        dx := -1;
        dy := 0
      end;
    VK_RIGHT:
      begin
        dx := 1;
        dy := 0
      end;
    VK_UP:
      begin
        dx := 0;
        dy := -1
      end;
    VK_DOWN:
      begin
        dx := 0;
        dy := 1
      end
    end
end;

function GetDirectionIndex(dx, dy: Integer): Integer;
begin
  if (dx = -1) and (dy = 0) then
    Result := 4
  else if (dx = 1) and (dy = 0) then
    Result := 2
  else if (dx = 0) and (dy = -1) then
    Result := 1
  else if (dx = 0) and (dy = 1) then
    Result := 3
  else
    Result := 0
end;

{-------------------------------------------------------------------}
{ Главная процедура }
procedure TForm1.FormActivate(Sender: TObject);
var
  oldtime: TDateTime;
  NewX, NewY: Integer; { Координаты целевой клетки }
  ToGrow, DirectionIndex: Integer;
begin
  if not FirstRun then
    Exit; { Процедура работает лишь при первом запуске }

  FirstRun := false;
  Randomize;
  LoadBitmaps; { Загрузка изображений }

  while ID_CANCEL <> Application.MessageBox('OK - запуск, Cancel - выход', 'Snake', MB_OKCANCEL) do
  begin
    ClearField; { Очистка игрового поля }
    InitSnake; { Создание удава }
    PlaceNumber; { Генерация случайной цифры }
    ToGrow := 0; { Количество сегментов, на которое должен вырасти удав }
    { Главный цикл }
    while true do
    begin
      oldtime := Now;
      { Определение целевой клетки }
      NewX := Snake[SnakeLength].x + dx;
      NewY := Snake[SnakeLength].y + dy;

      { Если сделан недопустимый ход, конец игры }
      if (NewX < 0) or (NewX >= FieldWidth) or (NewY < 0) or
          (NewY >= FieldHeight) or IsSnake(NewX, NewY) then
        Break;   { Конец игры }

      { Если текущая клетка содержит цифру программируем рост удава }
      if (NewX = Number.x) and (NewY = Number.y) then
      begin
        ToGrow := ToGrow + CurNumber;
        { Генерируем очередную цифру }
        PlaceNumber
      end;

      if ToGrow > 0 then { Если удав растет }
      begin
        ToGrow := ToGrow - 1;
        SnakeLength := SnakeLength + 1 { Увеличиваем его длину }
      end;
      { Обновление координат удава }
      Snake[SnakeLength + 1].x := NewX;
      Snake[SnakeLength + 1].y := NewY;

      DirectionIndex := GetDirectionIndex(dx, dy);

      Form1.Screen.Canvas.Draw(CellSize * Snake[1].x, CellSize * Snake[1].y, Background);
      Form1.Screen.Canvas.Draw(CellSize * Snake[2].x, CellSize * Snake[2].y,
          Tail[DirectionIndex]);

      { Сдвиг массива }
      Move(Snake[2], Snake[1], SizeOf(Coords) * SnakeLength);

      Form1.Screen.Canvas.Draw(CellSize * Snake[SnakeLength - 1].x,
          CellSize * Snake[SnakeLength - 1].y, Body);
      Form1.Screen.Canvas.Draw(CellSize * Snake[SnakeLength].x,
          CellSize * Snake[SnakeLength].y, Head[DirectionIndex]);

      { Вывод на экран текущей длины удава }
      Form1.SnakeLenLabel.Caption := IntToStr(SnakeLength);

      { Задержка перед следующим циклом }
      Application.ProcessMessages;
      while Round(MSecsPerFrame - (Now - oldtime) * MSecsPerDay) > 0 do
        Application.ProcessMessages
    end
  end;
  FreeBitmaps; { Освобождение выделенной памяти }
  Application.Terminate { Выход из программы }
end;

end.