Snake · Round 1.28" touch watch
Game 3 - Snake: swipe to steer. Eat the food to grow; don't bite yourself. Teaches: grid games, a list as a queue, gestures, wrapping inside a round board.
You’ll learn: grid game, swipe gestures
Board: Waveshare ESP32-S3-Touch-LCD-1.28 (ESP32-S3R2). Part of the kit’s Games. Needs the board’s LVGL firmware: flash it from the notebook’s Flash button, then press Open in Full IDE.
# Game 3 - Snake: swipe to steer. Eat the food to grow; don't bite yourself.
# Teaches: grid games, a list as a queue, gestures, wrapping inside a round board.
import lvgl as lv
import display
display.init() # start the display and touch (does nothing if already on)
LINE = 0x24452F
TEXT = 0xE3EFE6
ACCENT = 0x46E07C
AMBER = 0xF2B84B
keep = [] # styles, buffers and callbacks LVGL uses must stay referenced
FONTS = {12: lv.font_montserrat_12, 14: lv.font_montserrat_14, 16: lv.font_montserrat_16}
def label(parent, text="", color=TEXT, font=16, align=lv.ALIGN.CENTER, x=0, y=0, zoom=0):
"""lv.label with a colour and a Montserrat 12/14/16 font. zoom=2 draws it twice as big."""
lb = lv.label(parent)
lb.set_text(text)
lb.set_style_text_color(lv.color_hex(color), 0)
lb.set_style_text_font(FONTS.get(font, lv.font_montserrat_16), 0)
if zoom:
lb.set_style_transform_scale(int(256 * zoom), 0) # 256 = 100 %
lb.update_layout()
lb.set_style_transform_pivot_x(lb.get_width() // 2, 0)
lb.set_style_transform_pivot_y(lb.get_height() // 2, 0)
lb.align(align, int(x), int(y))
return lb
def dot(parent, size, color, x=0, y=0, align=lv.ALIGN.CENTER):
"""A filled circle: a plain lv.obj with every theme style removed."""
o = lv.obj(parent)
o.remove_style_all()
size = max(1, int(size))
o.set_size(size, size)
o.set_style_radius(lv.RADIUS_CIRCLE, 0)
o.set_style_bg_color(lv.color_hex(color), 0)
o.set_style_bg_opa(lv.OPA.COVER, 0)
o.remove_flag(lv.obj.FLAG.CLICKABLE)
o.align(align, int(x), int(y))
return o
def on_swipe(obj, cb):
"""cb('left' | 'right' | 'up' | 'down') when a finger swipes across obj."""
names = {lv.DIR.LEFT: "left", lv.DIR.RIGHT: "right", lv.DIR.TOP: "up", lv.DIR.BOTTOM: "down"}
def handler(e):
d = lv.indev_active().get_gesture_dir()
if d in names:
cb(names[d])
obj.add_event_cb(handler, lv.EVENT.GESTURE, None)
keep.append(handler)
def high_score(name, score=None):
"""Read (score=None) or raise the best score saved in a file on the board."""
path = "/hs_%s.txt" % name
try:
with open(path) as f:
best = int(f.read())
except (OSError, ValueError):
best = 0
if score is not None and score > best:
best = score
try:
with open(path, "w") as f:
f.write(str(best))
except OSError:
pass
return best
scr = lv.screen_active() # the screen LVGL is showing
scr.clean() # remove what the last program drew
scr.set_style_bg_color(lv.color_hex(0x07140D), 0)
scr.remove_flag(lv.obj.FLAG.SCROLLABLE)
CELL = 12
N = 14 # 14 x 14 grid, fits inside the circle
ORIGIN = -N * CELL // 2
board = lv.obj(scr)
board.set_size(N * CELL + 6, N * CELL + 6)
board.center()
board.set_style_bg_color(lv.color_hex(0x0C1F14), 0)
board.set_style_border_color(lv.color_hex(LINE), 0)
board.set_style_radius(16, 0)
board.remove_flag(lv.obj.FLAG.CLICKABLE)
MAXLEN = 60
segs = [dot(scr, CELL - 2, ACCENT) for _ in range(MAXLEN)]
for s in segs:
s.set_style_radius(3, 0)
s.add_flag(lv.obj.FLAG.HIDDEN)
food = dot(scr, CELL - 2, AMBER)
hud = label(scr, "", 0xFFFFFF, 14, y=-104)
msg = label(scr, "", 0xFFFFFF, 14, y=0)
DIRS = {"left": (-1, 0), "right": (1, 0), "up": (0, -1), "down": (0, 1)}
g = {}
def cell_xy(c):
return ORIGIN + c[0] * CELL + CELL // 2, ORIGIN + c[1] * CELL + CELL // 2
def put(obj, c):
x, y = cell_xy(c)
obj.align(lv.ALIGN.CENTER, x, y)
def new_food():
while True:
c = (lv.rand(0, N - 1), lv.rand(0, N - 1))
if c not in g["body"]:
g["food"] = c
put(food, c)
return
def reset(e=None):
g.update(body=[(7, 7), (6, 7), (5, 7)], dir=(1, 0), next=(1, 0), over=False, score=0, step=0)
for s in segs:
s.add_flag(lv.obj.FLAG.HIDDEN)
msg.set_text("")
new_food()
draw()
def draw():
for i, s in enumerate(segs):
if i < len(g["body"]):
s.remove_flag(lv.obj.FLAG.HIDDEN)
put(s, g["body"][i])
s.set_style_bg_color(lv.color_hex(0xB6FFC9 if i == 0 else ACCENT), 0)
else:
s.add_flag(lv.obj.FLAG.HIDDEN)
hud.set_text("score %d" % g["score"])
def tick(_):
if g["over"]:
return
g["step"] += 1
if g["step"] % max(2, 6 - g["score"] // 5): # speeds up as you grow
return
dx, dy = g["next"]
if (dx, dy) != (-g["dir"][0], -g["dir"][1]):
g["dir"] = (dx, dy)
hx, hy = g["body"][0]
head = ((hx + g["dir"][0]) % N, (hy + g["dir"][1]) % N) # wrap around the edges
if head in g["body"]:
g["over"] = True
best = high_score("snake", g["score"])
msg.set_text("Game over\nscore %d best %d\ntap to replay" % (g["score"], best))
return
g["body"].insert(0, head)
if head == g["food"] and len(g["body"]) < MAXLEN:
g["score"] += 1
new_food()
else:
g["body"].pop()
draw()
def steer(d):
g["next"] = DIRS[d]
on_swipe(scr, steer)
scr.add_event_cb(lambda e: g["over"] and reset(), lv.EVENT.CLICKED, None)
reset()
tick_timer = lv.timer_create(tick, 40, None)
print("Swipe up/down/left/right to steer the snake.")
Comments