Skip to content

Instantly share code, notes, and snippets.

@FrankBuss
Created April 29, 2018 00:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FrankBuss/c40b2e33fbb493d0d5d68927d54a29fd to your computer and use it in GitHub Desktop.
Save FrankBuss/c40b2e33fbb493d0d5d68927d54a29fd to your computer and use it in GitHub Desktop.
segmentImage = Image.load("segment.png")
pi = 4*math.atan(1)
green = Color.new(0,255,0)
black = Color.new(0,0,0)
segmentSize = segmentImage:width()
segmentSpace = segmentSize - 2
width = 480 + 2 * segmentSize
height = 272 + 2 * segmentSize
function init()
x = 100
head = { dir = 0, posX = x, posY = 100, next = nil }
for i=1,20 do
x = x + segmentSpace
head = { dir = 0, posX = x, posY = 100, next = head }
end
dir = 0
end
function drawSegment(seg)
screen:blit(seg.posX, seg.posY, segmentImage)
end
function adjustSegment(seg)
if seg.posX < -segmentSize then seg.posX = seg.posX + width end
if seg.posX > width-segmentSize then seg.posX = seg.posX - width end
if seg.posY < -segmentSize then seg.posY = seg.posY + height end
if seg.posY > height-segmentSize then seg.posY = seg.posY - height end
end
function drawSnake(head, dir)
drawSegment(head)
head.posX = head.posX + math.sin(dir) * 2
head.posY = head.posY + math.cos(dir) * 2
adjustSegment(head)
seg = head.next
lastX = head.posX
lastY = head.posY
while seg do
drawSegment(seg)
dx = lastX - seg.posX
dy = lastY - seg.posY
if dx < -240 then dx = dx + width end
if dy < -136 then dy = dy + height end
if dx > 240 then dx = dx - width end
if dy > 136 then dy = dy - height end
r = math.atan2(dx, dy)
lastX = lastX - math.sin(r) * segmentSpace
lastY = lastY - math.cos(r) * segmentSpace
seg.posX = lastX
seg.posY = lastY
adjustSegment(seg)
seg = seg.next
end
end
init()
timer = Timer.new()
fps = 0
fpsUpdate = 0
while true do
if fpsUpdate == 9 then
fpsUpdate = 0
fps = math.floor(10000 / timer:time() + 0.5)
timer:reset()
timer:start()
else
fpsUpdate = fpsUpdate + 1
end
controls = Controls.read()
if controls:start() then break end
screen:clear(black)
dx = controls:analogX()
dy = controls:analogY()
if dx*dx + dy*dy > 200 then
dir = math.atan2(dx, dy)
end
drawSnake(head, dir)
screen:print(0, 0, "fps: " .. tostring(fps), green)
screen.waitVblankStart()
screen.flip()
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment