Colour Memory · Round 1.28" touch watch
Game 5 - Colour Memory: watch the quadrants light up, then repeat the sequence. Teaches: state machines with timers, playback of a sequence, arc segments as buttons.
You’ll learn: sequence game, arc buttons
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 5 - Colour Memory: watch the quadrants light up, then repeat the sequence.
# Teaches: state machines with timers, playback of a sequence, arc segments as buttons.
import lvgl as lv
import display
display.init() # start the display and touch (does nothing if already on)
TEXT = 0xE3EFE6
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 anim(obj, start, end, ms, setter, path=None, repeat=1, playback=0, delay=0, done=None):
"""Animate start -> end over ms, calling setter(obj, value). repeat=-1 loops forever."""
a = lv.anim_t()
a.init()
a.set_var(obj)
a.set_values(start, end)
a.set_duration(ms)
a.set_delay(delay)
a.set_custom_exec_cb(lambda _a, v: setter(obj, v))
a.set_path_cb(path or lv.anim_t.path_ease_in_out)
if repeat < 0:
a.set_repeat_count(lv.ANIM_REPEAT_INFINITE)
elif repeat > 1:
a.set_repeat_count(repeat)
if playback:
a.set_reverse_duration(playback) # play back to start
if done:
a.set_completed_cb(lambda _a: done())
a.start()
keep.append(a)
return a
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(0x0A0A0A), 0)
scr.remove_flag(lv.obj.FLAG.SCROLLABLE)
COLORS = [(0xC0392B, 0xFF7B6B), (0x1E8449, 0x6BFF9B), (0x1F618D, 0x7BC7FF), (0xB7950B, 0xFFE36B)]
pads = []
for i, (dim, lit) in enumerate(COLORS):
a = lv.arc(scr)
a.set_size(220, 220)
a.center()
a.remove_style(None, lv.PART.KNOB)
a.set_bg_angles(i * 90 + 4, i * 90 + 86)
a.set_angles(i * 90 + 4, i * 90 + 4)
a.set_style_arc_width(56, lv.PART.MAIN)
a.set_style_arc_color(lv.color_hex(dim), lv.PART.MAIN)
a.set_style_arc_width(0, lv.PART.INDICATOR)
a.add_flag(lv.obj.FLAG.ADV_HITTEST) # only the visible arc is touchable
pads.append(a)
center = dot(scr, 96, 0x111111)
info = label(scr, "tap to\nstart", 0xFFFFFF, 14)
info.set_style_text_align(lv.TEXT_ALIGN.CENTER, 0)
g = {"seq": [], "pos": 0, "state": "idle", "show": 0, "tick": 0, "best": high_score("memory")}
def light(i, on):
pads[i].set_style_arc_color(lv.color_hex(COLORS[i][1 if on else 0]), lv.PART.MAIN)
def start_round():
g["seq"].append(lv.rand(0, 3))
g.update(state="show", show=0, tick=0, pos=0)
info.set_text("watch\n%d" % len(g["seq"]))
def tick(_):
if g["state"] != "show":
return
g["tick"] += 1
step, phase = divmod(g["tick"], 12)
if step >= len(g["seq"]):
g["state"] = "input"
info.set_text("your\nturn")
return
light(g["seq"][step], phase < 8)
def pressed(i):
if g["state"] == "idle":
g["seq"] = []
start_round()
return
if g["state"] != "input":
return
light(i, True)
anim(pads[i], 0, 1, 180, lambda o, v: None, done=lambda: light(i, False))
if g["seq"][g["pos"]] != i:
g["best"] = high_score("memory", len(g["seq"]) - 1)
g["state"] = "idle"
info.set_text("wrong!\n%d (best %d)\ntap" % (len(g["seq"]) - 1, g["best"]))
return
g["pos"] += 1
if g["pos"] == len(g["seq"]):
g["state"] = "wait"
info.set_text("nice!")
anim(center, 0, 1, 600, lambda o, v: None, done=start_round)
for i, p in enumerate(pads):
p.add_event_cb(lambda e, i=i: pressed(i), lv.EVENT.PRESSED, None)
center.add_flag(lv.obj.FLAG.CLICKABLE)
center.add_event_cb(lambda e: g["state"] == "idle" and pressed(0), lv.EVENT.CLICKED, None)
tick_timer = lv.timer_create(tick, 50, None)
print("Tap the centre to start, then repeat the colours.")
Comments