unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.ExtCtrls; type TForm1 = class(TForm) Timer1: TTimer; procedure FormCreate(Sender: TObject); procedure FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); procedure Timer1Timer(Sender: TObject); procedure FormPaint(Sender: TObject); private { Private declarations } Snake: array[0..499] of TPoint; SnakeLength: Integer; Food: TPoint; Direction: TPoint; procedure DrawSnake; procedure DrawFood; procedure MoveSnake; procedure CheckCollision; public { Public declarations } end; var Form1: TForm1; implementation {$R *.dfm} const BlockSize = 10; procedure TForm1.FormCreate(Sender: TObject); begin SnakeLength := 1; Snake[0].X := 10; Snake[0].Y := 10; Food.X := 30; Food.Y := 30; Direction.X := 1; Direction.Y := 0; Timer1.Enabled := True; DoubleBuffered := True; end; procedure TForm1.FormKeyDown(Sender: TObject; var Key: Word; Shift: TShiftState); begin case Key of VK_UP: begin Direction.X := 0; Direction.Y := -1; end; VK_DOWN: begin Direction.X := 0; Direction.Y := 1; end; VK_LEFT: begin Direction.X := -1; Direction.Y := 0; end; VK_RIGHT: begin Direction.X := 1; Direction.Y := 0; end; end; end; procedure TForm1.FormPaint(Sender: TObject); begin DrawSnake; DrawFood; end; procedure TForm1.Timer1Timer(Sender: TObject); begin MoveSnake; CheckCollision; Repaint; end; procedure TForm1.DrawSnake; var i: Integer; begin for i := 0 to SnakeLength - 1 do begin Canvas.Brush.Color := clGreen; Canvas.FillRect(Rect(Snake[i].X * BlockSize, Snake[i].Y * BlockSize, Snake[i].X * BlockSize + BlockSize, Snake[i].Y * BlockSize + BlockSize)); end; end; procedure TForm1.DrawFood; begin Canvas.Brush.Color := clRed; Canvas.FillRect(Rect(Food.X * BlockSize, Food.Y * BlockSize, Food.X * BlockSize + BlockSize, Food.Y * BlockSize + BlockSize)); end; procedure TForm1.MoveSnake; var i: Integer; begin for i := SnakeLength - 1 downto 1 do Snake[i] := Snake[i - 1]; Snake[0].X := Snake[0].X + Direction.X; Snake[0].Y := Snake[0].Y + Direction.Y; end; procedure TForm1.CheckCollision; var i: Integer; begin if (Snake[0].X = Food.X) and (Snake[0].Y = Food.Y) then begin Inc(SnakeLength); Snake[SnakeLength - 1] := Snake[SnakeLength - 2]; Food.X := Random(ClientWidth div BlockSize); Food.Y := Random(ClientHeight div BlockSize); end; if Snake[0].X < 0 then Snake[0].X := ClientWidth div BlockSize - 1; if Snake[0].X > ClientWidth div BlockSize - 1 then Snake[0].X := 0; if Snake[0].Y < 0 then Snake[0].Y := ClientHeight div BlockSize - 1; if Snake[0].Y > ClientHeight div BlockSize - 1 then Snake[0].Y := 0; for i := 1 to SnakeLength - 1 do if (Snake[0].X = Snake[i].X) and (Snake[0].Y = Snake[i].Y) then Timer1.Enabled := False; end; end.
// 吃完第一个食物就完了。哈哈
标签:begin,end,BlockSize,delphi,Direction,贪吃蛇,Snake,ChatGPT,procedure From: https://www.cnblogs.com/onlyou13/p/17109235.html