SNAKE game v0.3: round screen, swipe control

- 16x16 grid, 320px board centered on round 466 screen, designWidth 466
- pure snake logic in src/common/snake.js (step/turn/rotateDir/spawnFood, TDD'd)
- for-directive segment rendering, show-gated game-over overlay, 300ms tick
- swipe direction input (crown rotation confirmed unsupported on Vela S4)
- tests: snake logic + page wiring
This commit is contained in:
2026-09-09 15:09:23 +01:00
commit e618c02c1b
13 changed files with 10875 additions and 0 deletions
+5
View File
@@ -0,0 +1,5 @@
node_modules/
build/
dist/
sign/*.pem
+209
View File
@@ -0,0 +1,209 @@
# Xiaomi Vela Hello World for Watch S4
This is the smallest practical Xiaomi Vela JS watch application. It shows two centered lines on a round black screen:
```text
Hello World!
Xiaomi Watch S4
```
It compiles entirely from a Linux terminal. Xiaomi AIoT-IDE is not required.
## 1. What you need
- A 64-bit Linux system
- Node.js and npm
- OpenSSL, but only if you want a signed release package
- Internet access for the first `npm install`
Node.js 20 LTS is a conservative choice. The included project has also been build-tested with Node.js 24 and npm 11.
On Ubuntu or Debian, install the basic tools:
```bash
sudo apt update
sudo apt install -y curl openssl
```
Install Node.js using your preferred package manager or a version manager such as `nvm`. Confirm that it works:
```bash
node --version
npm --version
```
## 2. Understand the tiny project
```text
xiaomi-vela-s4-hello-world/
├── package.json
├── README.md
├── sign/
└── src/
├── app.ux
├── manifest.json
├── common/
│ ├── icon.png
│ └── icon.svg
└── pages/
└── index/
└── index.ux
```
- `package.json` installs Xiaomi's command-line build tool and defines the build commands.
- `src/manifest.json` defines the package, icon, watch target, design width, and start page.
- `src/app.ux` contains application lifecycle hooks.
- `src/pages/index/index.ux` contains the UI and its styles.
- `sign/` is where release certificate files go. Keep private keys private.
Vela `.ux` files resemble small single-file web components. A page may contain `template`, `style`, and `script` blocks. This Hello World page needs only `template` and `style`.
## 3. Compile a debug RPK without Xiaomi's IDE
Open a terminal in the project folder and run:
```bash
npm install
npm run build
```
The important output is created under `dist/` and ends in `.debug.rpk`:
```bash
find dist -maxdepth 1 -type f -name '*.rpk' -print
```
The `build/` directory contains intermediate generated files. You normally do not edit either `build/` or `dist/`.
To include a separate source map while debugging:
```bash
npm run build:source-map
```
To see every compiler option supported by your installed toolkit:
```bash
npm run help
```
## 4. Create a signed release RPK
The release builder expects these two files:
```text
sign/private.pem
sign/certificate.pem
```
Generate a local development certificate from the project root:
```bash
openssl req \
-newkey rsa:2048 \
-nodes \
-keyout sign/private.pem \
-x509 \
-days 3650 \
-out sign/certificate.pem \
-subj '/CN=Hello Vela Development/O=Example/C=US'
```
Then compile the release package:
```bash
npm run release
find dist -maxdepth 1 -type f -name '*.release.*.rpk' -print
```
Do not commit or share `sign/private.pem`. If a companion Android application communicates with the watch app, Xiaomi's wearable integration may require matching signing identity; changing certificates later can also prevent an update from being accepted as the same app.
## 5. Change the app
Edit `src/pages/index/index.ux`. For example, replace:
```xml
<text class="hello">Hello World!</text>
```
with:
```xml
<text class="hello">My first app</text>
```
Then rebuild:
```bash
npm run build
```
When publishing an update, increase `versionCode` in `src/manifest.json`. Also update `versionName` when you want the visible version string to change.
## 6. Important Vela rules
- A template must have exactly one root element.
- Visible text must be inside a `<text>` component.
- Vela uses flex layout, but its CSS support is smaller than a browser's CSS support.
- Package names should use reverse-domain form, such as `com.yourname.hello`.
- `designWidth: 480` lets Vela scale the 480-pixel design to the physical display.
- APIs such as sensors, storage, network, or vibration must usually be declared in the manifest's `features` array before use. This Hello World app requests no APIs.
## 7. Installing on a real Watch S4
Compilation and installation are separate. The terminal workflow above reliably creates the `.rpk`; transferring it to a physical watch depends on the exact Watch S4 model, firmware region, Mi Fitness version, and whether developer or debugging access is enabled for that firmware.
Do not treat the `.rpk` as an Android APK, and do not flash random firmware. Use Xiaomi's supported wearable deployment route for your device/account. Some retail or global firmware builds do not expose the same development or sideload controls as Chinese developer setups.
## 8. Troubleshooting
### `aiot: command not found`
Always run the local tool through npm:
```bash
npm install
npm run build
```
Do not rely on a global `aiot` installation.
### Dependency installation fails
Clear only this project's installed dependencies and retry:
```bash
rm -rf node_modules
npm install
```
If you use a company proxy, configure npm for that proxy instead of disabling TLS verification.
### No `.rpk` appears
Read the first compiler error, then verify:
```bash
npx aiot build -h
find src -maxdepth 4 -type f -print
```
The required files are `src/manifest.json`, `src/app.ux`, and the routed page component.
### Release build says signing files are missing
Run the OpenSSL command in section 4 and confirm:
```bash
test -s sign/private.pem && test -s sign/certificate.pem && echo 'Signing files exist'
```
## Official references
- Xiaomi Vela JS documentation: <https://iot.mi.com/vela/quickapp/en/>
- Project structure: <https://iot.mi.com/vela/quickapp/zh/guide/start/project-overview.html>
- Manifest configuration: <https://iot.mi.com/vela/quickapp/zh/guide/framework/manifest.html>
- Compiler parameters: <https://iot.mi.com/vela/quickapp/zh/guide/start/toolkit-params.html>
- UI introduction: <https://iot.mi.com/vela/quickapp/zh/guide/start/user-interface.html>
The project intentionally uses only the public `aiot-toolkit` command-line package. It does not require Xiaomi AIoT-IDE.
+1
View File
@@ -0,0 +1 @@
/tmp/hw/node_modules
+10223
View File
File diff suppressed because it is too large Load Diff
+15
View File
@@ -0,0 +1,15 @@
{
"name": "xiaomi-vela-s4-hello-world",
"version": "1.0.0",
"private": true,
"description": "Minimal Xiaomi Vela JS Hello World app for Xiaomi Watch S4",
"scripts": {
"build": "aiot build",
"release": "aiot release",
"build:source-map": "aiot build --devtool=source-map",
"help": "aiot build -h"
},
"devDependencies": {
"aiot-toolkit": "2.0.5"
}
}
+10
View File
@@ -0,0 +1,10 @@
<script>
export default {
onCreate() {
console.log('Hello Vela app created')
},
onDestroy() {
console.log('Hello Vela app destroyed')
}
}
</script>
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

+4
View File
@@ -0,0 +1,4 @@
<svg xmlns="http://www.w3.org/2000/svg" width="192" height="192" viewBox="0 0 192 192">
<rect width="192" height="192" rx="48" fill="#ff6900"/>
<text x="96" y="116" text-anchor="middle" font-family="DejaVu Sans, sans-serif" font-size="72" font-weight="700" fill="#ffffff">Hi</text>
</svg>

After

Width:  |  Height:  |  Size: 293 B

+59
View File
@@ -0,0 +1,59 @@
// Snake core — pure functions, no Vela APIs. Exports: initialSnake, step, turn, spawnFood.
function initialSnake() {
return [
{ x: 6, y: 7 },
{ x: 5, y: 7 },
{ x: 4, y: 7 }
]
}
// Advance the snake one cell in `dir` ({x,y} unit vector). Returns { snake, ate, alive }.
function step(snake, dir, food, N) {
const head = snake[0]
const nx = head.x + dir.x
const ny = head.y + dir.y
if (nx < 0 || ny < 0 || nx >= N || ny >= N) {
return { snake, ate: false, alive: false }
}
const ate = (nx === food.x && ny === food.y)
// tail cell vacates unless we grew, so exclude it from self-collision check
const body = ate ? snake : snake.slice(0, snake.length - 1)
for (let i = 0; i < body.length; i++) {
if (body[i].x === nx && body[i].y === ny) {
return { snake, ate: false, alive: false }
}
}
const next = [{ x: nx, y: ny }].concat(snake)
if (!ate) next.pop()
return { snake: next, ate, alive: true }
}
// Reject a 180° reversal; otherwise accept the new direction.
function turn(current, desired) {
if (current.x + desired.x === 0 && current.y + desired.y === 0) return current
return desired
}
// Rotate a direction 90°: clockwise order right->down->left->up. Always ±90°, never a reversal.
function rotateDir(dir, clockwise) {
const order = [{ x: 1, y: 0 }, { x: 0, y: 1 }, { x: -1, y: 0 }, { x: 0, y: -1 }]
let i = 0
for (let k = 0; k < 4; k++) {
if (order[k].x === dir.x && order[k].y === dir.y) { i = k; break }
}
return clockwise ? order[(i + 1) % 4] : order[(i + 3) % 4]
}
// Random empty cell, avoiding the snake.
function spawnFood(snake, N) {
const occupied = new Set(snake.map(s => s.x + ',' + s.y))
if (occupied.size >= N * N) return null
let x, y
do {
x = Math.floor(Math.random() * N)
y = Math.floor(Math.random() * N)
} while (occupied.has(x + ',' + y))
return { x, y }
}
module.exports = { initialSnake, step, turn, rotateDir, spawnFood }
+32
View File
@@ -0,0 +1,32 @@
{
"package": "com.ilias.snake",
"name": "SNAKE",
"icon": "/common/icon.png",
"versionName": "0.3",
"versionCode": 3,
"minAPILevel": 1,
"deviceTypeList": [
"watch"
],
"config": {
"logLevel": "debug",
"designWidth": 466
},
"router": {
"entry": "pages/index",
"pages": {
"pages/index": {
"component": "index",
"path": "/"
}
}
},
"display": {
"backgroundColor": "#000000"
},
"features": [
{
"name": "system.router"
}
]
}
+180
View File
@@ -0,0 +1,180 @@
<template>
<div class="page" onswipe="onSwipe">
<stack class="dial">
<div class="board"></div>
<div class="food" style="left: {{ food.left }}px; top: {{ food.top }}px;"></div>
<div class="{{ seg.cls }}" for="{{ seg in snake }}" style="left: {{ seg.left }}px; top: {{ seg.top }}px;"></div>
<div class="overlay" show="{{ over }}" onclick="onTap">
<text class="overText">GAME OVER</text>
<text class="overSub">{{ scoreText }}</text>
<text class="overHint">tap to play again</text>
</div>
<text class="score">{{ scoreText }}</text>
<text class="hint">swipe to move</text>
</stack>
</div>
</template>
<script>
import snake from '../../common/snake.js'
const CELL = 20
const GRID = 16
const OFFSET = 73
export default {
private: {
snake: [],
food: { left: '73px', top: '73px' },
scoreText: 'SCORE 0',
over: false
},
onInit() {
this.dir = { x: 1, y: 0 }
this.pending = null
this.reset()
},
onShow() {
this.timer = setInterval(() => this.tick(), 300)
},
onHide() {
clearInterval(this.timer)
},
onDestroy() {
clearInterval(this.timer)
},
reset() {
this.model = snake.initialSnake()
this.foodModel = snake.spawnFood(this.model, GRID)
this.dir = { x: 1, y: 0 }
this.pending = null
this.over = false
this.rebuild()
},
tick() {
if (this.over) return
if (this.pending) {
this.dir = snake.turn(this.dir, this.pending)
this.pending = null
}
const r = snake.step(this.model, this.dir, this.foodModel, GRID)
if (!r.alive) {
this.over = true
clearInterval(this.timer)
return
}
this.model = r.snake
if (r.ate) {
this.foodModel = snake.spawnFood(this.model, GRID)
}
this.rebuild()
},
restart() {
this.reset()
clearInterval(this.timer)
this.timer = setInterval(() => this.tick(), 300)
},
onSwipe(e) {
if (this.over) return
const d = e.direction
let v
if (d === 'left') v = { x: -1, y: 0 }
else if (d === 'right') v = { x: 1, y: 0 }
else if (d === 'up') v = { x: 0, y: -1 }
else if (d === 'down') v = { x: 0, y: 1 }
else return
this.pending = v
},
onTap() {
if (this.over) this.restart()
},
rebuild() {
const out = []
for (let i = 0; i < this.model.length; i++) {
const s = this.model[i]
out.push({
left: (OFFSET + s.x * CELL + 1) + 'px',
top: (OFFSET + s.y * CELL + 1) + 'px',
cls: i === 0 ? 'seg head' : 'seg'
})
}
this.snake = out
this.food = {
left: (OFFSET + this.foodModel.x * CELL + 3) + 'px',
top: (OFFSET + this.foodModel.y * CELL + 3) + 'px'
}
this.scoreText = 'SCORE ' + (this.model.length - 3)
}
}
</script>
<style>
.page {
width: 466px; height: 466px;
background-color: #000000;
align-items: center;
justify-content: center;
}
.dial {
width: 466px; height: 466px;
}
.board {
position: absolute; left: 71px; top: 71px;
width: 320px; height: 320px;
border-radius: 26px;
border-width: 2px;
border-color: #2a3040;
background-color: #0a0f1a;
}
.seg {
position: absolute;
width: 18px; height: 18px;
border-radius: 4px;
background-color: #35c26a;
}
.seg.head {
background-color: #7cf0a0;
}
.food {
position: absolute;
width: 14px; height: 14px;
border-radius: 7px;
background-color: #ff5a5a;
}
.score {
position: absolute; left: 0px; top: 24px;
width: 466px;
color: #9aa0aa;
font-size: 22px;
text-align: center;
}
.hint {
position: absolute; left: 0px; top: 408px;
width: 466px;
color: #3a4052;
font-size: 18px;
text-align: center;
}
.overlay {
position: absolute; left: 0px; top: 160px;
width: 466px;
flex-direction: column;
align-items: center;
}
.overText {
height: 40px;
color: #ffffff;
font-size: 32px;
text-align: center;
}
.overSub {
height: 32px;
color: #f3a633;
font-size: 24px;
text-align: center;
}
.overHint {
height: 30px;
color: #9aa0aa;
font-size: 20px;
text-align: center;
}
</style>
+67
View File
@@ -0,0 +1,67 @@
// Page wiring test: drives the VM methods extracted from index.ux.
const fs = require('node:fs');
const vm = require('node:vm');
const assert = require('node:assert/strict');
const snake = require('../src/common/snake.js');
const ux = fs.readFileSync('src/pages/index/index.ux', 'utf8');
const body = ux.match(/<script>([\s\S]*?)<\/script>/)[1]
.replace(/import\s+snake\s+from\s+'[^']*';?/, '')
.replace(/^const\s+\w+\s*=[^\n]*\n/gm, '')
.replace('export default', '');
const sandbox = { snake, Date, Math, String, Number, console, setInterval: () => 0, clearInterval: () => {},
CELL: 20, GRID: 16, OFFSET: 73 };
vm.createContext(sandbox);
const spec = vm.runInContext('(' + body + ')', sandbox);
function mk() {
const o = Object.assign({}, spec, JSON.parse(JSON.stringify(spec.private)));
o.$element = () => null;
spec.onInit.call(o);
return o;
}
let c = mk();
assert.equal(c.model.length, 3, 'initialized to length 3');
assert.equal(c.snake.length, 3, 'rendered 3 segments');
assert.equal(c.snake[0].cls, 'seg head', 'head flagged');
assert.equal(c.snake[1].cls, 'seg', 'body flagged');
assert.equal(c.scoreText, 'SCORE 0');
assert.equal(c.snake[0].left, (73 + 6 * 20 + 1) + 'px', 'head x mapped to px');
for (let i = 0; i < 5; i++) c.tick();
assert.equal(c.model[0].x, 11, 'head moved right 5 steps from x=6');
assert.equal(c.over, false);
c.onSwipe({ direction: 'down' });
c.tick();
assert.equal(c.dir.x, 0, 'dir x');
assert.equal(c.dir.y, 1, 'direction turned down');
assert.equal(c.model[0].y, 8, 'head moved down');
c.onSwipe({ direction: 'up' });
c.tick();
assert.equal(c.dir.x, 0, 'reversal keeps x');
assert.equal(c.dir.y, 1, 'reversal blocked');
// run into the wall to trigger game over (GRID=16, last column x=15)
c.model = [{ x: 15, y: 5 }, { x: 14, y: 5 }, { x: 13, y: 5 }];
c.dir = { x: 1, y: 0 };
c.pending = null;
c.tick();
assert.equal(c.over, true, 'game over on wall hit');
c.restart();
assert.equal(c.over, false);
assert.equal(c.model.length, 3);
assert.equal(c.scoreText, 'SCORE 0');
// template uses documented directives/events, no transforms, no crown remnants
assert.match(ux, /for="\{\{ seg in snake \}\}"/);
assert.match(ux, /show="\{\{ over \}\}"/);
assert.match(ux, /onswipe="onSwipe"/);
assert.doesNotMatch(ux, /crownrotationchanged/i);
assert.doesNotMatch(ux, /transform\s*:/);
console.log('PAGE WIRING PASS (movement, turn, reversal, game over, restart, directives)');
+70
View File
@@ -0,0 +1,70 @@
// TDD: Snake core — pure functions, no Vela APIs.
const assert = require('node:assert/strict');
const snake = require('../src/common/snake.js');
// initial snake: head first, heading right, length 3
const init = snake.initialSnake();
assert.equal(init.length, 3, 'starts length 3');
assert.deepEqual(init[0], { x: 6, y: 7 }, 'head at start cell');
assert.deepEqual(init[1], { x: 5, y: 7 }, 'body behind head');
assert.deepEqual(init[2], { x: 4, y: 7 }, 'tail');
// move right into empty cell: alive, no food, length unchanged, tail advances
let r = snake.step(init, { x: 1, y: 0 }, { x: 10, y: 10 }, 14);
assert.equal(r.alive, true);
assert.equal(r.ate, false);
assert.equal(r.snake.length, 3);
assert.deepEqual(r.snake[0], { x: 7, y: 7 }, 'head moved right');
assert.deepEqual(r.snake[2], { x: 5, y: 7 }, 'tail advanced');
// eat food: length grows by 1, tail retained
r = snake.step(r.snake, { x: 1, y: 0 }, { x: 8, y: 7 }, 14);
assert.equal(r.ate, true, 'ate the food ahead');
assert.equal(r.snake.length, 4, 'grew by one');
assert.deepEqual(r.snake[0], { x: 8, y: 7 });
// wall collision: move left wall
r = snake.step([{ x: 0, y: 5 }, { x: 1, y: 5 }], { x: -1, y: 0 }, { x: 3, y: 3 }, 14);
assert.equal(r.alive, false, 'hit left wall');
r = snake.step([{ x: 13, y: 5 }, { x: 12, y: 5 }], { x: 1, y: 0 }, { x: 3, y: 3 }, 14);
assert.equal(r.alive, false, 'hit right wall');
r = snake.step([{ x: 5, y: 0 }, { x: 5, y: 1 }], { x: 0, y: -1 }, { x: 3, y: 3 }, 14);
assert.equal(r.alive, false, 'hit top wall');
r = snake.step([{ x: 5, y: 13 }, { x: 5, y: 12 }], { x: 0, y: 1 }, { x: 3, y: 3 }, 14);
assert.equal(r.alive, false, 'hit bottom wall');
// self collision: run into own body
const loop = [{ x: 5, y: 5 }, { x: 5, y: 6 }, { x: 6, y: 6 }, { x: 6, y: 5 }];
r = snake.step(loop, { x: 0, y: -1 }, { x: 3, y: 3 }, 14); // head 5,5 -> 5,4? no, dir -y -> 5,4 empty
assert.equal(r.alive, true, 'moving away from body is safe');
// head at 5,5 move up into 5,4 (empty), then try to move into own neck is blocked by dir reversal
// direct: build snake where head's next cell is body
const sb = [{ x: 5, y: 5 }, { x: 4, y: 5 }, { x: 4, y: 4 }, { x: 5, y: 4 }];
r = snake.step(sb, { x: 0, y: 1 }, { x: 9, y: 9 }, 14); // 5,5 -> 5,6 empty
assert.equal(r.alive, true);
r = snake.step([{ x: 5, y: 5 }, { x: 4, y: 5 }, { x: 4, y: 4 }, { x: 5, y: 4 }, { x: 6, y: 4 }, { x: 6, y: 5 }], { x: 0, y: 1 }, { x: 9, y: 9 }, 14);
assert.equal(r.alive, true, 'moving into vacating tail cell is allowed');
r = snake.step([{ x: 5, y: 5 }, { x: 5, y: 6 }, { x: 4, y: 6 }, { x: 4, y: 5 }], { x: 0, y: 1 }, { x: 9, y: 9 }, 14); // 5,5 -> 5,6 which is a middle body cell
assert.equal(r.alive, false, 'run into body');
// direction reversal guard
assert.deepEqual(snake.turn({ x: 1, y: 0 }, { x: -1, y: 0 }), { x: 1, y: 0 }, 'cannot reverse into itself');
assert.deepEqual(snake.turn({ x: 1, y: 0 }, { x: 0, y: 1 }), { x: 0, y: 1 }, 'turn down allowed');
assert.deepEqual(snake.turn({ x: 1, y: 0 }, { x: 1, y: 0 }), { x: 1, y: 0 });
// crown rotation: rotate direction ±90° (right->down->left->up, clockwise)
assert.deepEqual(snake.rotateDir({ x: 1, y: 0 }, true), { x: 0, y: 1 }, 'clockwise right->down');
assert.deepEqual(snake.rotateDir({ x: 0, y: 1 }, true), { x: -1, y: 0 }, 'clockwise down->left');
assert.deepEqual(snake.rotateDir({ x: -1, y: 0 }, true), { x: 0, y: -1 }, 'clockwise left->up');
assert.deepEqual(snake.rotateDir({ x: 0, y: -1 }, true), { x: 1, y: 0 }, 'clockwise up->right (wrap)');
assert.deepEqual(snake.rotateDir({ x: 1, y: 0 }, false), { x: 0, y: -1 }, 'counterclockwise right->up');
assert.deepEqual(snake.rotateDir({ x: 0, y: -1 }, false), { x: -1, y: 0 }, 'counterclockwise up->left');
// spawnFood lands on an empty cell
for (let i = 0; i < 50; i++) {
const f = snake.spawnFood([{ x: 0, y: 0 }], 14);
assert.ok(f.x >= 0 && f.x < 14 && f.y >= 0 && f.y < 14, 'in bounds');
assert.ok(!(f.x === 0 && f.y === 0), 'not on snake');
}
console.log('ALL SNAKE LOGIC PASS');