0
\$\begingroup\$

I want to make a basic snake game. It has a head and a series of tails that occupy a tile in a grid. The first tail in the series is adjacent to the head. and each tail that comes after is adjacent to the previous tail. Head can move in four directions and the first tail moves to head's previous position, and each other tail moves to the previous position of the previous tail, as they follow each other.

How can I model this as data, and update it for movement.

I've tried this but that's a little doesn't work.

p = {
  x=0,
  y=0,
  tails={}
}

function init_tail(dx,dy)
   return {
      x=0,
      y=0,
      dx=dx,
      dy=dy
   }
end
-- Initialization
add(p.tails, init_tail(0,1))
add(p.tails, init_tail(0,1))
add(p.tails, init_tail(0,1))

local last = p
for tail in all(p.tails) do
   local tx = last.x + tail.dx
   local ty = last.y + tail.dy
   tail.x = tx
   tail.y = ty
   last = tail
end
-- Movement
local last = p
for tail in all(p.tails) do
   tail.dx = -last.dx
   tail.dy = -last.dy
   local tx = last.x + last.dx + tail.dx
   local ty = last.y + last.dy + tail.dy
   tail.x = tx
   tail.y = ty
   last = tail
end

This is what I have so far: snake game

\$\endgroup\$
  • \$\begingroup\$ Did you try looking at past Q&A in the snake tag for some leads? This is a mechanic with lots of existing tutorials and sample implementations available online, so I doubt there's much new that we could tell you that hasn't already been said. \$\endgroup\$ – DMGregory Sep 16 at 16:24
  • \$\begingroup\$ This example in the Lexaloffle BBS might have something you could use: lexaloffle.com/bbs/?pid=69789#p \$\endgroup\$ – apa64 Oct 10 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.