Snake

On your display
Watch an autonomous Snake chase its food across your AWTRIX display.
- Works with
- AWTRIX NG
- Topic
- Gaming
- Includes
- Script
Choose your display in the next step.
Flow description
A memory-optimized self-playing Snake animation for AWTRIX-NG.
The snake automatically finds its way to the food and can wrap around the edges of the display, just like in the original game.
No configuration or additional icons required — just install and enjoy.
l3qLTHc0tCXB.ax
# @name Auto Snake
# @desc Memory-optimized self-playing Snake for AWTRIX NG
# @version 0.3
# @author mckdoubleu
import math
class AutoSnake
var b,hd,f,len,last
def init()
self.b=bytes(-256)
self.reset()
end
def reset()
for i:0..255 self.b[i]=0 end
self.len=5
self.hd=7
for x:3..7 self.b[x]=x-2 end
self.food()
self.last=now_ms()
end
def food()
if self.len>=255 self.reset() return end
var s=math.rand()%256
for n:0..255
var i=(s+n)%256
if self.b[i]==0 self.f=i return end
end
end
def dist(i)
var x=i%32
var y=i/32
var fx=self.f%32
var fy=self.f/32
var dx=x-fx
var dy=y-fy
if dx<0 dx=-dx end
if dy<0 dy=-dy end
if dx>32-dx dx=32-dx end
if dy>8-dy dy=8-dy end
return dx+dy
end
def next()
var x=self.hd%32
var y=self.hd/32
var ni=-1
var best=41
var i=y*32+((x+1)%32)
var d=self.dist(i)
if self.b[i]<=1 && d<best ni=i best=d end
i=y*32+((x+31)%32)
d=self.dist(i)
if self.b[i]<=1 && d<best ni=i best=d end
i=((y+1)%8)*32+x
d=self.dist(i)
if self.b[i]<=1 && d<best ni=i best=d end
i=((y+7)%8)*32+x
d=self.dist(i)
if self.b[i]<=1 && d<best ni=i best=d end
if ni<0 self.reset() return end
var eat=ni==self.f
if eat
self.len+=1
else
for j:0..255
if self.b[j]>0 self.b[j]-=1 end
end
end
self.hd=ni
self.b[ni]=self.len
if eat self.food() end
end
def draw()
var t=now_ms()
if t-self.last>=75 self.last=t self.next() end
clear(0)
for i:0..255
var v=self.b[i]
if v>0
var x=i%32
var y=i/32
if i==self.hd
pixel(x,y,0xB7FF3C)
elif v<3
pixel(x,y,0x147A22)
else
pixel(x,y,0x32D74B)
end
end
end
var fx=self.f%32
var fy=self.f/32
if (t%500)<400
pixel(fx,fy,0xFF3030)
else
pixel(fx,fy,0xFF8A00)
end
end
def duration()
return 30000
end
end
return AutoSnake()
Discussion 0
Ask a question, suggest a change or share how you use it.
No comments yet. Start the conversation.
More flows for AWTRIX NG Scripts or Gaming
Something wrong with this flow? Report it.
Have an idea?
Sign in to ask questions and join the conversation.