1. Declare The SnakeBody VariableIt is easy, just put this code at at declaration area:
2. Initial The SnakeBody When The Program StartYou need to put this on
FormCreate:
var
SnakeSegment: PRect;
begin
SnakeBody := TList.Create;
// ...
SnakeSegment^ := snakepos; // Put this line after ...random(10)
SnakeBody.Add(SnakeSegment); // Put this line after SnakeSegment^ := ...
// ...
3. Free SnakeBody When Not NeededPut this on
FormClose:
4. Add A New Variable "SnakeIsGrowing"This variable is needed to know if the snake is moving or growing. If it is moving, then the latest segment of the body (tail) will be deleted automatically.
Add this as a global variable:
var
SnakeIsGrowing: Boolean = False;
5. Add A New Procedure "MoveSnake"Create a new procedure, I call it
MoveSnake. It should be on private section of TForm1. Here is the code:
procedure TForm1.MoveSnake(NewHead: TRect);
var
SnakeSegment: PRect;
begin
New(SnakeSegment);
SnakeSegment^ := NewHead;
SnakeBody.Insert(0, SnakeSegment);
if not(SnakeIsGrowing) then begin
SnakeSegment := SnakeBody[SnakeBody.Count-1];
PutItem(SnakeSegment^.Left, SnakeSegment^.Top, Emtpy);
Freemem(SnakeSegment);
SnakeBody.Delete(SnakeBody.Count-1);
end;
SnakeIsGrowing := False;
end;
You can know from the code above, if the snake is not growing then the code will remove the tail.
6. Make It MoveBecause you use Timer1 as the game main loop, so you should put this code on
Timer1Timer:
You should put the code above at the end of the procedure.
7. Fix An Error: PutItemYou should
remove PutItem(snakepos.left, snakepos.top, snake) on the FormKeyDown because you already have it on Timer1Timer.
8. Fix An Error: ClearWorldYou should not call ClearWorld on Timer1Timer. ClearWorld is needed only when starting a new round of the game. So
remove ClearWorld on Timer1Timer.
9. Write Code for TestingEverything should be okay now. You can write some code to test if it working correctly.
Add the code on your key down testing section:
if key=VK_ADD then
begin
SnakeIsGrowing := True;
end;
Now, you can try pressing '+' when moving the snake, the snake should grow longer.
I wrote this explanation on the same time coding it on your code. It works here on my test.