# Snake turning

Hi. I am as I said in a previous thread new with codea and was wondering if any of you knew how I i could make the snake in the game snake do the “L” turn instead of just flat out turning. Sorry if I am unclear and i can explain if you need me to

Do you mean that instead of each piece will turn at once, each turns one by one?

You have to keep a list of every segment and where it’s located. At each time slice, move the tail piece and put it in front of the front piece. Thus, you will have a table of segments and some data to determine where the head is and where it’s going.

When the snake grows, leave the tail pieces where they are and just add more to the head…

I hope that’s what you are asking.

I think so, but sorry you might have to dumb it down a little. Im not that good with tables

So what I want to do if you don’t understand, JakAttack, is make it so instead of all the body “segments” all switching to behind the head automatically, I want them to do the L shape like in the arcade game.

Basically, you have to keep track of where each segment of the snake is on the screen. You will need to keep this information in a table. (sorry )

You will use this table to draw the snake for each frame. And every so many microseconds, depending on how fast your snake is, you will need to remove the tail piece and move it to the head.

The table will be as easy as something like

``````snake ={{5,6},{6,6},{7,6},{7,7},{7,8}}
``````

Each of the {x,y} pairs is the location of a segment. I’ve put in real values so you can see what’s going on.

If the {7,8} is the head piece, we can see that it’s next position will be {7,9}. Normally, you will keep the direction as an x,y pair. So remove the {5,6} with

``````table.remove(snake, 1)
``````

with 1 referring to the first element. Lua will automatically slide all the other elements down. And to add the new segment:

``````table.insert(snake, {7,9})
``````

Lua always inserts at the end unless you tell it otherwise. You get

``````snake ={{6,6},{7,6},{7,7},{7,8},{7,9}}
``````

Tables are wondrous things. Since I started Lua, I now dream in tables.

@syntonica is correct

thanks!

@compactbear This may not be exactly what you want, but I had this sitting around and thought this might be useful. Just slide your finger around the screen.

``````
function setup()
displayMode(FULLSCREEN)
tab={}
x=WIDTH/2
y=HEIGHT/2
sx=0
sy=0
length=150
end

function draw()
background(40,40,50)
fill(255,0,0)
x = x + sx
y = y + sy
if #tab<length then
table.insert(tab,1,vec2(x,y))
else
table.insert(tab,1,vec2(x,y))
table.remove(tab,#tab)
end
for a,b in pairs(tab) do
if a==1 then
ellipse(b.x,b.y,20,20)
else
ellipse(b.x,b.y,10,10)
end
end
end

function getDirection()
dx=CurrentTouch.x-x
dy=CurrentTouch.y-y
h=math.sqrt(dx*dx+dy*dy)
sx=dx/25
sy=dy/25
end

function touched(t)
getDirection()
end

``````

thanks I’ll definately look at this