Arrays are going to help a ton here. Someday we will have real arrays, but for now, fake arrays are not hard to do.
You could make some fake arrays with "read global" and "write global" but for what you are doing, slices are going to be easiest, since they already have X and Y properties, and you can use them to visually display your snake on the map.
First, create a slice container, and parent it to the map layer
Code: Select all
global variable(0, snake layer)
plotscript, create snake layer, begin
snake layer := create container()
set parent(snake layer, lookup slice(sl:hero layer))
# Create 5 children to hold the 5 most recent positions
variable(ch, i)
for(i, 0, 4) do(
ch := create rect(20, 20)
set parent(ch, snake layer)
# Make all the children start out at the hero's x,y position
set slice x(ch, hero pixel x(0))
set slice y(ch, hero pixel y(0))
)
end
Now each time the hero completes a step, you can add a new child to the snake layer, and remove an old one.
Code: Select all
plotscript, each step snake, begin
variable(ch)
# Add a new segment at the hero's current
ch := create rect(20, 20)
# this reparents the new child slice, and makes it the first child in the list
move slice below(ch, first child(snake layer))
set slice x(ch, hero pixel x(0))
set slice y(ch, hero pixel y(0))
# Remove the last child in the list
free slice(last child(snake layer))
end
Finally, you can check for collisions like this:
Code: Select all
script, check for snake collisions, begin
variable(ch)
ch := first child(snake layer)
while(ch) do(
if(find colliding slice(snake layer, ch, false)) then(
# Crash! A snake child touched a sibling
exit returning(true)
)
ch := next sibling(ch)
)
# didn't find any collisions
exit returning(false)
end
If any of this needs more explanations, just ask :)