[verified] Snake 0.7: queued controls, records, pause and wrap mode

This commit is contained in:
2026-09-12 12:23:09 +01:00
parent eacad97240
commit 5a7081b933
10 changed files with 548 additions and 109 deletions
+63
View File
@@ -0,0 +1,63 @@
// Vela storage callbacks return raw strings, not { data } wrappers.
// https://iot.mi.com/vela/quickapp/en/features/data/storage.html
function createStore(storage) {
let value = 0
let saved = 0
let loaded = false
let reading = false
let writing = false
let listener = null
function notify() { if (listener) listener(value) }
function flush() {
if (!loaded || writing || value <= saved) return
writing = true
const target = value
let settled = false
const fail = () => { if (!settled) { settled = true; writing = false } }
try {
storage.set({ key: 'snake.best', value: String(target), success() {
if (settled) return
settled = true
writing = false
saved = target
flush()
}, fail })
} catch (e) { fail() }
}
function sync() {
if (loaded) { flush(); return }
if (reading) return
reading = true
let settled = false
const fail = () => { if (!settled) { settled = true; reading = false } }
try {
storage.get({ key: 'snake.best', default: '0', success(raw) {
if (settled) return
settled = true
reading = false
const n = Number(raw)
saved = Number.isInteger(n) && n >= 0 && n <= 253 ? n : 0
value = Math.max(value, saved)
loaded = true
notify()
flush()
}, fail })
} catch (e) { fail() }
}
return {
subscribe(fn) { listener = fn; notify() },
record(score) { value = Math.max(value, score); notify(); sync() },
sync
}
}
// One coordinator per native storage module, retained across page recreation.
let sharedAPI
let sharedStore
function getStore(storage) {
if (storage !== sharedAPI) {
sharedAPI = storage
sharedStore = createStore(storage)
}
return sharedStore
}
module.exports = { getStore }
+22 -13
View File
@@ -8,11 +8,14 @@ function initialSnake() {
}
// Advance the snake one cell in `dir` ({x,y} unit vector). Returns { snake, ate, alive }.
function step(snake, dir, food, N) {
function step(snake, dir, food, N, mode) {
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) {
let nx = head.x + dir.x
let ny = head.y + dir.y
if (mode === 'wrap') {
nx = (nx + N) % N
ny = (ny + N) % N
} else if (nx < 0 || ny < 0 || nx >= N || ny >= N) {
return { snake, ate: false, alive: false }
}
const ate = (nx === food.x && ny === food.y)
@@ -37,16 +40,17 @@ function turn(current, desired) {
// Classify every segment as a texture piece (head/body/corner/tail + compass side),
// so the page can render each cell with the right PNG. Returns one name per segment.
// Sides are screen compass (y grows down): e/w/n/s = right/left/up/down.
function renderPieces(snakeCells, dir) {
function renderPieces(snakeCells, dir, N) {
const D = { '1,0': 'e', '-1,0': 'w', '0,-1': 'n', '0,1': 's' }
const opp = { e: 'w', w: 'e', n: 's', s: 'n' }
const delta = d => N && d === N - 1 ? -1 : N && d === 1 - N ? 1 : d
return snakeCells.map((s, i) => {
if (i === 0) return 'head_' + D[dir.x + ',' + dir.y]
const prev = snakeCells[i - 1]
const next = snakeCells[i + 1]
const from = D[(prev.x - s.x) + ',' + (prev.y - s.y)] // side toward head
const from = D[delta(prev.x - s.x) + ',' + delta(prev.y - s.y)] // side toward head
if (!next) return 'tail_' + opp[from] // tip points away from body
const to = D[(next.x - s.x) + ',' + (next.y - s.y)] // side toward tail tip
const to = D[delta(next.x - s.x) + ',' + delta(next.y - s.y)] // side toward tail tip
if ((from === 'e' || from === 'w') && (to === 'e' || to === 'w')) return 'body_h'
if ((from === 'n' || from === 's') && (to === 'n' || to === 's')) return 'body_v'
// corner: name = the two sides it connects; pairs are alphabetically sorted
@@ -72,12 +76,17 @@ function rotateDir(dir, clockwise) {
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 }
// Select an empty-cell rank uniformly; at most N*N checks, even almost full.
let rank = Math.floor(Math.random() * (N * N - occupied.size))
for (let y = 0; y < N; y++) {
for (let x = 0; x < N; x++) {
if (!occupied.has(x + ',' + y)) {
if (rank === 0) return { x, y }
rank--
}
}
}
return null
}
module.exports = { initialSnake, step, turn, renderPieces, rotateDir, spawnFood }
+3 -3
View File
@@ -2,8 +2,8 @@
"package": "com.ilias.snake",
"name": "SNAKE",
"icon": "/common/icon.png",
"versionName": "0.6",
"versionCode": 6,
"versionName": "0.7",
"versionCode": 7,
"minAPILevel": 1,
"deviceTypeList": [
"watch"
@@ -26,7 +26,7 @@
},
"features": [
{
"name": "system.router"
"name": "system.storage"
}
]
}
+151 -54
View File
@@ -1,21 +1,44 @@
<template>
<div class="page" onswipe="onSwipe">
<stack class="dial">
<image class="board" src="/common/tex/board.png"></image>
<image class="food" src="/common/tex/apple.png" style="left: {{ food.left }}px; top: {{ food.top }}px;"></image>
<image class="seg" src="{{ seg.src }}" for="{{ seg in snake }}" style="left: {{ seg.left }}px; top: {{ seg.top }}px;"></image>
<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>
<image class="board" src="/common/tex/board.png" onclick="onTap"></image>
<image class="food" src="/common/tex/apple.png" show="{{ hasFood }}" onclick="onTap" style="left: {{ food.left }}; top: {{ food.top }};"></image>
<image class="seg" src="{{ seg.src }}" for="{{ seg in snake }}" onclick="onTap" style="left: {{ seg.left }}; top: {{ seg.top }};"></image>
<div class="hud">
<text class="score">{{ scoreText }}</text>
<text class="best">{{ bestText }}</text>
</div>
<div class="footer">
<text class="modeLabel">{{ modeText }}</text>
<text class="hint">swipe / tap to pause</text>
</div>
<div class="overlay" show="{{ paused && !over }}">
<text class="overText">PAUSED</text>
<text class="overSub">{{ scoreText }}</text>
<text class="retry" onclick="onTap">RESUME</text>
<text class="overHint">Change mode: new game</text>
<div class="modes">
<text class="modeButton" onclick="selectMode('classic')">CLASSIC</text>
<text class="modeButton" onclick="selectMode('wrap')">WRAP</text>
</div>
</div>
<div class="overlay" show="{{ over }}">
<text class="overText">{{ endText }}</text>
<text class="overSub">{{ scoreText }}</text>
<text class="retry" onclick="restart">PLAY AGAIN</text>
<text class="overHint">Change mode: new game</text>
<div class="modes">
<text class="modeButton" onclick="selectMode('classic')">CLASSIC</text>
<text class="modeButton" onclick="selectMode('wrap')">WRAP</text>
</div>
</div>
<text class="score">{{ scoreText }}</text>
<text class="hint">swipe to move</text>
</stack>
</div>
</template>
<script>
import snake from '../../common/snake.js'
import storage from '@system.storage'
import best from '../../common/best.js'
const CELL = 20
const GRID = 16
@@ -25,56 +48,103 @@ export default {
private: {
snake: [],
food: { left: '73px', top: '73px' },
hasFood: true,
endText: 'GAME OVER',
scoreText: 'SCORE 0',
bestText: 'BEST 0',
mode: 'classic',
modeText: 'CLASSIC',
paused: false,
over: false
},
onInit() {
this.dir = { x: 1, y: 0 }
this.pending = null
this.queue = []
this.records = best.getStore(storage)
this.records.subscribe(value => { if (!this.destroyed) this.bestText = 'BEST ' + value })
this.reset()
this.records.sync()
},
onShow() {
this.timer = setInterval(() => this.tick(), 300)
if (this.destroyed) return
this.visible = true
this.records.sync()
this.startTimer()
},
stopTimer() {
this.timerEpoch = (this.timerEpoch || 0) + 1
clearInterval(this.timer)
this.timer = null
},
startTimer() {
this.stopTimer()
if (this.destroyed || !this.visible || this.paused || this.over) return
const epoch = this.timerEpoch
this.timer = setInterval(() => {
if (epoch === this.timerEpoch) this.tick()
}, Math.max(120, 300 - (this.model.length - 3) * 10))
},
onHide() {
clearInterval(this.timer)
this.visible = false
this.paused = true
this.queue = []
this.stopTimer()
},
onDestroy() {
clearInterval(this.timer)
this.onHide()
this.destroyed = true
this.records.subscribe(null)
},
reset() {
this.model = snake.initialSnake()
this.foodModel = snake.spawnFood(this.model, GRID)
this.dir = { x: 1, y: 0 }
this.pending = null
this.queue = []
this.over = false
this.endText = 'GAME OVER'
this.paused = 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 (this.over || this.paused || this.destroyed || this.visible === false) return
if (this.queue.length) this.dir = this.queue.shift()
const r = snake.step(this.model, this.dir, this.foodModel, GRID, this.mode)
if (!r.alive) {
this.over = true
clearInterval(this.timer)
this.stopTimer()
return
}
this.model = r.snake
if (r.ate) {
this.foodModel = snake.spawnFood(this.model, GRID)
if (!this.foodModel) {
this.over = true
this.endText = 'YOU WIN'
this.stopTimer()
}
}
this.rebuild()
if (r.ate) {
this.records.record(this.model.length - 3)
this.startTimer()
}
},
selectMode(mode) {
if (this.destroyed || !this.visible || (!this.paused && !this.over)) return
if ((mode !== 'classic' && mode !== 'wrap') || mode === this.mode) return
this.mode = mode
this.modeText = mode === 'wrap' ? 'WRAP' : 'CLASSIC'
this.reset()
this.paused = true
this.stopTimer()
},
restart() {
if (this.destroyed || this.visible === false) return
this.reset()
clearInterval(this.timer)
this.timer = setInterval(() => this.tick(), 300)
this.startTimer()
},
onSwipe(e) {
if (this.over) return
if (this.over || this.paused || this.destroyed || this.visible === false) return
const d = e.direction
let v
if (d === 'left') v = { x: -1, y: 0 }
@@ -82,13 +152,19 @@ export default {
else if (d === 'up') v = { x: 0, y: -1 }
else if (d === 'down') v = { x: 0, y: 1 }
else return
this.pending = v
const last = this.queue.length ? this.queue[this.queue.length - 1] : this.dir
if (this.queue.length >= 2 || (last.x === v.x && last.y === v.y)) return
if (snake.turn(last, v) === last) return
this.queue.push(v)
},
onTap() {
if (this.over) this.restart()
if (this.destroyed || !this.visible || this.over) return
this.paused = !this.paused
this.queue = []
this.startTimer()
},
rebuild() {
const pieces = snake.renderPieces(this.model, this.dir)
const pieces = snake.renderPieces(this.model, this.dir, this.mode === 'wrap' ? GRID : 0)
const out = []
for (let i = 0; i < this.model.length; i++) {
const s = this.model[i]
@@ -99,7 +175,8 @@ export default {
})
}
this.snake = out
this.food = {
this.hasFood = !!this.foodModel
if (this.hasFood) this.food = {
left: (OFFSET + this.foodModel.x * CELL) + 'px',
top: (OFFSET + this.foodModel.y * CELL) + 'px'
}
@@ -130,41 +207,61 @@ export default {
width: 20px; height: 20px;
}
.score {
position: absolute; left: 0px; top: 24px;
width: 466px;
color: #9aa0aa;
font-size: 22px;
text-align: center;
width: 188px; height: 22px;
color: #d8edce; font-size: 18px; text-align: center;
}
.best {
width: 188px; height: 22px;
color: #f3bd60; font-size: 17px; text-align: center;
}
.hud {
position: absolute; left: 139px; top: 24px;
width: 188px; height: 44px;
flex-direction: column; align-items: center;
}
.footer {
position: absolute; left: 135px; top: 400px;
width: 196px; height: 40px;
flex-direction: column; align-items: center;
}
.modeLabel {
width: 196px; height: 20px;
color: #cee4bd; font-size: 17px; text-align: center;
}
.hint {
position: absolute; left: 0px; top: 408px;
width: 466px;
color: #3a4052;
font-size: 18px;
text-align: center;
width: 196px; height: 20px;
color: #adb7c6; font-size: 16px; text-align: center;
}
.overlay {
position: absolute; left: 0px; top: 160px;
width: 466px;
flex-direction: column;
align-items: center;
position: absolute; left: 93px; top: 123px;
width: 280px; height: 220px;
background-color: #101923; border-radius: 18px;
flex-direction: column; align-items: center; justify-content: center;
}
.overText {
height: 40px;
color: #ffffff;
font-size: 32px;
text-align: center;
width: 260px; height: 40px;
color: #ffffff; font-size: 30px; text-align: center;
}
.overSub {
height: 32px;
color: #f3a633;
font-size: 24px;
text-align: center;
width: 260px; height: 30px;
color: #f3bd60; font-size: 22px; text-align: center;
}
.retry {
width: 216px; height: 56px;
background-color: #80bf55; border-radius: 12px;
color: #101923; font-size: 23px; text-align: center;
}
.overHint {
height: 30px;
color: #9aa0aa;
font-size: 20px;
text-align: center;
width: 260px; height: 30px;
color: #adb7c6; font-size: 17px; text-align: center;
}
.modes {
width: 240px; height: 44px;
flex-direction: row; justify-content: space-between;
}
.modeButton {
width: 116px; height: 44px;
background-color: #304252; border-radius: 10px;
color: #ffffff; font-size: 18px; text-align: center;
}
</style>