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\$
2
  • 2
    \$\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\$ Commented Sep 16, 2020 at 16:24
  • \$\begingroup\$ This example in the Lexaloffle BBS might have something you could use: lexaloffle.com/bbs/?pid=69789#p \$\endgroup\$ Commented Oct 10, 2020 at 14:58

0

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.