Simple snake game in DELPHI

lT GEEK
lT GEEK used Ask the Experts™
on
Hello.

I want to make a snake game using DELPHI. The basic, the snake eats the apple and it grows longer. I have the apple generating in random places. The only thing that I cant get is the delay. So i need the blocks to follow the first block in a train effect, but so far they are all stuck together and when I change direction they all move together instead of being in a 'train' effect.

Can anyone help me? I don't know if the explanation was detailed enough.
Many Thanks
54999858925__AB9E1587-E48B-4EC4-B511.MOV
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Geert GOracle dba
Top Expert 2009

Commented:
it's all about the code, isn't it ?

Author

Commented:
Geert G

Yes it is. I can’t seem so get it right.
Geert GOracle dba
Top Expert 2009

Commented:
https://www.youtube.com/watch?v=iWxAURPFDuY
this guy at least posted a video with an explanation of how he did it ...
without showing your code, we can only comment on your video.

compare your code to the concepts in that video
Software architect
Top Expert 2012
Commented:
Without looking how others do it... I will try show my thoughts...

So, try to use dynamic array - where you will store Snake (each element of an array will be one Snake segment).
Dyn-arrays can be safely expand...

type
  TSnakeSegment = record
    XPos, YPos: Integer;
   
  end;
  TSnake = array of TSnakeSegment;

Open in new window


following code will expand Snake - better do expanding from first position - because first segment (head) will have
always new position, remain segments will take prev. segment position :
procedure ExpandSnake(var Snake: TSnake; Segment: TSnakeSegment);
var
  i: Integer;
begin
  //shift
  SetLength(Snake, Length(Snake)+1);
  for i := (Low(Snake)+1) to High(Snake) do
     Snake[i] := Snake[i-1];
 //replace first...  
  Snake[0] := Segment;
end;

Open in new window


...when expanding is not in place (just moving) - do shifting without expanding Snake>
procedure MoveSnake(var Snake: TSnake; x,y: Integer);
var
  i: Integer;
begin
  //shift
  for i := (Low(Snake)+1) to High(Snake) do
     Snake[i] := Snake[i-1];
 //replace first position...  
  Snake[0].XPos := x;
  Snake[0].YPos := y;
end;

Open in new window


... this way you can have a "Train" effect - cause you will draw each segment in a sequential way.
Drawing - just iterate from first to last element of an array.

Author

Commented:
I had to use a dynamic array which is something I haven’t learnt yet. Thank you.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial