MantisIDE

Tilt Gems · Round 1.28" touch watch

Project by MantisIDE Team · Fri Nov 27 2026 · 0 points · 0 comments

Game 2 - Tilt Gems: roll the ball by tilting the watch, collect gems, dodge the red mines. Teaches: IMU input, physics with friction, circle collisions, spawning.

You’ll learn: IMU physics, round-wall bounce

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 2 - Tilt Gems: roll the ball by tilting the watch, collect gems, dodge the red mines.
# Teaches: IMU input, physics with friction, circle collisions, spawning.
import math
import lvgl as lv
import display
import bb_imu

display.init()                     # start the display and touch (does nothing if already on)

TEXT = 0xE3EFE6
ACCENT = 0x46E07C
BLUE = 0x6CB8FF
RED = 0xFF6B6B
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(0x0A0F1E), 0)
scr.remove_flag(lv.obj.FLAG.SCROLLABLE)
imu = bb_imu.IMU()               # QMI8658 motion sensor, on the touch I2C bus
ARENA = 105

edge = lv.obj(scr)
edge.set_size(2 * ARENA + 16, 2 * ARENA + 16)
edge.center()
edge.set_style_radius(lv.RADIUS_CIRCLE, 0)
edge.set_style_bg_opa(lv.OPA.TRANSP, 0)
edge.set_style_border_color(lv.color_hex(BLUE), 0)
edge.set_style_border_width(2, 0)
edge.remove_flag(lv.obj.FLAG.CLICKABLE)

ball = dot(scr, 18, 0xFFFFFF)
ball.set_style_shadow_width(14, 0)
ball.set_style_shadow_color(lv.color_hex(BLUE), 0)
gem = dot(scr, 14, ACCENT)
mines = [dot(scr, 16, RED) for _ in range(3)]
hud = label(scr, "", 0xFFFFFF, 14, y=-96)
msg = label(scr, "", 0xFFFFFF, 14, y=30)

g = {"x": 0.0, "y": 0.0, "vx": 0.0, "vy": 0.0, "score": 0, "time": 60.0, "over": False,
     "gem": (0, 0), "mines": [], "best": high_score("tiltgems")}


def rand_spot(min_r=20):
    while True:
        a = math.radians(lv.rand(0, 359))
        r = lv.rand(min_r, ARENA - 12)
        x, y = math.cos(a) * r, math.sin(a) * r
        if (x - g["x"]) ** 2 + (y - g["y"]) ** 2 > 45 ** 2:
            return x, y


def new_gem():
    g["gem"] = rand_spot()
    gem.align(lv.ALIGN.CENTER, int(g["gem"][0]), int(g["gem"][1]))
    anim(gem, 128, 300, 300, lambda o, v: o.set_style_transform_scale(v, 0), path=lv.anim_t.path_overshoot)


def reset(e=None):
    g.update(x=0.0, y=0.0, vx=0.0, vy=0.0, score=0, time=60.0, over=False)
    g["mines"] = [rand_spot(35) for _ in mines]
    for m, (x, y) in zip(mines, g["mines"]):
        m.align(lv.ALIGN.CENTER, int(x), int(y))
    msg.set_text("")
    new_gem()


def tick(_):
    if g["over"]:
        return
    ax, ay, _z = imu.accel()
    g["vx"] = (g["vx"] - ax * 0.9) * 0.94           # tilt pushes, friction slows
    g["vy"] = (g["vy"] + ay * 0.9) * 0.94
    g["x"] += g["vx"]
    g["y"] += g["vy"]
    r = math.sqrt(g["x"] ** 2 + g["y"] ** 2)
    if r > ARENA - 9:                               # bounce off the round wall
        nx, ny = g["x"] / r, g["y"] / r
        dot = g["vx"] * nx + g["vy"] * ny
        g["vx"] -= 1.6 * dot * nx
        g["vy"] -= 1.6 * dot * ny
        g["x"], g["y"] = nx * (ARENA - 9), ny * (ARENA - 9)
    ball.align(lv.ALIGN.CENTER, int(g["x"]), int(g["y"]))
    gx, gy = g["gem"]
    if (g["x"] - gx) ** 2 + (g["y"] - gy) ** 2 < 16 ** 2:
        g["score"] += 1
        g["time"] += 2
        new_gem()
    for mx, my in g["mines"]:
        if (g["x"] - mx) ** 2 + (g["y"] - my) ** 2 < 17 ** 2:
            end("BOOM!")
            return
    g["time"] -= 0.04
    if g["time"] <= 0:
        end("Time!")
    hud.set_text("%d   %ds" % (g["score"], max(0, int(g["time"]))))


def end(why):
    g["over"] = True
    g["best"] = high_score("tiltgems", g["score"])
    msg.set_text("%s  score %d\nbest %d - tap to replay" % (why, g["score"], g["best"]))

scr.add_event_cb(lambda e: g["over"] and reset(), lv.EVENT.CLICKED, None)
reset()
tick_timer = lv.timer_create(tick, 40, None)
print("Tilt the watch to roll the ball. Green = gem, red = mine.")
Loading post…

Dialog