feat: SodiumPet 小钠桌宠 v0.1.0(Live2D 桌宠 / 经济任务 / 音乐 / 成就 / 编辑器 / MOD)

This commit is contained in:
Tian_XiaRi
2026-12-01 16:41:07 +08:00
commit ba6bcaca98
270 changed files with 33676 additions and 0 deletions
+2362
View File
File diff suppressed because it is too large Load Diff
+89
View File
@@ -0,0 +1,89 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
/** 本地知识库:data/knowledge 下的 .md/.txt,聊天时按关键词检索注入 */
export class KnowledgeBase {
private docs: Array<{ name: string; content: string }> = []
readonly dir: string
constructor(dataDir: string) {
this.dir = path.join(dataDir, 'knowledge')
fs.mkdirSync(this.dir, { recursive: true })
this.reload()
}
reload(): void {
this.docs = []
for (const f of fs.readdirSync(this.dir)) {
if (!/\.(md|txt)$/i.test(f)) continue
try {
const content = fs.readFileSync(path.join(this.dir, f), 'utf8').slice(0, 20000)
this.docs.push({ name: f, content })
} catch {
/* 跳过读不了的文件 */
}
}
}
list(): Array<{ name: string; chars: number }> {
return this.docs.map((d) => ({ name: d.name, chars: d.content.length }))
}
addFromFile(src: string): void {
const name = path.basename(src)
fs.copyFileSync(src, path.join(this.dir, name))
this.reload()
}
remove(name: string): void {
fs.rmSync(path.join(this.dir, name), { force: true })
this.reload()
}
/** 关键词打分,返回最相关的 1~2 段上下文(最多约 700 字) */
search(query: string): string {
if (this.docs.length === 0) return ''
const rawTerms = query
.split(/[\s,。?!、,.!?;;::]+/)
.map((t) => t.trim())
.filter((t) => t.length >= 2)
if (rawTerms.length === 0) return ''
// 长词拆成二元组,中文短语也能命中
const terms = new Set<string>()
for (const t of rawTerms) {
terms.add(t)
if (t.length > 4) {
for (let i = 0; i + 2 <= t.length; i++) terms.add(t.slice(i, i + 2))
}
}
const scored = this.docs
.map((d) => {
const lower = d.content.toLowerCase()
let score = 0
for (const t of terms) {
const idx = lower.indexOf(t.toLowerCase())
if (idx >= 0) score += 1 + (idx < 200 ? 2 : 0)
}
return { d, score }
})
.filter((x) => x.score > 0)
.sort((a, b) => b.score - a.score)
if (scored.length === 0) return ''
const parts = scored.slice(0, 2).map((x) => {
let snippet = x.d.content
for (const t of terms) {
const idx = x.d.content.toLowerCase().indexOf(t.toLowerCase())
if (idx >= 0) {
snippet = x.d.content.slice(Math.max(0, idx - 150), idx + 350)
break
}
}
return `【${x.d.name}】${snippet}`
})
return parts.join('\n\n')
}
}
+123
View File
@@ -0,0 +1,123 @@
import {
fallbackReply,
systemPrompt,
type ChatMessage,
type LlmConfig
} from '../shared/llm'
import type { PetSave } from '../shared/petState'
export class ChatService {
private history: ChatMessage[] = []
constructor(
private readonly getConfig: () => LlmConfig,
private readonly getSave: () => PetSave
) {}
reset(): void {
this.history = []
}
async ask(text: string): Promise<string> {
let full = ''
await this.askStream(text, (chunk) => {
full += chunk
})
return full
}
/** 流式请求:每收到一段 delta 就回调一次,返回完整回复 */
async askStream(
text: string,
onChunk: (chunk: string) => void,
extraContext = "",
imageDataUrl = "",
flavor = "chemistry"
): Promise<string> {
const cfg = this.getConfig()
if (!cfg.enabled || !cfg.apiKey) {
const reply = fallbackReply(text.length + Date.now())
onChunk(reply)
return reply
}
const sys = systemPrompt(this.getSave(), cfg.personaExtra, flavor)
const messages: ChatMessage[] = [
{
role: 'system',
content: extraContext ? `${sys}\n\n【知识库参考,可用可不用】\n${extraContext}` : sys
},
...this.history.slice(-cfg.maxHistory),
{
role: 'user',
content: imageDataUrl
? [
{ type: 'text', text },
{ type: 'image_url', image_url: { url: imageDataUrl } }
]
: text
}
]
const url = `${cfg.baseUrl.replace(/\/+$/, '')}/chat/completions`
const res = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${cfg.apiKey}`
},
body: JSON.stringify({
model: cfg.model,
messages,
temperature: cfg.temperature,
max_tokens: 320,
stream: true
}),
signal: AbortSignal.timeout(45_000)
})
if (!res.ok) {
const body = await res.text().catch(() => '')
throw new Error(`HTTP ${res.status} ${body.slice(0, 200)}`)
}
if (!res.body) throw new Error('无响应体')
const reader = res.body.getReader()
const decoder = new TextDecoder('utf-8')
let full = ''
let buf = ''
for (;;) {
const { done, value } = await reader.read()
if (done) break
buf += decoder.decode(value, { stream: true })
const lines = buf.split('\n')
buf = lines.pop() ?? ''
for (const raw of lines) {
const line = raw.trim()
if (!line.startsWith('data:')) continue
const data = line.slice(5).trim()
if (data === '[DONE]') continue
try {
const json = JSON.parse(data) as {
choices?: Array<{ delta?: { content?: string } }>
}
const delta = json.choices?.[0]?.delta?.content ?? ''
if (delta) {
full += delta
onChunk(delta)
}
} catch {
// 忽略不完整的 JSON 行
}
}
}
if (!full.trim()) throw new Error('空回复')
this.history.push({ role: 'user', content: text }, { role: 'assistant', content: full })
const cap = cfg.maxHistory * 2
if (this.history.length > cap) this.history = this.history.slice(-cap)
return full
}
}
+87
View File
@@ -0,0 +1,87 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
import type { FileMeta, PhotoMeta } from '../shared/media'
/** 图库与文件袋:图片按 pet://photos/<file> 提供 */
export class MediaStore {
photos: PhotoMeta[] = []
files: FileMeta[] = []
readonly photoDir: string
readonly fileDir: string
private readonly photoMetaFile: string
private readonly fileMetaFile: string
constructor(dataDir: string) {
this.photoDir = path.join(dataDir, 'photos')
this.fileDir = path.join(dataDir, 'files')
fs.mkdirSync(this.photoDir, { recursive: true })
fs.mkdirSync(this.fileDir, { recursive: true })
this.photoMetaFile = path.join(dataDir, 'photos.json')
this.fileMetaFile = path.join(dataDir, 'files.json')
this.load()
}
private load(): void {
try {
this.photos = JSON.parse(fs.readFileSync(this.photoMetaFile, 'utf8')) as PhotoMeta[]
} catch {
this.photos = []
}
try {
this.files = JSON.parse(fs.readFileSync(this.fileMetaFile, 'utf8')) as FileMeta[]
} catch {
this.files = []
}
}
private save(): void {
try {
fs.writeFileSync(this.photoMetaFile, JSON.stringify(this.photos, null, 2), 'utf8')
fs.writeFileSync(this.fileMetaFile, JSON.stringify(this.files, null, 2), 'utf8')
} catch (err) {
console.error('[media] 保存失败', err)
}
}
addPhoto(file: string): PhotoMeta {
const meta: PhotoMeta = { id: `${Date.now()}`, file, at: Date.now(), favorite: false, category: '默认' }
this.photos.unshift(meta)
this.save()
return meta
}
toggleFavorite(id: string): void {
const p = this.photos.find((x) => x.id === id)
if (!p) return
p.favorite = !p.favorite
this.save()
}
setCategory(id: string, category: string): void {
const p = this.photos.find((x) => x.id === id)
if (!p) return
p.category = category
this.save()
}
removePhoto(id: string): void {
const p = this.photos.find((x) => x.id === id)
if (!p) return
fs.rmSync(path.join(this.photoDir, p.file), { force: true })
this.photos = this.photos.filter((x) => x.id !== id)
this.save()
}
addFile(name: string, original: string): FileMeta {
const meta: FileMeta = { name, at: Date.now(), original }
this.files.unshift(meta)
this.save()
return meta
}
removeFile(name: string): void {
fs.rmSync(path.join(this.fileDir, name), { force: true })
this.files = this.files.filter((x) => x.name !== name)
this.save()
}
}
+396
View File
@@ -0,0 +1,396 @@
import * as fs from 'node:fs'
import * as path from 'node:path'
import {
DEFAULT_CONFIG,
applyElapsed,
buy,
createSave,
itemById,
petHead,
rest,
startJob,
useItem,
type ActionResult,
type PetConfig,
type PetSave
} from '../shared/petState'
import { DEFAULT_LLM, type LlmConfig } from '../shared/llm'
import { ACHIEVEMENTS } from '../shared/achievements'
import { presetsFor, type PresetDialogue } from '../shared/dialogue'
const PRESET_CYCLE_MS = 30 * 60 * 1000
const OFFLINE_CAP_SECONDS = 12 * 3600
export class StateStore {
private save: PetSave
private config: PetConfig
private readonly file: string
private readonly configFile: string
private readonly llmFile: string
private llm: LlmConfig
private timer: NodeJS.Timeout | null = null
private readonly listeners = new Set<(s: PetSave) => void>()
private readonly configListeners = new Set<(c: PetConfig) => void>()
private readonly achievementListeners = new Set<(a: { title: string; desc: string; icon: string }) => void>()
private lastSaveAt = 0
constructor(private readonly dataDir: string) {
fs.mkdirSync(dataDir, { recursive: true })
this.file = path.join(dataDir, 'save.json')
this.configFile = path.join(dataDir, 'config.json')
this.llmFile = path.join(dataDir, 'llm.json')
this.save = this.load()
this.config = this.loadConfig()
this.llm = this.loadLlm()
}
private load(): PetSave {
const now = Date.now()
let save: PetSave
try {
const raw = fs.readFileSync(this.file, 'utf8')
save = JSON.parse(raw) as PetSave
if (!save || save.version !== 2 || !save.stats || !save.inventory) throw new Error('存档版本不匹配')
if (!save.counters) save.counters = {}
if (typeof save.dailyGiftDay !== 'string') save.dailyGiftDay = ''
if (typeof save.sleeping !== 'boolean') save.sleeping = false
if (typeof save.accidentForgiven !== 'boolean') save.accidentForgiven = false
if (typeof save.playtimeMs !== 'number') save.playtimeMs = 0
if (typeof save.birthday !== 'string') save.birthday = ''
if (typeof save.birthdaySetAt !== 'number') save.birthdaySetAt = 0
if (!save.achievements) save.achievements = {}
if (!Array.isArray(save.log)) save.log = []
} catch {
return createSave(now)
}
const elapsed = Math.min(Math.max((now - save.lastTick) / 1000, 0), OFFLINE_CAP_SECONDS)
if (elapsed > 0) {
applyElapsed(save, elapsed, now)
console.log(`[state] 离线 ${Math.round(elapsed / 60)} 分钟已结算`)
}
save.lastTick = now
return save
}
private loadLlm(): LlmConfig {
try {
const raw = fs.readFileSync(this.llmFile, 'utf8')
return { ...DEFAULT_LLM, ...(JSON.parse(raw) as Partial<LlmConfig>) }
} catch {
return { ...DEFAULT_LLM }
}
}
getLlm(): LlmConfig {
return { ...this.llm }
}
setLlm(patch: Partial<LlmConfig>): LlmConfig {
this.llm = { ...this.llm, ...patch }
try {
fs.writeFileSync(this.llmFile, JSON.stringify(this.llm, null, 2), 'utf8')
} catch (err) {
console.error('[llm] 保存失败', err)
}
return { ...this.llm }
}
/** 给渲染层看的脱敏配置 */
maskedLlm(): LlmConfig {
const key = this.llm.apiKey
return {
...this.llm,
apiKey: key ? `${key.slice(0, 4)}****${key.slice(-4)}` : ''
}
}
private loadConfig(): PetConfig {
try {
const raw = fs.readFileSync(this.configFile, 'utf8')
return { ...DEFAULT_CONFIG, ...(JSON.parse(raw) as Partial<PetConfig>) }
} catch {
return { ...DEFAULT_CONFIG }
}
}
start(): void {
if (this.timer) return
this.timer = setInterval(() => this.tick(), 1000)
this.saveNow()
}
private tick(): void {
const now = Date.now()
const dt = Math.min(Math.max((now - this.save.lastTick) / 1000, 0), 5)
if (dt <= 0) return
applyElapsed(this.save, dt, now)
this.save.lastTick = now
this.checkAchievements()
this.emit()
if (now - this.lastSaveAt > 15_000) this.saveNow()
}
snapshot(): PetSave {
return JSON.parse(JSON.stringify(this.save)) as PetSave
}
getConfig(): PetConfig {
return { ...this.config }
}
setConfig(patch: Partial<PetConfig>): PetConfig {
this.config = { ...this.config, ...patch }
try {
fs.writeFileSync(this.configFile, JSON.stringify(this.config, null, 2), 'utf8')
} catch (err) {
console.error('[config] 保存失败', err)
}
for (const cb of this.configListeners) cb({ ...this.config })
return { ...this.config }
}
onAchievement(cb: (a: { title: string; desc: string; icon: string }) => void): () => void {
this.achievementListeners.add(cb)
return () => this.achievementListeners.delete(cb)
}
/** 检查成就,返回本次新解锁的成就 */
checkAchievements(): Array<{ title: string; desc: string; icon: string }> {
const unlocked: Array<{ title: string; desc: string; icon: string }> = []
for (const a of ACHIEVEMENTS) {
if (this.save.achievements[a.id]) continue
let ok = false
try {
ok = a.check(this.save)
} catch {
ok = false
}
if (ok) {
this.save.achievements[a.id] = Date.now()
unlocked.push({ title: a.title, desc: a.desc, icon: a.icon })
}
}
if (unlocked.length > 0) {
this.pushLog('解锁成就:' + unlocked.map((a) => a.title).join('、'))
this.saveNow()
for (const a of unlocked) for (const cb of this.achievementListeners) cb(a)
}
return unlocked
}
pushLog(text: string): void {
const stamp = new Date()
const hh = String(stamp.getHours()).padStart(2, '0')
const mm = String(stamp.getMinutes()).padStart(2, '0')
this.save.log.unshift(hh + ':' + mm + ' ' + text)
if (this.save.log.length > 60) this.save.log.length = 60
}
/** 取当前可用预设(到期或换风格则重新随机一组,5~7 条) */
getAvailablePresets(flavor: string, now = Date.now()): { presets: PresetDialogue[]; nextAt: number } {
const pool = presetsFor(flavor)
const cur = this.save.presets
if (!cur || now >= cur.cycleAt || cur.flavor !== flavor || !Array.isArray(cur.ids)) {
const count = 5 + Math.floor(Math.random() * 3)
const ids = [...pool.map((p) => p.id)]
for (let i = ids.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1))
;[ids[i], ids[j]] = [ids[j], ids[i]]
}
this.save.presets = {
cycleAt: now + PRESET_CYCLE_MS,
ids: ids.slice(0, Math.min(count, ids.length)),
used: [],
flavor
}
this.saveNow()
}
const st = this.save.presets!
const remaining = st.ids
.filter((id) => !st.used.includes(id))
.map((id) => pool.find((p) => p.id === id))
.filter((p): p is PresetDialogue => Boolean(p))
return { presets: remaining, nextAt: st.cycleAt }
}
markPresetUsed(id: string): void {
const st = this.save.presets
if (!st) return
if (!st.used.includes(id)) st.used.push(id)
this.saveNow()
}
setBirthday(day: string): ActionResult {
const now = Date.now()
if (this.save.birthdaySetAt && now - this.save.birthdaySetAt < 30 * 24 * 3600 * 1000) {
const days = Math.ceil((30 * 24 * 3600 * 1000 - (now - this.save.birthdaySetAt)) / 86400000)
return { ok: false, message: '一个月只能改一次,还要等 ' + days + ' 天' }
}
if (!/^\d{2}-\d{2}$/.test(day)) return { ok: false, message: '日期格式不对' }
this.save.birthday = day
this.save.birthdaySetAt = now
this.pushLog('把主人生日设成了 ' + day)
this.emit()
this.saveNow()
return { ok: true, message: '生日已设为 ' + day }
}
onConfig(cb: (c: PetConfig) => void): () => void {
this.configListeners.add(cb)
return () => this.configListeners.delete(cb)
}
action(name: string, payload?: unknown): ActionResult {
const now = Date.now()
let result: ActionResult
switch (name) {
case 'buy':
result = buy(this.save, String(payload), 1)
break
case 'use': {
const id = String(payload)
result = useItem(this.save, id)
if (result.ok) this.save.counters[`use:${id}`] = (this.save.counters[`use:${id}`] ?? 0) + 1
break
}
case 'work': {
const p = payload as { id?: string; mult?: number } | string | undefined
const id = typeof p === 'string' ? p : String(p?.id ?? '')
const mult = typeof p === 'string' ? 1 : Number(p?.mult ?? 1)
result = startJob(this.save, id, now, mult)
break
}
case 'rest':
result = rest(this.save, now)
break
case 'pet':
result = petHead(this.save, now)
break
case 'sleep':
this.save.sleeping = !this.save.sleeping
result = { ok: true, message: this.save.sleeping ? '晚安……' : '我醒了' }
break
default:
result = { ok: false, message: '未知操作' }
}
if (result.ok) {
if (name === 'use') this.pushLog('使用了 ' + String(payload))
if (name === 'buy') this.pushLog('购买了 ' + String(payload))
if (name === 'work') this.pushLog('开始了任务')
if (name === 'pet') this.pushLog('被摸了摸头')
if (name === 'sleep') this.pushLog(this.save.sleeping ? '睡着了' : '醒了')
this.checkAchievements()
this.emit()
this.saveNow()
}
return result
}
applyJobPenalty(p: { money?: number; mood?: number; oxidation?: number }): void {
if (p.money) this.save.money = Math.max(0, this.save.money + p.money)
if (p.mood) this.save.stats.mood = Math.max(0, Math.min(100, this.save.stats.mood + p.mood))
if (p.oxidation) {
this.save.stats.oxidation = Math.max(0, Math.min(100, this.save.stats.oxidation + p.oxidation))
}
this.emit()
this.saveNow()
}
applyChatEffect(e: {
mood?: number
bond?: number
electron?: number
satiety?: number
paraffin?: number
oxidation?: number
}): void {
const s = this.save.stats
if (e.mood) s.mood = Math.max(0, Math.min(100, s.mood + e.mood))
if (e.paraffin) s.paraffin = Math.max(0, Math.min(100, s.paraffin + e.paraffin))
if (e.bond) s.bond = Math.max(0, Math.min(100, s.bond + e.bond))
if (e.electron) s.electron = Math.max(0, Math.min(100, s.electron + e.electron))
if (e.satiety) s.satiety = Math.max(0, Math.min(100, s.satiety + e.satiety))
if (e.oxidation) s.oxidation = Math.max(0, Math.min(100, s.oxidation + e.oxidation))
this.emit()
this.saveNow()
}
autoBuy(itemId: string): ActionResult {
const r = buy(this.save, itemId, 1)
if (r.ok) {
this.emit()
this.saveNow()
}
return r
}
renamePet(name: string): void {
this.save.name = String(name).trim() || this.save.name
this.emit()
this.saveNow()
}
claimDaily(): ActionResult {
const day = new Date().toISOString().slice(0, 10)
if (this.save.dailyGiftDay === day) return { ok: false, message: '今天的礼包已经领过了' }
this.save.dailyGiftDay = day
this.save.money += 30
this.emit()
this.saveNow()
return { ok: true, message: '每日礼包:经费 +30' }
}
forgiveAccident(): boolean {
if (this.save.accidentForgiven) return false
this.save.accidentForgiven = true
this.emit()
this.saveNow()
return true
}
buySpecial(itemId: string, price: number): ActionResult {
const item = itemById(itemId)
if (!item) return { ok: false, message: '没有这件商品' }
if (this.save.money < price) return { ok: false, message: '金币不够啦' }
this.save.money -= price
this.save.inventory[itemId] = (this.save.inventory[itemId] ?? 0) + 1
this.emit()
this.saveNow()
return { ok: true, message: '领用成功' }
}
subscribe(cb: (s: PetSave) => void): () => void {
this.listeners.add(cb)
return () => this.listeners.delete(cb)
}
private emit(): void {
const snap = this.snapshot()
for (const cb of this.listeners) {
try {
cb(snap)
} catch (err) {
console.warn('[state] listener error', err)
}
}
}
saveNow(): void {
try {
const tmp = `${this.file}.tmp`
fs.writeFileSync(tmp, JSON.stringify(this.save, null, 2), 'utf8')
fs.renameSync(tmp, this.file)
this.lastSaveAt = Date.now()
} catch (err) {
console.error('[state] 存档失败', err)
}
}
dispose(): void {
if (this.timer) clearInterval(this.timer)
this.timer = null
this.saveNow()
}
}
+285
View File
@@ -0,0 +1,285 @@
import { contextBridge, ipcRenderer, webUtils } from 'electron'
import type { FileMeta, PhotoMeta } from '../shared/media'
import type { ActionResult, PetConfig, PetSave } from '../shared/petState'
import type { LlmConfig } from '../shared/llm'
export interface PetBridge {
platform: NodeJS.Platform
dragStart: () => void
dragEnd: () => void
quit: () => void
getState: () => Promise<PetSave>
action: (name: string, payload?: unknown) => Promise<ActionResult>
onState: (cb: (s: PetSave) => void) => () => void
getConfig: () => Promise<PetConfig>
setConfig: (patch: Partial<PetConfig>) => Promise<PetConfig>
onConfig: (cb: (c: PetConfig) => void) => () => void
openPanel: () => void
openPanelAt: (tab: string, arg?: string) => void
toggleMenu: () => void
importPhotos: () => Promise<PhotoMeta[]>
saveCalibration: (id: string, cal: unknown) => void
setPanelTitle: (label: string) => void
openStorage: () => void
openDetail: () => void
setChatExpanded: (open: boolean) => void
openEditor: () => void
getCatalog: () => Promise<{ items: unknown[]; jobs: unknown[] }>
saveCatalog: (data: unknown) => Promise<ActionResult>
onCatalogChanged: (cb: () => void) => () => void
importIcon: () => Promise<string>
chatPreset: (id: string) => Promise<{
ok: boolean
message: string
reply?: string
presets?: Array<{ id: string; text: string; textNormal: string; kind: string }>
}>
getMods: () => Promise<string[]>
addMod: () => Promise<{ ok: boolean; message: string; mods: string[] }>
removeMod: (name: string) => Promise<string[]>
getChatPresets: () => Promise<{
presets: Array<{ id: string; text: string; textNormal: string; kind: string }>
nextAt: number
}>
openMusic: () => void
chooseMusicDir: () => Promise<{ dir: string; tracks: Array<{ name: string; file: string }> }>
listMusic: () => Promise<{ dir: string; tracks: Array<{ name: string; file: string }> }>
getMusicBase: () => Promise<string>
getMusicPlaylist: () => Promise<Array<{ name: string; file: string }>>
addMusicPlaylist: (t: { name: string; file: string }) => Promise<Array<{ name: string; file: string }>>
removeMusicPlaylist: (file: string) => Promise<Array<{ name: string; file: string }>>
getLyric: (file: string) => Promise<string>
sendMusicNow: (payload: unknown) => void
onMusicNow: (cb: (p: unknown) => void) => () => void
onMusicList: (
cb: (p: { dir: string; tracks: Array<{ name: string; file: string }> }) => void
) => () => void
openLyric: () => void
closeLyric: () => void
getElementInfo: (z: number, name: string, symbol: string) => Promise<{ text: string; cached: boolean }>
getDailySpecial: () => Promise<{ itemId: string; price: number; day: string; name: string; origin: number; claimed: boolean }>
claimDailyGift: () => Promise<ActionResult>
setBirthday: (day: string) => Promise<ActionResult>
buyDailySpecial: () => Promise<ActionResult>
getWs: () => Promise<Array<{ name: string; size: number }>>
getProfiles: () => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
delProfile: (id: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
onLook: (cb: (p: { x: number; y: number }) => void) => () => void
onSkins: (cb: (list: Array<{ id: string; name: string; active: boolean }>) => void) => () => void
createProfile: (name: string, skinId: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
renameProfile: (id: string, name: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
switchProfile: (id: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
renameSkin: (id: string, name: string) => Promise<Array<{ id: string; name: string; active: boolean }>>
getSkins: () => Promise<Array<{ id: string; name: string; active: boolean }>>
importSkin: () => Promise<Array<{ id: string; name: string; active: boolean }>>
switchSkin: (id: string) => Promise<Array<{ id: string; name: string; active: boolean }>>
delWs: (name: string) => Promise<Array<{ name: string; size: number }>>
openWs: () => Promise<void>
closePanel: () => void
bark: (kind: string) => void
showMenu: () => void
chat: (text: string) => Promise<{ ok: boolean; reply: string }>
getLlm: () => Promise<LlmConfig>
setLlm: (patch: Partial<LlmConfig>) => Promise<LlmConfig>
hideMenu: () => void
selectMenu: (tab: string) => void
onBubble: (cb: (b: { text: string; duration: number }) => void) => () => void
onBubbleStreamStart: (cb: () => void) => () => void
onBubbleChunk: (cb: (text: string) => void) => () => void
onBubbleStreamEnd: (cb: (d: { duration: number }) => void) => () => void
onToast: (cb: (text: string) => void) => () => void
onEvent: (cb: (e: { id: string; type: string; until: number } | null) => void) => () => void
onMotion: (cb: (name: string) => void) => () => void
eventResolve: (id: string) => void
getPhotos: () => Promise<PhotoMeta[]>
capturePhoto: () => Promise<PhotoMeta[]>
favPhoto: (id: string) => Promise<PhotoMeta[]>
delPhoto: (id: string) => Promise<PhotoMeta[]>
openPhoto: (id: string) => Promise<void>
onPhotos: (cb: (list: PhotoMeta[]) => void) => () => void
getFiles: () => Promise<FileMeta[]>
delFile: (name: string) => Promise<FileMeta[]>
openFile: (name: string) => Promise<void>
onNavigate: (cb: (nav: { tab: string; arg?: string }) => void) => () => void
setPhotoCat: (id: string, cat: string) => Promise<PhotoMeta[]>
onFiles: (cb: (list: FileMeta[]) => void) => () => void
dropFile: (file: unknown) => void
getKb: () => Promise<Array<{ name: string; chars: number }>>
addKb: (name: string) => Promise<Array<{ name: string; chars: number }>>
delKb: (name: string) => Promise<Array<{ name: string; chars: number }>>
getBubble: () => Promise<{ text: string; duration: number; at: number } | null>
}
contextBridge.exposeInMainWorld('pet', {
platform: process.platform,
dragStart: () => ipcRenderer.send('pet:drag:start'),
dragEnd: () => ipcRenderer.send('pet:drag:end'),
quit: () => ipcRenderer.send('pet:quit'),
getState: () => ipcRenderer.invoke('pet:state:get'),
action: (name: string, payload?: unknown) => ipcRenderer.invoke('pet:action', name, payload),
onState: (cb: (s: PetSave) => void) => {
const listener = (_e: unknown, s: PetSave): void => cb(s)
ipcRenderer.on('pet:state:update', listener)
return () => ipcRenderer.removeListener('pet:state:update', listener)
},
getConfig: () => ipcRenderer.invoke('pet:config:get'),
setConfig: (patch: Partial<PetConfig>) => ipcRenderer.invoke('pet:config:set', patch),
onConfig: (cb: (c: PetConfig) => void) => {
const listener = (_e: unknown, c: PetConfig): void => cb(c)
ipcRenderer.on('pet:config:update', listener)
return () => ipcRenderer.removeListener('pet:config:update', listener)
},
openPanel: () => ipcRenderer.send('pet:panel:open'),
openPanelAt: (tab: string, arg?: string) => ipcRenderer.send('pet:panel:open', tab, arg),
toggleMenu: () => ipcRenderer.send('pet:menu:toggle'),
importPhotos: () => ipcRenderer.invoke('pet:photos:import'),
saveCalibration: (id: string, cal: unknown) => ipcRenderer.invoke('pet:skin:calibrate', id, cal),
setPanelTitle: (label: string) => ipcRenderer.send('pet:panel:title', label),
openStorage: () => ipcRenderer.send('pet:storage:open'),
openDetail: () => ipcRenderer.send('pet:detail:open'),
setChatExpanded: (open: boolean) => ipcRenderer.send('pet:chat:expand', open),
openEditor: () => ipcRenderer.send('pet:editor:open'),
getCatalog: () => ipcRenderer.invoke('pet:catalog:get'),
saveCatalog: (data: unknown) => ipcRenderer.invoke('pet:catalog:save', data),
onCatalogChanged: (cb: () => void) => {
const l = (): void => cb()
ipcRenderer.on('pet:catalog:changed', l)
return () => ipcRenderer.removeListener('pet:catalog:changed', l)
},
importIcon: () => ipcRenderer.invoke('pet:icon:import'),
chatPreset: (id: string) => ipcRenderer.invoke('pet:chat:preset', id),
getMods: () => ipcRenderer.invoke('pet:mods:list'),
addMod: () => ipcRenderer.invoke('pet:mods:add'),
removeMod: (name: string) => ipcRenderer.invoke('pet:mods:remove', name),
getChatPresets: () => ipcRenderer.invoke('pet:chat:presets'),
openMusic: () => ipcRenderer.send('pet:music:open'),
chooseMusicDir: () => ipcRenderer.invoke('pet:music:choose'),
listMusic: () => ipcRenderer.invoke('pet:music:list'),
getMusicBase: () => ipcRenderer.invoke('pet:music:base'),
getMusicPlaylist: () => ipcRenderer.invoke('pet:music:playlist'),
addMusicPlaylist: (t: { name: string; file: string }) => ipcRenderer.invoke('pet:music:playlist:add', t),
removeMusicPlaylist: (file: string) =>
ipcRenderer.invoke('pet:music:playlist:remove', file),
getLyric: (file: string) => ipcRenderer.invoke('pet:music:lyric', file),
sendMusicNow: (payload: unknown) => ipcRenderer.send('pet:music:now', payload),
onMusicNow: (cb: (p: unknown) => void) => {
const l = (_e: unknown, p: unknown): void => cb(p)
ipcRenderer.on('pet:music:now', l)
return () => ipcRenderer.removeListener('pet:music:now', l)
},
onMusicList: (
cb: (p: { dir: string; tracks: Array<{ name: string; file: string }> }) => void
) => {
const l = (
_e: unknown,
p: { dir: string; tracks: Array<{ name: string; file: string }> }
): void => cb(p)
ipcRenderer.on('pet:music:list', l)
return () => ipcRenderer.removeListener('pet:music:list', l)
},
openLyric: () => ipcRenderer.send('pet:lyric:open'),
closeLyric: () => ipcRenderer.send('pet:lyric:close'),
getElementInfo: (z: number, name: string, symbol: string) => ipcRenderer.invoke('pet:element:info', z, name, symbol),
getDailySpecial: () => ipcRenderer.invoke('pet:daily:special'),
claimDailyGift: () => ipcRenderer.invoke('pet:daily:gift'),
setBirthday: (day: string) => ipcRenderer.invoke('pet:birthday:set', day),
buyDailySpecial: () => ipcRenderer.invoke('pet:daily:buy'),
getWs: () => ipcRenderer.invoke('pet:ws:list'),
delWs: (name: string) => ipcRenderer.invoke('pet:ws:del', name),
openWs: () => ipcRenderer.invoke('pet:ws:open'),
getProfiles: () => ipcRenderer.invoke('pet:profiles:list'),
createProfile: (name: string, skinId: string) => ipcRenderer.invoke('pet:profiles:create', name, skinId),
renameProfile: (id: string, name: string) => ipcRenderer.invoke('pet:profiles:rename', id, name),
renameSkin: (id: string, name: string) => ipcRenderer.invoke('pet:skins:rename', id, name),
switchProfile: (id: string) => ipcRenderer.invoke('pet:profiles:switch', id),
delProfile: (id: string) => ipcRenderer.invoke('pet:profiles:del', id),
onLook: (cb: (p: { x: number; y: number }) => void) => {
const l = (_e: unknown, p: { x: number; y: number }): void => cb(p)
ipcRenderer.on('pet:look', l)
return () => ipcRenderer.removeListener('pet:look', l)
},
onSkins: (cb: (list: Array<{ id: string; name: string; active: boolean }>) => void) => {
const l = (_e: unknown, list: Array<{ id: string; name: string; active: boolean }>): void => cb(list)
ipcRenderer.on('pet:skins:update', l)
return () => ipcRenderer.removeListener('pet:skins:update', l)
},
getSkins: () => ipcRenderer.invoke('pet:skins:list'),
importSkin: () => ipcRenderer.invoke('pet:skins:import'),
switchSkin: (id: string) => ipcRenderer.invoke('pet:skins:switch', id),
closePanel: () => ipcRenderer.send('pet:panel:close'),
bark: (kind: string) => ipcRenderer.send('pet:bark', kind),
showMenu: () => ipcRenderer.send('pet:menu:show'),
chat: (text: string) => ipcRenderer.invoke('pet:chat', text),
getLlm: () => ipcRenderer.invoke('pet:llm:get'),
setLlm: (patch: Partial<LlmConfig>) => ipcRenderer.invoke('pet:llm:set', patch),
hideMenu: () => ipcRenderer.send('pet:menu:hide'),
selectMenu: (tab: string) => ipcRenderer.send('pet:menu:select', tab),
getBubble: () => ipcRenderer.invoke('pet:bubble:current'),
onEvent: (cb: (e: { id: string; type: string; until: number } | null) => void) => {
const l = (_ev: unknown, e: { id: string; type: string; until: number } | null): void => cb(e)
ipcRenderer.on('pet:event', l)
return () => ipcRenderer.removeListener('pet:event', l)
},
onMotion: (cb: (name: string) => void) => {
const l = (_ev: unknown, name: string): void => cb(name)
ipcRenderer.on('pet:motion', l)
return () => ipcRenderer.removeListener('pet:motion', l)
},
eventResolve: (id: string) => ipcRenderer.send('pet:event:resolve', id),
getPhotos: () => ipcRenderer.invoke('pet:photos:list'),
capturePhoto: () => ipcRenderer.invoke('pet:photos:capture'),
favPhoto: (id: string) => ipcRenderer.invoke('pet:photos:fav', id),
delPhoto: (id: string) => ipcRenderer.invoke('pet:photos:del', id),
openPhoto: (id: string) => ipcRenderer.invoke('pet:photos:open', id),
onPhotos: (cb: (list: PhotoMeta[]) => void) => {
const l = (_e: unknown, list: PhotoMeta[]): void => cb(list)
ipcRenderer.on('pet:photos:update', l)
return () => ipcRenderer.removeListener('pet:photos:update', l)
},
getFiles: () => ipcRenderer.invoke('pet:files:list'),
delFile: (name: string) => ipcRenderer.invoke('pet:files:del', name),
openFile: (name: string) => ipcRenderer.invoke('pet:files:open', name),
onNavigate: (cb: (nav: { tab: string; arg?: string }) => void) => {
const l = (_e: unknown, nav: { tab: string; arg?: string }): void => cb(nav)
ipcRenderer.on('pet:panel:navigate', l)
return () => ipcRenderer.removeListener('pet:panel:navigate', l)
},
setPhotoCat: (id: string, cat: string) => ipcRenderer.invoke('pet:photos:cat', id, cat),
onFiles: (cb: (list: FileMeta[]) => void) => {
const l = (_e: unknown, list: FileMeta[]): void => cb(list)
ipcRenderer.on('pet:files:update', l)
return () => ipcRenderer.removeListener('pet:files:update', l)
},
getKb: () => ipcRenderer.invoke('pet:kb:list'),
addKb: (name: string) => ipcRenderer.invoke('pet:kb:add', name),
delKb: (name: string) => ipcRenderer.invoke('pet:kb:del', name),
dropFile: (file: unknown) => {
const p = webUtils.getPathForFile(file as File)
ipcRenderer.send('pet:file:drop', p)
},
onToast: (cb: (text: string) => void) => {
const listener = (_e: unknown, text: string): void => cb(text)
ipcRenderer.on('pet:toast', listener)
return () => ipcRenderer.removeListener('pet:toast', listener)
},
onBubbleStreamStart: (cb: () => void) => {
const l = (): void => cb()
ipcRenderer.on('pet:bubble:stream:start', l)
return () => ipcRenderer.removeListener('pet:bubble:stream:start', l)
},
onBubbleChunk: (cb: (text: string) => void) => {
const l = (_e: unknown, d: { text: string }): void => cb(d.text)
ipcRenderer.on('pet:bubble:stream:chunk', l)
return () => ipcRenderer.removeListener('pet:bubble:stream:chunk', l)
},
onBubbleStreamEnd: (cb: (d: { duration: number }) => void) => {
const l = (_e: unknown, d: { duration: number }): void => cb(d)
ipcRenderer.on('pet:bubble:stream:end', l)
return () => ipcRenderer.removeListener('pet:bubble:stream:end', l)
},
onBubble: (cb: (b: { text: string; duration: number }) => void) => {
const listener = (_e: unknown, b: { text: string; duration: number }): void => cb(b)
ipcRenderer.on('pet:bubble', listener)
return () => ipcRenderer.removeListener('pet:bubble', listener)
}
} satisfies PetBridge)
+15
View File
@@ -0,0 +1,15 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta
http-equiv="Content-Security-Policy"
content="default-src 'self'; img-src 'self' pet: data: blob:; media-src 'self' pet: http://127.0.0.1:* blob: data:; connect-src 'self' pet: ws: http://localhost:* http://127.0.0.1:*; script-src 'self' pet: 'unsafe-inline' 'unsafe-eval'; style-src 'self' 'unsafe-inline';"
/>
<title>小钠</title>
</head>
<body>
<div id="root"></div>
<script type="module" src="./src/main.tsx"></script>
</body>
</html>
File diff suppressed because one or more lines are too long
+243
View File
@@ -0,0 +1,243 @@
import { useEffect, useRef, useState } from 'react'
import type { SkinManifest } from '../../shared/types'
import { DESIGN_H, DESIGN_W, DEFAULT_CONFIG, moodOf, type PetConfig } from '../../shared/petState'
import { createAvatar } from './pet/createAvatar'
import type { AvatarAdapter } from './pet/types'
import { api } from './api'
import './toast.css'
const TAP_SLOP = 4
export default function App(): React.ReactElement {
const stageRef = useRef<HTMLDivElement>(null)
const adapterRef = useRef<AvatarAdapter | null>(null)
const [error, setError] = useState<string | null>(null)
const [hint, setHint] = useState(true)
const [cfg, setCfg] = useState<PetConfig>(DEFAULT_CONFIG)
const [toast, setToast] = useState('')
const [eventInfo, setEventInfo] = useState<{ id: string; type: string; until: number } | null>(null)
const [eventNow, setEventNow] = useState(Date.now())
const cfgRef = useRef<PetConfig>(DEFAULT_CONFIG)
const loadedSkinRef = useRef('')
const dragRef = useRef({ active: false, moved: false, sx: 0, sy: 0 })
const draggingRef = useRef(false)
const lastMoodRef = useRef<string>('')
useEffect(() => {
let disposed = false
async function boot(): Promise<void> {
try {
const a = api()
const latest = (await a?.getConfig()) ?? cfgRef.current
cfgRef.current = latest
setCfg(latest)
const skinId = latest.currentSkin || 'xiaona'
const baseUrl = `pet://skins/${skinId}/`
const res = await fetch(`${baseUrl}skin.json`)
if (!res.ok) throw new Error(`读取皮肤清单失败:HTTP ${res.status}`)
const skin = (await res.json()) as SkinManifest
const adapter = await createAvatar({ skin, baseUrl })
if (disposed) {
adapter.destroy()
return
}
if (!stageRef.current) throw new Error('舞台节点未就绪')
await adapter.mount(stageRef.current, {
w: DESIGN_W * cfgRef.current.scale,
h: DESIGN_H * cfgRef.current.scale
})
adapterRef.current = adapter
adapter.resize(DESIGN_W * cfgRef.current.scale, DESIGN_H * cfgRef.current.scale)
void adapter.play(skin.motions?.idle ?? 'Idle', true)
loadedSkinRef.current = cfgRef.current.currentSkin || 'xiaona'
{
const calAny = skin.avatar.calibration as { v?: number } | undefined
const imported = (skin as { flavor?: string }).flavor === 'normal'
const needCal = !calAny || (imported && (calAny.v ?? 0) < 2)
if (needCal) {
window.setTimeout(() => adapterRef.current?.tryAutoCalibrate?.(), 900)
}
}
} catch (err) {
console.error(err)
setError(err instanceof Error ? `${err.message}` : String(err))
}
}
void boot()
const a = api()
void a?.getConfig().then(setCfg)
const offCfg = a?.onConfig(setCfg)
void a?.getState().then((s) => applyMood(moodOf(s.stats)))
const offState = a?.onState((s) => applyMood(moodOf(s.stats)))
const offToast = a?.onToast((t) => showToast(t))
const offEvent = a?.onEvent(setEventInfo)
const offMotion = a?.onMotion((name) => {
void adapterRef.current?.play(name)
})
const offLook = a?.onLook((p) => {
adapterRef.current?.lookAt?.(p.x, p.y)
})
const eventTimer = window.setInterval(() => setEventNow(Date.now()), 500)
const onBlur = (): void => {
if (!draggingRef.current) return
dragRef.current.active = false
draggingRef.current = false
api()?.dragEnd()
document.getElementById('root')?.classList.remove('dragging')
}
window.addEventListener('blur', onBlur)
return () => {
disposed = true
window.removeEventListener('blur', onBlur)
offCfg?.()
offState?.()
offToast?.()
offEvent?.()
offMotion?.()
offLook?.()
window.clearInterval(eventTimer)
adapterRef.current?.destroy()
adapterRef.current = null
}
}, [])
// 配置变化(缩放/裁剪)后按设计尺寸重排
useEffect(() => {
cfgRef.current = cfg
document.documentElement.dataset.theme = cfg.theme
const w = DESIGN_W * cfg.scale
const h = DESIGN_H * cfg.scale
adapterRef.current?.resize(w, h)
if (!cfg.eyeFollow) adapterRef.current?.lookAt?.(-1, -1)
// 只有模型已经挂载完成(记录过皮肤)且皮肤确实变了才重载,避免启动时的无限重载循环
if (loadedSkinRef.current && (cfg.currentSkin || 'xiaona') !== loadedSkinRef.current) {
window.location.reload()
}
}, [cfg])
function showToast(text: string): void {
setToast(text)
window.setTimeout(() => setToast(''), 1800)
}
function applyMood(mood: string): void {
if (mood === lastMoodRef.current) return
lastMoodRef.current = mood
adapterRef.current?.expression(mood)
}
useEffect(() => {
const t = setTimeout(() => setHint(false), 4000)
return () => clearTimeout(t)
}, [])
function onPointerDown(e: React.PointerEvent<HTMLDivElement>): void {
if (e.button !== 0) return
// 遇水危机:点击 = 擦干
if (eventInfo) {
api()?.eventResolve(eventInfo.id)
setEventInfo(null)
return
}
dragRef.current = { active: true, moved: false, sx: e.clientX, sy: e.clientY }
draggingRef.current = true
api()?.dragStart()
;(e.currentTarget as HTMLElement).setPointerCapture(e.pointerId)
}
function onPointerMove(e: React.PointerEvent<HTMLDivElement>): void {
const d = dragRef.current
if (!d.active) return
if (e.buttons === 0) {
endDrag()
return
}
if (Math.abs(e.clientX - d.sx) > TAP_SLOP || Math.abs(e.clientY - d.sy) > TAP_SLOP) {
d.moved = true
document.getElementById('root')?.classList.add('dragging')
}
if (cfg.eyeFollow) {
adapterRef.current?.lookAt?.(e.clientX + cfg.cropLeft, e.clientY + cfg.cropTop)
}
}
function endDrag(): void {
const d = dragRef.current
if (!d.active) return
d.active = false
draggingRef.current = false
api()?.dragEnd()
document.getElementById('root')?.classList.remove('dragging')
if (d.moved) return
const adapter = adapterRef.current
if (!adapter) return
// 先看这次摸头有没有成功(冷却中不加数值、不弹加成提示)
void api()
?.action('pet')
.then((r) => {
if (!r) return
if (r.ok) {
api()?.bark('click')
showToast('心情 +4 · 亲和 +1')
adapter.expression('happy')
void adapter.play('nod')
} else {
showToast(r.message)
}
setTimeout(() => {
lastMoodRef.current = ''
adapter.expression(null)
}, 1600)
})
}
const stageW = DESIGN_W * cfg.scale
const stageH = DESIGN_H * cfg.scale
return (
<div
onPointerDown={onPointerDown}
onPointerMove={onPointerMove}
onPointerUp={endDrag}
onPointerCancel={endDrag}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault()
for (const f of Array.from(e.dataTransfer.files)) api()?.dropFile(f)
}}
onContextMenu={(e) => {
e.preventDefault()
api()?.toggleMenu()
}}
style={{ width: '100%', height: '100%', overflow: 'hidden', position: 'relative' }}
>
<div
ref={stageRef}
className="pet-stage"
style={{ width: stageW, height: stageH, left: -cfg.cropLeft, top: -cfg.cropTop }}
/>
{error && <div className="pet-error">加载失败:{error}</div>}
{hint && !error && <div className="pet-hint">拖动 · 单击摸头 · 右键面板</div>}
{toast && <div className="pet-toast">{toast}</div>}
{eventInfo && (
<div className="water-event">
<div className="water-droplet">💧</div>
<div className="water-text">
快擦干!{Math.max(0, Math.ceil((eventInfo.until - eventNow) / 1000))}s
</div>
</div>
)}
</div>
)
}
+120
View File
@@ -0,0 +1,120 @@
import type { ActionResult, PetConfig, PetSave } from '../../shared/petState'
import type { LlmConfig } from '../../shared/llm'
import type { FileMeta, PhotoMeta } from '../../shared/media'
export interface PetApi {
platform: string
dragStart: () => void
dragEnd: () => void
quit: () => void
getState: () => Promise<PetSave>
action: (name: string, payload?: unknown) => Promise<ActionResult>
onState: (cb: (s: PetSave) => void) => () => void
getConfig: () => Promise<PetConfig>
setConfig: (patch: Partial<PetConfig>) => Promise<PetConfig>
onConfig: (cb: (c: PetConfig) => void) => () => void
openPanel: () => void
openPanelAt: (tab: string, arg?: string) => void
toggleMenu: () => void
importPhotos: () => Promise<PhotoMeta[]>
saveCalibration: (id: string, cal: unknown) => void
setPanelTitle: (label: string) => void
openStorage: () => void
openDetail: () => void
setChatExpanded: (open: boolean) => void
openEditor: () => void
getCatalog: () => Promise<{ items: unknown[]; jobs: unknown[] }>
saveCatalog: (data: unknown) => Promise<ActionResult>
onCatalogChanged: (cb: () => void) => () => void
importIcon: () => Promise<string>
chatPreset: (id: string) => Promise<{
ok: boolean
message: string
reply?: string
presets?: Array<{ id: string; text: string; textNormal: string; kind: string }>
}>
getMods: () => Promise<string[]>
addMod: () => Promise<{ ok: boolean; message: string; mods: string[] }>
removeMod: (name: string) => Promise<string[]>
getChatPresets: () => Promise<{
presets: Array<{ id: string; text: string; textNormal: string; kind: string }>
nextAt: number
}>
openMusic: () => void
chooseMusicDir: () => Promise<{ dir: string; tracks: Array<{ name: string; file: string }> }>
listMusic: () => Promise<{ dir: string; tracks: Array<{ name: string; file: string }> }>
getMusicBase: () => Promise<string>
getMusicPlaylist: () => Promise<Array<{ name: string; file: string }>>
addMusicPlaylist: (t: { name: string; file: string }) => Promise<Array<{ name: string; file: string }>>
removeMusicPlaylist: (file: string) => Promise<Array<{ name: string; file: string }>>
getLyric: (file: string) => Promise<string>
sendMusicNow: (payload: unknown) => void
onMusicNow: (cb: (p: unknown) => void) => () => void
onMusicList: (
cb: (p: { dir: string; tracks: Array<{ name: string; file: string }> }) => void
) => () => void
openLyric: () => void
closeLyric: () => void
getElementInfo: (z: number, name: string, symbol: string) => Promise<{ text: string; cached: boolean }>
getDailySpecial: () => Promise<{ itemId: string; price: number; day: string; name: string; origin: number; claimed: boolean }>
claimDailyGift: () => Promise<ActionResult>
setBirthday: (day: string) => Promise<ActionResult>
buyDailySpecial: () => Promise<ActionResult>
getWs: () => Promise<Array<{ name: string; size: number }>>
getProfiles: () => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
createProfile: (name: string, skinId: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
renameProfile: (id: string, name: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
renameSkin: (id: string, name: string) => Promise<Array<{ id: string; name: string; active: boolean }>>
delProfile: (id: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
switchProfile: (id: string) => Promise<Array<{ id: string; name: string; active: boolean; level: string }>>
onLook: (cb: (p: { x: number; y: number }) => void) => () => void
onSkins: (cb: (list: Array<{ id: string; name: string; active: boolean }>) => void) => () => void
getSkins: () => Promise<Array<{ id: string; name: string; active: boolean }>>
importSkin: () => Promise<Array<{ id: string; name: string; active: boolean }>>
switchSkin: (id: string) => Promise<Array<{ id: string; name: string; active: boolean }>>
delWs: (name: string) => Promise<Array<{ name: string; size: number }>>
openWs: () => Promise<void>
closePanel: () => void
bark: (kind: string) => void
showMenu: () => void
chat: (text: string) => Promise<{ ok: boolean; reply: string }>
getLlm: () => Promise<LlmConfig>
setLlm: (patch: Partial<LlmConfig>) => Promise<LlmConfig>
hideMenu: () => void
selectMenu: (tab: string) => void
onBubble: (cb: (b: { text: string; duration: number }) => void) => () => void
onBubbleStreamStart: (cb: () => void) => () => void
onBubbleChunk: (cb: (text: string) => void) => () => void
onBubbleStreamEnd: (cb: (d: { duration: number }) => void) => () => void
onToast: (cb: (text: string) => void) => () => void
onEvent: (cb: (e: { id: string; type: string; until: number } | null) => void) => () => void
onMotion: (cb: (name: string) => void) => () => void
eventResolve: (id: string) => void
getPhotos: () => Promise<PhotoMeta[]>
capturePhoto: () => Promise<PhotoMeta[]>
favPhoto: (id: string) => Promise<PhotoMeta[]>
delPhoto: (id: string) => Promise<PhotoMeta[]>
openPhoto: (id: string) => Promise<void>
onPhotos: (cb: (list: PhotoMeta[]) => void) => () => void
getFiles: () => Promise<FileMeta[]>
delFile: (name: string) => Promise<FileMeta[]>
openFile: (name: string) => Promise<void>
onNavigate: (cb: (nav: { tab: string; arg?: string }) => void) => () => void
setPhotoCat: (id: string, cat: string) => Promise<PhotoMeta[]>
onFiles: (cb: (list: FileMeta[]) => void) => () => void
dropFile: (file: unknown) => void
getKb: () => Promise<Array<{ name: string; chars: number }>>
addKb: (name: string) => Promise<Array<{ name: string; chars: number }>>
delKb: (name: string) => Promise<Array<{ name: string; chars: number }>>
getBubble: () => Promise<{ text: string; duration: number; at: number } | null>
}
declare global {
interface Window {
pet?: PetApi
}
}
export function api(): PetApi | undefined {
return window.pet
}
+75
View File
@@ -0,0 +1,75 @@
import { useEffect, useState } from 'react'
import { api } from '../api'
import './bubble.css'
export default function Bubble(): React.ReactElement | null {
const [text, setText] = useState('')
const [visible, setVisible] = useState(false)
const [streaming, setStreaming] = useState(false)
useEffect(() => {
let timer: number | undefined
function show(t: string, duration: number): void {
setText(t)
setStreaming(false)
setVisible(true)
window.clearTimeout(timer)
timer = window.setTimeout(() => setVisible(false), Math.max(1500, duration - 400))
}
const applyTheme = (c: { theme: string; accent: string }): void => {
document.documentElement.dataset.theme = c.theme
document.documentElement.style.setProperty('--accent', c.accent)
}
const a = api()
void a?.getConfig().then(applyTheme)
const offCfg = a?.onConfig(applyTheme)
// 窗口可能比消息晚就绪,挂载时补取一次当前气泡
void a
?.getBubble()
.then((b) => {
if (!b) return
const left = b.duration - (Date.now() - b.at)
if (left > 500) show(b.text, left)
})
const offB = a?.onBubble(({ text: t, duration }) => show(t, duration))
const offS = a?.onBubbleStreamStart(() => {
setStreaming(true)
setText('…')
setVisible(true)
window.clearTimeout(timer)
})
const offC = a?.onBubbleChunk((t) => {
setText((prev) => (prev === '…' ? t : prev + t))
})
const offE = a?.onBubbleStreamEnd(({ duration }) => {
setStreaming(false)
window.clearTimeout(timer)
timer = window.setTimeout(() => setVisible(false), Math.max(1500, duration - 400))
})
return () => {
offB?.()
offS?.()
offC?.()
offE?.()
offCfg?.()
window.clearTimeout(timer)
}
}, [])
if (!text) return null
return (
<div className={`bubble-wrap ${visible ? 'on' : 'off'}`}>
<div className="bubble-text">
{text}
{streaming && <span className="cursor">▍</span>}
</div>
<div className="bubble-tail" />
</div>
)
}
+67
View File
@@ -0,0 +1,67 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
user-select: none;
}
.bubble-wrap {
position: absolute;
left: 50%;
bottom: 14px;
transform: translateX(-50%) translateY(6px);
max-width: 300px;
display: flex;
flex-direction: column;
align-items: center;
opacity: 0;
transition: opacity 0.18s ease, transform 0.18s ease;
}
.bubble-wrap.on {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
.bubble-text {
background: rgba(16, 20, 30, 0.94);
border: 1px solid #35415a;
border-radius: 12px;
padding: 9px 13px;
color: #eef3ff;
font: 13px/1.55 'Microsoft YaHei', system-ui, sans-serif;
text-align: center;
word-break: break-word;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
}
.bubble-tail {
width: 0;
height: 0;
border-left: 7px solid transparent;
border-right: 7px solid transparent;
border-top: 7px solid rgba(16, 20, 30, 0.94);
}
[data-theme='day'] .bubble-text {
background: #ffffff;
color: #1b2434;
border-color: #cfd8e6;
}
[data-theme='day'] .bubble-tail {
border-top-color: #ffffff;
}
.cursor {
color: var(--accent, #ffd54a);
animation: blink 0.8s steps(1) infinite;
}
@keyframes blink {
50% { opacity: 0; }
}
+156
View File
@@ -0,0 +1,156 @@
import { useEffect, useState } from 'react'
import { api } from '../api'
import { suggestions } from '../../../shared/dialogue'
import type { PetSave } from '../../../shared/petState'
import './chat.css'
const PRESETS_CHEM = ['今天在做什么?', '讲个化学小知识吧', '你饿不饿?', '被夸会脸红吗?', '你喜欢小氯吗?', '带我看看你的记录本']
const PRESETS_NORMAL = ['今天在做什么?', '给我讲个笑话吧', '你饿不饿?', '被夸会脸红吗?', '你最喜欢什么?', '今天心情怎么样?']
export default function ChatBar(): React.ReactElement {
const [text, setText] = useState('')
const [busy, setBusy] = useState(false)
const [open, setOpen] = useState(false)
const [state, setState] = useState<PetSave | null>(null)
const [flavor, setFlavor] = useState<'chemistry' | 'normal'>('chemistry')
useEffect(() => {
const load = (): void => {
void api()
?.getChatPresets()
.then((r) => {
setPresetList(r.presets)
setNextAt(r.nextAt)
})
}
load()
const t = window.setInterval(load, 60_000)
return () => window.clearInterval(t)
}, [flavor])
const [feedback, setFeedback] = useState('')
const [presetList, setPresetList] = useState<
Array<{ id: string; text: string; textNormal: string; kind: string }>
>([])
const [nextAt, setNextAt] = useState(0)
useEffect(() => {
const applyTheme = (c: { theme: string; accent: string; currentSkin?: string; flavorMode?: string }): void => {
document.documentElement.dataset.theme = c.theme
document.documentElement.style.setProperty('--accent', c.accent)
const mode = c.flavorMode || 'auto'
if (mode === 'chemistry') setFlavor('chemistry')
else if (mode === 'normal') setFlavor('normal')
else {
void fetch('pet://skins/' + (c.currentSkin || 'xiaona') + '/skin.json')
.then((r) => (r.ok ? r.json() : null))
.then((m) => setFlavor(m && m.flavor === 'normal' ? 'normal' : 'chemistry'))
.catch(() => setFlavor('chemistry'))
}
}
void api()?.getConfig().then(applyTheme)
const offCfg = api()?.onConfig(applyTheme)
const a = api()
void a?.getState().then(setState)
const offState = a?.onState(setState)
return () => {
offState?.()
offCfg?.()
}
}, [])
const list = state
? suggestions(state, flavor)
: flavor === 'normal'
? PRESETS_NORMAL
: PRESETS_CHEM
async function send(): Promise<void> {
const t = text.trim()
if (!t || busy) return
setText('')
setOpen(false)
setBusy(true)
try {
await api()?.chat(t)
} finally {
setBusy(false)
}
}
return (
<div className="chat-bar">
<button
className="chat-more"
onClick={() => {
const next = !open
setOpen(next)
api()?.setChatExpanded(next)
}}
title="预设话题"
>
▾
</button>
<input
className="chat-input"
value={text}
placeholder={'和' + (state?.name ?? '她') + '说…'}
onChange={(e) => setText(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') void send()
if (e.key === 'Escape') (e.currentTarget as HTMLInputElement).blur()
}}
/>
<button className="chat-send" disabled={busy || !text.trim()} onClick={() => void send()}>
{busy ? '…' : '发送'}
</button>
{feedback && <div className="chat-feedback">{feedback}</div>}
{open && (
<div className="chat-suggest">
{presetList.map((p) => (
<button
key={p.id}
className="chat-suggest-item"
onClick={() => {
setOpen(false)
void api()
?.chatPreset(p.id)
.then((r) => {
if (r?.presets) setPresetList(r.presets)
if (r?.message) {
setFeedback(r.message)
window.setTimeout(() => {
setFeedback('')
api()?.setChatExpanded(false)
}, 2800)
} else {
api()?.setChatExpanded(false)
}
})
}}
>
🎲 {flavor === 'normal' ? p.textNormal : p.text}
</button>
))}
{presetList.length === 0 && (
<div className="chat-suggest-empty">
(这批预设都选完啦,约{' '}
{Math.max(1, Math.round((nextAt - Date.now()) / 60000))} 分钟后刷新)
</div>
)}
{list.map((s) => (
<button
key={s}
className="chat-suggest-item"
onClick={() => {
setText(s)
setOpen(false)
}}
>
{s}
</button>
))}
</div>
)}
</div>
)
}
+153
View File
@@ -0,0 +1,153 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
user-select: none;
}
.chat-bar {
position: absolute;
left: 4px;
right: 4px;
bottom: 4px;
height: 46px;
display: flex;
align-items: center;
gap: 8px;
padding: 6px 8px;
box-sizing: border-box;
background: rgba(13, 16, 23, 0.94);
border: 1px solid #2b3648;
border-radius: 12px;
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.4);
}
.chat-input {
flex: 1;
min-width: 0;
height: 30px;
padding: 0 10px;
border-radius: 8px;
border: 1px solid #222c3f;
background: #10151f;
color: #e8edf7;
font: 13px/1 'Microsoft YaHei', system-ui, sans-serif;
outline: none;
}
.chat-input:focus {
border-color: #3a4b6b;
}
.chat-input::placeholder {
color: #55617a;
}
.chat-send {
height: 30px;
padding: 0 14px;
border-radius: 8px;
border: 1px solid #ffd54a;
background: #ffd54a;
color: #0d1017;
font: 13px/1 'Microsoft YaHei', system-ui, sans-serif;
cursor: pointer;
}
.chat-send:disabled {
opacity: 0.45;
cursor: default;
}
.chat-more {
width: 22px;
height: 30px;
border: 1px solid #222c3f;
border-radius: 8px;
background: #10151f;
color: #7f8ca3;
cursor: pointer;
font-size: 12px;
}
.chat-suggest {
position: absolute;
left: 8px;
right: 8px;
bottom: 58px;
max-height: 184px;
overflow-y: auto;
background: rgba(13, 16, 23, 0.97);
border: 1px solid #2b3648;
border-radius: 10px;
padding: 4px;
display: flex;
flex-direction: column;
gap: 2px;
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.5);
}
.chat-suggest-item {
border: none;
background: transparent;
color: #cfe0ff;
font: 13px/1 'Microsoft YaHei', system-ui, sans-serif;
text-align: left;
padding: 8px 10px;
border-radius: 8px;
cursor: pointer;
}
.chat-suggest-item:hover {
background: #1b2333;
color: #ffd54a;
}
.chat-send { background: var(--accent, #ffd54a); border-color: var(--accent, #ffd54a); }
[data-theme='day'] .chat-bar { background: #f7f9fc; border-color: #cfd8e6; }
[data-theme='day'] .chat-input { background: #fff; color: #1b2434; border-color: #cfd8e6; }
[data-theme='day'] .chat-more { background: #fff; color: #5b6b82; border-color: #cfd8e6; }
[data-theme='day'] .chat-suggest { background: #fff; border-color: #cfd8e6; }
[data-theme='day'] .chat-suggest-item { color: #1b2434; }
.chat-feedback {
position: absolute;
left: 12px;
right: 12px;
bottom: 58px;
padding: 8px 12px;
border-radius: 10px;
background: rgba(30, 44, 66, 0.96);
border: 1px solid #35507a;
color: #9fe3ff;
font: 13px/1.4 'Microsoft YaHei', system-ui, sans-serif;
text-align: center;
box-shadow: 0 6px 18px rgba(0, 0, 0, 0.35);
}
[data-theme='day'] .chat-feedback {
background: #ffffff;
border-color: #b9cde6;
color: #1e6c9e;
}
.chat-suggest-empty {
padding: 10px 12px;
font: 12.5px/1.5 'Microsoft YaHei', system-ui, sans-serif;
color: #7f8ca3;
text-align: center;
}
[data-theme='day'] .chat-suggest-item:hover {
background: #e6eef9;
color: #b8860b;
}
[data-theme='day'] .chat-suggest-empty {
color: #6b7890;
}
+540
View File
@@ -0,0 +1,540 @@
import { useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import { ITEMS, JOBS, expProgress, jobMaxMult, levelOf } from '../../../shared/petState'
import type { PetSave } from '../../../shared/petState'
import { LEVEL_CAP_NORMAL } from '../../../shared/petState'
import { ELEMENT_FLAVOR } from '../../../shared/elementFlavor'
import { ACHIEVEMENTS } from '../../../shared/achievements'
import {
CATEGORY_COLORS,
ELEMENT_GRID_POS,
ELEMENT_CATEGORY_LABEL,
DEFAULT_PERIODIC_STYLE,
ELEMENTS,
elementName,
levelLabelWrapped,
MAX_LEVEL,
periodicCellColor,
PERIODIC_PRESETS,
type PeriodicPreset,
type PeriodicStyle
} from '../../../shared/elements'
import { getCatalogLevels, type CatalogLevels } from '../../../shared/catalog'
import { FLAVOR_LABELS, NORMAL_ITEM_NAMES, NORMAL_JOB_NAMES, type Flavor } from '../../../shared/flavor'
import { Icon } from '../ui/Icon'
import '../panel/panel.css'
import './detail.css'
type Tab = 'stat' | 'summary' | 'birthday' | 'log' | 'levels'
const DEFAULT_NORMAL_DESC: Record<number, string> = {
1: '一切的开始',
2: '第一次自己站起来',
3: '学会了一点点新东西',
4: '还会更好',
5: '小有起色',
6: '手感来了',
7: '慢慢变得可靠',
8: '我们都在长大',
9: '离两位数只差一步',
10: '两位数了!',
15: '渐渐熟练',
20: '半个大人',
25: '能独当一面了',
30: '熟悉的味道',
40: '开始被人依赖',
50: '值得纪念的一半',
75: '走得比想象中远',
100: '三位数!',
150: '还在一路往上',
200: '两百级,故事还在继续',
250: '很久很久以后',
300: '终点?不,是新的起点'
}
export default function Detail(): React.ReactElement {
const [state, setState] = useState<PetSave | null>(null)
const [flavor, setFlavor] = useState<Flavor>('chemistry')
const [theme, setTheme] = useState('night')
const [tab, setTab] = useState<Tab>('stat')
const [query, setQuery] = useState('')
const [birthday, setBirthday] = useState('')
const [levels, setLevels] = useState<CatalogLevels>({})
const [selZ, setSelZ] = useState(1)
const [info, setInfo] = useState('')
const [infoLoading, setInfoLoading] = useState(false)
const [normalSel, setNormalSel] = useState(1)
const [lvMode, setLvMode] = useState<'auto' | 'chemistry' | 'normal'>('auto')
const [periodic, setPeriodic] = useState<PeriodicStyle>(DEFAULT_PERIODIC_STYLE)
const [customPresets, setCustomPresets] = useState<PeriodicPreset[]>([])
const [toast, setToast] = useState('')
useEffect(() => {
const a = api()
api()?.setPanelTitle('统计面板')
void a?.getState().then((s) => {
setState(s)
setBirthday(s.birthday || '')
})
const off = a?.onState((s) => {
setState(s)
setBirthday(s.birthday || '')
})
void a?.getCatalog().then((cat) => {
try {
setLevels(((cat as { levels?: CatalogLevels }).levels ?? {}) as CatalogLevels)
const catPeriodic = (cat as { periodic?: PeriodicStyle & { presets?: PeriodicPreset[] } })
.periodic
setPeriodic((catPeriodic ?? DEFAULT_PERIODIC_STYLE) as PeriodicStyle)
setCustomPresets(catPeriodic?.presets ?? [])
} catch {
setLevels({})
}
})
void a?.getConfig().then((c) => {
setTheme(c.theme)
const mode = c.flavorMode || 'auto'
if (mode === 'chemistry') return setFlavor('chemistry')
if (mode === 'normal') return setFlavor('normal')
void fetch('pet://skins/' + (c.currentSkin || 'xiaona') + '/skin.json')
.then((r) => (r.ok ? r.json() : null))
.then((m) => setFlavor(m && m.flavor === 'normal' ? 'normal' : 'chemistry'))
.catch(() => setFlavor('chemistry'))
})
const offCat = a?.onCatalogChanged(() => window.location.reload())
return () => {
off?.()
offCat?.()
}
}, [])
useEffect(() => {
document.documentElement.dataset.theme = theme
}, [theme])
const itemName = (id: string): string => {
const item = ITEMS.find((i) => i.id === id)
if (!item) return id
return flavor === 'normal'
? (item.nameNormal ?? NORMAL_ITEM_NAMES[id] ?? item.name)
: item.name
}
const jobName = (id: string): string => {
const job = JOBS.find((j) => j.id === id)
if (!job) return id
return flavor === 'normal'
? (job.nameNormal ?? NORMAL_JOB_NAMES[id] ?? job.name)
: job.name
}
const rows = useMemo(() => {
if (!state) return []
const out: Array<{ name: string; count: number; group: string }> = []
for (const item of ITEMS) {
out.push({
name: '购买次数_' + itemName(item.id),
count: state.counters['buy:' + item.id] ?? 0,
group: 'buy'
})
}
for (const item of ITEMS) {
out.push({
name: '使用次数_' + itemName(item.id),
count: state.counters['use:' + item.id] ?? 0,
group: 'use'
})
}
for (const job of JOBS) {
out.push({
name: '完成次数_' + jobName(job.id),
count: state.counters['job:' + job.id] ?? 0,
group: 'job'
})
}
return out
}, [state, flavor])
const filtered = rows.filter((r) => !query || r.name.includes(query))
if (!state) return <div className="detail">加载中…</div>
const level = levelOf(state.exp)
const prog = expProgress(state.exp)
const playH = Math.floor(state.playtimeMs / 3600000)
const playM = Math.floor((state.playtimeMs % 3600000) / 60000)
const unlocked = Object.keys(state.achievements || {}).length
async function saveBirthday(): Promise<void> {
const r = await api()?.setBirthday(birthday)
if (r) {
setToast(r.message)
window.setTimeout(() => setToast(''), 1800)
}
}
return (
<div className="detail">
<header className="detail-head">
<div className="detail-title">面板 · {state.name}</div>
<button className="icon-btn" onClick={() => window.close()} title="关闭">
✕
</button>
</header>
<nav className="detail-tabs">
{([
['stat', '统计面板'],
['summary', '统计总结'],
['birthday', '生日祝福'],
['log', '活动日志'],
['levels', '等级预览']
] as const).map(([id, label]) => (
<button
key={id}
className={'set-tab' + (tab === id ? ' on' : '')}
onClick={() => setTab(id)}
>
{label}
</button>
))}
</nav>
{tab === 'stat' && (
<>
<input
className="text-input"
placeholder="搜索统计"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className="stat-table">
<div className="stat-row stat-head">
<span>名称</span>
<span>数量</span>
</div>
{filtered.map((r) => (
<div className="stat-row" key={r.group + r.name}>
<span>{r.name}</span>
<span className={r.count > 0 ? 'stat-num on' : 'stat-num'}>{r.count}</span>
</div>
))}
{filtered.length === 0 && <div className="empty">没有匹配的统计项</div>}
</div>
</>
)}
{tab === 'summary' && (
<>
<div className="summary">
<div className="summary-cell">
<span className="summary-label">累计在线</span>
<span className="summary-value">
{playH}h {playM}m
</span>
</div>
<div className="summary-cell">
<span className="summary-label">经费</span>
<span className="summary-value">{state.money}¥</span>
</div>
<div className="summary-cell">
<span className="summary-label">等级</span>
<span className="summary-value">
Lv.{level}({prog.cur}/{prog.need})
</span>
</div>
<div className="summary-cell">
<span className="summary-label">完成任务</span>
<span className="summary-value">{state.jobsDone} 次</span>
</div>
<div className="summary-cell">
<span className="summary-label">成就</span>
<span className="summary-value">
{unlocked}/{ACHIEVEMENTS.length}
</span>
</div>
</div>
<div className="summary-grid">
{(Object.keys(FLAVOR_LABELS[flavor]) as Array<keyof typeof FLAVOR_LABELS[typeof flavor]>).map(
(k) => (
<div className="summary-cell" key={k}>
<span className="summary-label">{FLAVOR_LABELS[flavor][k]}</span>
<span className="summary-value">{Math.round(state.stats[k])}</span>
</div>
)
)}
</div>
<div className="section-title" style={{ marginTop: 12 }}>
各任务当前倍率
</div>
<div className="stat-table">
{JOBS.map((j) => {
const locked = level < j.level
const m = jobMaxMult(j.level, level)
return (
<div className="stat-row" key={j.id}>
<span>
{jobName(j.id)}
{locked ? '(需 Lv.' + j.level + ')' : ''}
</span>
<span className={locked ? 'stat-num' : 'stat-num on'}>×{locked ? 0 : m}</span>
</div>
)
})}
</div>
</>
)}
{tab === 'birthday' && (
<>
<div className="birthday-card">
<div className="birthday-title">主人生日</div>
<div className="birthday-date">{state.birthday || '还没有设置'}</div>
<div className="birthday-note">
设置后,到那天她会给你庆祝生日。一个月只能修改一次。
</div>
</div>
<div className="new-profile">
<input
className="text-input"
placeholder="MM-DD,例如 08-15"
value={birthday}
onChange={(e) => setBirthday(e.target.value)}
/>
<button className="mini" onClick={() => void saveBirthday()}>
保存生日
</button>
</div>
{toast && <p className="tips">{toast}</p>}
</>
)}
{tab === 'levels' && (
<>
<div className="periodic-presets">
{!PERIODIC_PRESETS.some(
(ps) =>
ps.scheme === periodic.scheme &&
JSON.stringify(ps.colors) === JSON.stringify(periodic.colors ?? {})
) &&
customPresets.every(
(ps) =>
ps.scheme !== periodic.scheme ||
JSON.stringify(ps.colors) !== JSON.stringify(periodic.colors ?? {})
) && <span className="preset-custom-tag">当前:自定义</span>}
{[...PERIODIC_PRESETS, ...customPresets].map((ps) => (
<button
key={ps.id}
className={
'set-tab' +
(periodic.scheme === ps.scheme &&
JSON.stringify(periodic.colors ?? {}) === JSON.stringify(ps.colors)
? ' on'
: '')
}
onClick={() =>
setPeriodic({ ...periodic, scheme: ps.scheme, colors: { ...ps.colors } })
}
>
{ps.name}
</button>
))}
</div>
<div className="level-mode">
{([
['auto', '跟随当前文本风格'],
['chemistry', '化学(元素周期表)'],
['normal', '普通(纯数字等级)']
] as const).map(([k, label]) => (
<button
key={k}
className={'set-tab' + ((lvMode === k ? ' on' : '') ?? '')}
onClick={() => setLvMode(k)}
>
{label}
</button>
))}
</div>
{(lvMode === 'auto' ? flavor === 'normal' : lvMode === 'normal') ? (
<div className="level-list">
{Array.from({ length: LEVEL_CAP_NORMAL }, (_, i) => i + 1)
.filter((n) => {
const meta = levels.normal?.[String(n)]
const hasUnlock = JOBS.some((j) => j.level === n)
return n === level || n % 10 === 0 || !!meta?.desc || hasUnlock
})
.map((n) => {
const meta = levels.normal?.[String(n)]
const unlocked = JOBS.filter((j) => j.level === n)
return (
<div
className={'level-row' + (n === level ? ' on' : '')}
key={n}
onClick={() => setNormalSel(n)}
>
<div className="level-row-head">
<b className={normalSel === n ? 'level-now' : ''}>Lv.{n}</b>
<Icon value={meta?.icon} />
<span className="level-row-desc">
{meta?.desc ?? DEFAULT_NORMAL_DESC[n] ?? ''}
</span>
</div>
{unlocked.length > 0 && (
<div className="level-row-unlocks">
{unlocked.map((j) => (
<span key={j.id} className="unlock-chip">
{j.icon} {jobName(j.id)}
</span>
))}
</div>
)}
</div>
)
})}
<p className="tips">普通文本的等级上限是 {LEVEL_CAP_NORMAL},当前 Lv.{level}。</p>
</div>
) : (
<>
<div
className="periodic"
style={{
background:
theme === 'day' && (!periodic.bg || periodic.bg === '#0e1420')
? '#f2f6fc'
: periodic.bg
}}
>
{ELEMENTS.map((el) => {
const [row, col] = ELEMENT_GRID_POS[el.z - 1] ?? [1, 1]
return (
<button
key={el.z}
className={
'pt-cell block-' +
el.block +
(selZ === el.z ? ' on' : '') +
(level % MAX_LEVEL === el.z ? ' cur' : '')
}
style={{
gridRow: row,
gridColumn: col,
background: periodicCellColor(el, periodic)
}}
onClick={() => {
setSelZ(el.z)
setInfo('')
}}
title={elementName(el.z)}
>
<span className="pt-z">{el.z}</span>
<span className="pt-sym">{el.symbol}</span>
</button>
)
})}
</div>
<div className="periodic-legend">
{periodic.scheme === 'category'
? (Object.keys(ELEMENT_CATEGORY_LABEL) as Array<keyof typeof ELEMENT_CATEGORY_LABEL>).map((k) => (
<span key={k} className="legend-item">
<i style={{ background: periodic.colors?.[k] ?? CATEGORY_COLORS[k] }} />
{ELEMENT_CATEGORY_LABEL[k]}
</span>
))
: (['s', 'p', 'd', 'f'] as const).map((b) => (
<span key={b} className="legend-item">
<i style={{ background: periodic.colors?.[b] ?? ({s:'#ffd54a',p:'#6fc8ff',d:'#8ef0b0',f:'#cf9bff'} as Record<string,string>)[b] }} />
{b} 区
</span>
))}
</div>
<div className="element-panel">
<div className="element-head">
<b>
{selZ} {elementName(selZ)} {ELEMENTS[selZ - 1].symbol}
</b>
<span className="muted">{ELEMENTS[selZ - 1].configSuper}</span>
<span className="muted">当前 Lv.{level}</span>
<button
className="mini"
onClick={() => {
setInfoLoading(true)
void api()
?.getElementInfo(selZ, elementName(selZ), ELEMENTS[selZ - 1].symbol)
.then((r) => {
setInfo(r.text)
setInfoLoading(false)
})
}}
>
{infoLoading ? '搜索中…' : '联网查元素特征'}
</button>
</div>
<div className="element-desc">
{levels.chemistry?.[String(selZ)]?.desc ?? ELEMENT_FLAVOR[selZ] ?? ''}
</div>
{info && <div className="element-online">🔎 {info}</div>}
<div className="element-unlocks">
{JOBS.filter((j) => j.level === selZ).map((j) => (
<span key={j.id} className="unlock-chip">
{j.icon} {jobName(j.id)}
</span>
))}
</div>
</div>
<div className="level-rows">
{JOBS.reduce<number[]>((acc, j) => (acc.includes(j.level) ? acc : [...acc, j.level]), [])
.sort((a, b) => a - b)
.map((n) => (
<div
className={'level-row' + (n === level ? ' on' : '')}
key={n}
onClick={() => {
setSelZ(((n - 1) % MAX_LEVEL) + 1)
setInfo('')
}}
>
<div className="level-row-head">
<b>
Lv.{n} {levelLabelWrapped(n).symbol}
</b>
<span className="muted">{levelLabelWrapped(n).config}</span>
<span className="level-row-desc">
{levels.chemistry?.[String(n)]?.desc ??
ELEMENT_FLAVOR[((n - 1) % MAX_LEVEL) + 1] ??
''}
</span>
</div>
<div className="level-row-unlocks">
{JOBS.filter((j) => j.level === n).map((j) => (
<span key={j.id} className="unlock-chip">
{j.icon} {jobName(j.id)}
</span>
))}
</div>
</div>
))}
</div>
</>
)}
</>
)}
{tab === 'log' && (
<div className="list">
{(state.log || []).length === 0 && <div className="empty">还没有活动记录</div>}
{(state.log || []).map((line: string, i: number) => (
<div className="row" key={i}>
<div className="row-title">{line}</div>
</div>
))}
</div>
)}
</div>
)
}
+462
View File
@@ -0,0 +1,462 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #0d1017;
overflow: hidden;
}
.detail {
display: flex;
flex-direction: column;
gap: 12px;
height: 100vh;
box-sizing: border-box;
padding: 14px 18px;
background: #0d1017;
color: #e8edf7;
font-family: 'Microsoft YaHei', system-ui, sans-serif;
overflow-y: auto;
}
.detail-head {
display: flex;
align-items: center;
justify-content: space-between;
-webkit-app-region: drag;
}
.detail-head .icon-btn {
-webkit-app-region: no-drag;
}
.detail-title {
font-size: 17px;
font-weight: 600;
}
.summary {
display: grid;
grid-template-columns: repeat(5, 1fr);
gap: 10px;
}
.summary-cell {
background: #131826;
border: 1px solid #1d2637;
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 4px;
}
.summary-label {
font-size: 12px;
color: #8190a8;
}
.summary-value {
font-size: 16px;
font-weight: 600;
color: #ffd54a;
}
.detail-cols {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 14px;
align-items: start;
}
.detail-col {
display: flex;
flex-direction: column;
gap: 8px;
}
.col-title {
font-size: 13px;
color: #b8c4d8;
}
[data-theme='day'] .detail {
background: #eef2f8;
color: #1b2434;
}
[data-theme='day'] .summary-cell {
background: #fff;
border-color: #cfd8e6;
}
[data-theme='day'] .summary-label,
[data-theme='day'] .col-title {
color: #55627a;
}
.detail-tabs {
display: flex;
gap: 4px;
flex-wrap: wrap;
}
.detail-tabs .set-tab {
border: none;
background: transparent;
color: #b8c4d8;
padding: 6px 12px;
border-radius: 10px;
cursor: pointer;
font-size: 13px;
}
.detail-tabs .set-tab.on {
background: #2f9cf0;
color: #fff;
}
.stat-table {
display: flex;
flex-direction: column;
border: 1px solid #1d2637;
border-radius: 10px;
overflow: hidden;
}
.stat-row {
display: grid;
grid-template-columns: 1fr 120px;
padding: 8px 14px;
border-bottom: 1px solid #161d2a;
font-size: 13px;
color: #d5dfef;
}
.stat-row:last-child {
border-bottom: none;
}
.stat-head {
background: #141b28;
color: #8b98ad;
font-size: 12px;
}
.stat-num {
text-align: right;
color: #6b7890;
}
.stat-num.on {
color: #5ad1ff;
font-weight: 600;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 10px;
}
.birthday-card {
border: 1px dashed #2b3648;
border-radius: 14px;
padding: 18px;
text-align: center;
background: radial-gradient(circle at 50% 20%, #1c2537, #111826 70%);
}
.birthday-title {
font-size: 13px;
color: #8b98ad;
}
.birthday-date {
font-size: 28px;
font-weight: 700;
color: #ffd54a;
margin: 8px 0;
}
.birthday-note {
font-size: 12px;
color: #6b7890;
}
[data-theme='day'] .detail-tabs .set-tab {
color: #33415a;
}
[data-theme='day'] .stat-table {
border-color: #cfd8e6;
}
[data-theme='day'] .stat-row {
border-color: #e6ecf5;
color: #1b2434;
}
[data-theme='day'] .stat-head {
background: #f2f6fc;
color: #55627a;
}
[data-theme='day'] .birthday-card {
background: radial-gradient(circle at 50% 20%, #f7faff, #eef3fb 70%);
border-color: #cfd8e6;
}
[data-theme='day'] html,
[data-theme='day'] body,
[data-theme='day'] #root {
background: #eef2f8;
}
[data-theme='day'] .detail-head,
[data-theme='day'] .detail-title {
color: #1b2434;
}
[data-theme='day'] .icon-btn {
color: #55627a;
}
[data-theme='day'] .icon-btn:hover {
color: #1b2434;
}
[data-theme='day'] .summary-value {
color: #1e88c7;
}
[data-theme='day'] .birthday-date {
color: #b8860b;
}
[data-theme='day'] .stat-num.on {
color: #1e88c7;
}
[data-theme='day'] .empty {
color: #6b7890;
}
/* 日间模式:活动日志等列表文字 */
[data-theme='day'] .row {
background: #ffffff;
border-color: #e6ecf5;
}
[data-theme='day'] .row-title {
color: #1b2434;
}
[data-theme='day'] .row-sub {
color: #55627a;
}
[data-theme='day'] .empty {
color: #6b7890;
}
.periodic {
display: grid;
grid-template-columns: repeat(18, 1fr);
grid-auto-rows: 26px;
gap: 2px;
padding: 6px;
background: #0e1420;
border: 1px solid #1d2637;
border-radius: 10px;
}
.pt-cell {
border: none;
border-radius: 3px;
cursor: pointer;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
padding: 0;
color: #0d1017;
line-height: 1;
overflow: hidden;
}
.pt-z {
font-size: 7px;
opacity: 0.75;
}
.pt-sym {
font-size: 10.5px;
font-weight: 700;
}
.pt-cell.on {
outline: 2px solid #ffffff;
z-index: 2;
}
.pt-cell.cur {
box-shadow: 0 0 0 2px #ff5c8a inset;
}
.element-panel {
border: 1px solid #1d2637;
border-radius: 10px;
padding: 10px 12px;
display: flex;
flex-direction: column;
gap: 6px;
}
.element-head {
display: flex;
align-items: center;
gap: 10px;
flex-wrap: wrap;
font-size: 13px;
}
.element-desc {
font-size: 12.5px;
line-height: 1.5;
color: #b8c4d8;
}
.element-unlocks,
.level-row-unlocks {
display: flex;
flex-wrap: wrap;
gap: 6px;
}
.unlock-chip {
font-size: 11.5px;
background: #172033;
border: 1px solid #26334a;
border-radius: 8px;
padding: 2px 8px;
color: #a9b8cf;
}
.level-list,
.level-rows {
display: flex;
flex-direction: column;
gap: 6px;
}
.level-row {
border: 1px solid #1d2637;
border-radius: 10px;
padding: 8px 10px;
display: flex;
flex-direction: column;
gap: 6px;
cursor: pointer;
}
.level-row.on {
border-color: #3a4b6b;
background: #121a29;
}
.level-row-head {
display: flex;
align-items: center;
gap: 10px;
font-size: 13px;
flex-wrap: wrap;
}
.level-row-desc {
font-size: 12px;
color: #8b98ad;
}
.level-now {
color: #5ad1ff;
}
[data-theme='day'] .periodic {
background: #f2f6fc;
border-color: #cfd8e6;
}
[data-theme='day'] .element-panel,
[data-theme='day'] .level-row {
border-color: #dfe6f1;
background: #fff;
}
[data-theme='day'] .element-desc,
[data-theme='day'] .level-row-desc {
color: #55627a;
}
[data-theme='day'] .unlock-chip {
background: #eef3fb;
border-color: #cfd8e6;
color: #33415a;
}
.level-mode {
display: flex;
gap: 4px;
flex-wrap: wrap;
margin-bottom: 4px;
}
.element-online {
font-size: 12px;
line-height: 1.5;
color: #5ad1ff;
background: #101a28;
border: 1px dashed #2a3c58;
border-radius: 8px;
padding: 6px 10px;
}
[data-theme='day'] .element-online {
background: #f2f8ff;
border-color: #b9cde6;
color: #1e6c9e;
}
.periodic-legend {
display: flex;
flex-wrap: wrap;
gap: 10px;
font-size: 11.5px;
color: #8b98ad;
padding: 2px 4px;
}
.legend-item {
display: inline-flex;
align-items: center;
gap: 5px;
}
.legend-item i {
width: 12px;
height: 12px;
border-radius: 3px;
display: inline-block;
}
.periodic-presets {
display: flex;
gap: 4px;
flex-wrap: wrap;
}
+828
View File
@@ -0,0 +1,828 @@
import { useEffect, useMemo, useState } from 'react'
import { api } from '../api'
import { CATEGORY_LABEL, LEVEL_CAP_NORMAL, type Item, type JobDef } from '../../../shared/petState'
import {
CATEGORY_COLORS,
ELEMENT_CATEGORY_LABEL,
DEFAULT_PERIODIC_STYLE,
ELEMENT_GRID_POS,
ELEMENTS,
elementName,
MAX_LEVEL,
periodicCellColor,
PERIODIC_PRESETS,
type PeriodicStyle
} from '../../../shared/elements'
import type { CatalogLevels } from '../../../shared/catalog'
import { ELEMENT_FLAVOR } from '../../../shared/elementFlavor'
import { Icon } from '../ui/Icon'
import '../panel/panel.css'
import './editor.css'
type Tab = 'item' | 'job' | 'level' | 'lyric' | 'ui'
const EMOJI_PRESETS = [
'🍞','🍙','🍱','🍜','🍰','🍗','🥤','🧋','☕','💧',
'🧪','⚗️','🧫','🔬','🧬','🫧','🔥','❄️','⚡','💎',
'🟦','🟪','🔷','🧂','🛢️','🧴','💊','🧽','📄','🔖',
'📏','📗','📘','📙','📕','📚','📖','🧠','📓','🍂',
'💠','🧵','✏️','📝','🎇','🎁','🧩','🏷️','🧹','🗄️',
'🪣','⚙️','🛠️','🎮','📺','🎨','🚶','🙋','🏅','✨'
]
export default function Editor(): React.ReactElement {
const [items, setItems] = useState<Item[]>([])
const [jobs, setJobs] = useState<JobDef[]>([])
const [tab, setTab] = useState<Tab>('item')
const [query, setQuery] = useState('')
const [selId, setSelId] = useState('')
const [draft, setDraft] = useState<Record<string, unknown> | null>(null)
const [toast, setToast] = useState('')
const [theme, setTheme] = useState('night')
const [levelsMeta, setLevelsMeta] = useState<CatalogLevels>({})
const [lvKind, setLvKind] = useState<'chemistry' | 'normal'>('chemistry')
const [lvKey, setLvKey] = useState(1)
const [lvDraft, setLvDraft] = useState<{ desc: string; icon: string }>({ desc: '', icon: '' })
const [periodic, setPeriodic] = useState<PeriodicStyle>(DEFAULT_PERIODIC_STYLE)
const [lyric, setLyric] = useState({
lyricBg: 'rgba(16,20,30,0.55)',
lyricColor: '#ffffff',
lyricOutline: '#000000',
lyricSize: 20
})
const [presetName, setPresetName] = useState('')
const [customDirty, setCustomDirty] = useState(false)
const [tabIcons, setTabIcons] = useState<Record<string, string>>({})
const [uiTab, setUiTab] = useState('feed')
useEffect(() => {
api()?.setPanelTitle('编辑模式')
void api()?.getCatalog().then((c) => {
setItems(c.items as Item[])
setJobs(c.jobs as JobDef[])
setLevelsMeta(((c as { levels?: CatalogLevels }).levels ?? {}) as CatalogLevels)
setPeriodic(
((c as { periodic?: PeriodicStyle }).periodic ?? DEFAULT_PERIODIC_STYLE) as PeriodicStyle
)
})
void api()?.getConfig().then((c) => {
setTheme(c.theme)
setLyric({
lyricBg: c.lyricBg,
lyricColor: c.lyricColor,
lyricOutline: c.lyricOutline,
lyricSize: c.lyricSize
})
setTabIcons(c.tabIcons ?? {})
})
const offCfg = api()?.onConfig((c) => setTheme(c.theme))
return () => offCfg?.()
}, [])
useEffect(() => {
document.documentElement.dataset.theme = theme
}, [theme])
useEffect(() => {
const m = levelsMeta[lvKind]?.[String(lvKey)]
const base = lvKind === 'chemistry' ? (ELEMENT_FLAVOR[lvKey] ?? '') : ''
setLvDraft({ desc: m?.desc ?? base, icon: m?.icon ?? '' })
}, [lvKind, lvKey, levelsMeta])
const list = tab === 'item' ? items : jobs
const filtered = useMemo(
() =>
list.filter((x) => {
if (!query) return true
const n = (x as { name: string }).name
return n.includes(query) || x.id.includes(query)
}),
[list, query]
)
const selected = list.find((x) => x.id === selId)
function loadLevelMeta(): void {
const key = String(lvKey)
const m = levelsMeta[lvKind]?.[key]
setLvDraft({ desc: m?.desc ?? '', icon: m?.icon ?? '' })
}
function pick(id: string): void {
setSelId(id)
const cur = list.find((x) => x.id === id)
setDraft(cur ? ({ ...cur } as Record<string, unknown>) : null)
}
function setField(key: string, value: unknown): void {
setDraft((d) => (d ? { ...d, [key]: value } : d))
}
function save(): void {
if (!draft) return
const id = String(draft.id)
if (tab === 'item') {
setItems((arr) => arr.map((x) => (x.id === id ? (draft as unknown as Item) : x)))
} else {
setJobs((arr) => arr.map((x) => (x.id === id ? (draft as unknown as JobDef) : x)))
}
void persist([...items], [...jobs], tab, [draft])
}
async function persist(
nextItems: Item[],
nextJobs: JobDef[],
which: Tab,
updated: Array<Record<string, unknown>>
): Promise<void> {
// 用 updated 覆盖对应数组中的条目,再保存
const mergedItems = which === 'item'
? nextItems.map((it) => {
const u = updated.find((d) => d.id === it.id)
return u ? (u as unknown as Item) : it
})
: nextItems
const mergedJobs = which === 'job'
? nextJobs.map((j) => {
const u = updated.find((d) => d.id === j.id)
return u ? (u as unknown as JobDef) : j
})
: nextJobs
setItems(mergedItems)
setJobs(mergedJobs)
const r = await api()?.saveCatalog({ items: mergedItems, jobs: mergedJobs })
if (r) {
setToast(r.message)
window.setTimeout(() => setToast(''), 2000)
}
}
function addNew(): void {
const id = 'custom-' + Date.now().toString(36)
if (tab === 'item') {
const it: Item = {
id,
icon: '🧩',
name: '新物品',
nameNormal: '新物品',
category: 'meal',
price: 10,
desc: '简介',
descNormal: '简介',
effects: { satiety: 10 }
}
const next = [...items, it]
setItems(next)
void persist(next, jobs, 'item', [it as unknown as Record<string, unknown>])
setSelId(id)
setDraft(it as unknown as Record<string, unknown>)
} else {
const j: JobDef = {
id,
icon: '🧩',
name: '新活动',
nameNormal: '新活动',
kind: 'work',
minutes: 10,
coin: 20,
exp: 5,
electron: 4,
satiety: 2,
mood: 0,
level: 1,
desc: '简介',
descNormal: '简介'
}
const next = [...jobs, j]
setJobs(next)
void persist(items, next, 'job', [j as unknown as Record<string, unknown>])
setSelId(id)
setDraft(j as unknown as Record<string, unknown>)
}
}
function remove(): void {
if (!draft) return
const id = String(draft.id)
if (tab === 'item') {
const next = items.filter((x) => x.id !== id)
setItems(next)
void persist(next, jobs, 'item', [])
} else {
const next = jobs.filter((x) => x.id !== id)
setJobs(next)
void persist(items, next, 'job', [])
}
setSelId('')
setDraft(null)
}
return (
<div className="editor">
<header className="editor-head">
<div className="editor-title">编辑模式</div>
<div className="editor-actions">
<button className="mini" onClick={addNew}>
+ 添加
</button>
<button className="mini" onClick={remove} disabled={!draft}>
删除
</button>
<button className="mini" onClick={save} disabled={!draft}>
保存
</button>
<button className="icon-btn" onClick={() => window.close()} title="关闭">
✕
</button>
</div>
</header>
<nav className="detail-tabs">
{([
['item', '物品'],
['job', '活动'],
['level', '等级'],
['lyric', '歌词浮窗'],
['ui', '界面']
] as const).map(([id, label]) => (
<button
key={id}
className={'set-tab' + (tab === id ? ' on' : '')}
onClick={() => {
setTab(id)
setSelId('')
setDraft(null)
}}
>
{label}
</button>
))}
</nav>
<div className="editor-body">
<aside className="editor-list" style={tab === 'level' || tab === 'ui' || tab === 'lyric' ? { opacity: 0.35, pointerEvents: 'none' } : undefined}>
<input
className="text-input"
placeholder="搜索"
value={query}
onChange={(e) => setQuery(e.target.value)}
/>
<div className="list">
{filtered.map((x) => (
<button
key={x.id}
className={'row editor-row' + (selId === x.id ? ' on' : '')}
onClick={() => pick(x.id)}
>
<span className="editor-row-icon">{(x as { icon?: string }).icon ?? '·'}</span>
<span className="editor-row-name">{(x as { name: string }).name}</span>
<span className="editor-row-id">{x.id}</span>
</button>
))}
</div>
</aside>
<section className="editor-form">
{tab === 'ui' && (
<>
<div className="field">
<span>底栏按钮</span>
<select
className="text-input"
value={uiTab}
onChange={(e) => setUiTab(e.target.value)}
>
<option value="feed">投喂</option>
<option value="panel">面板</option>
<option value="interact">互动</option>
<option value="shop">商店 / 试剂店</option>
<option value="photos">图库</option>
<option value="settings">设置</option>
</select>
</div>
<div className="field">
<span>当前图标</span>
<div className="icon-picked">
<Icon value={tabIcons[uiTab]?.startsWith('sticker:') ? '🖼️' : tabIcons[uiTab]} className="icon-preview" />
<button className="mini" onClick={() => {
const next = { ...tabIcons }
delete next[uiTab]
setTabIcons(next)
}}>
清除
</button>
<button
className="mini"
onClick={() => {
void api()
?.importIcon()
.then((v) => {
if (v) setTabIcons({ ...tabIcons, [uiTab]: v })
})
}}
>
导入图片
</button>
</div>
</div>
<div className="tips">选一个表情包作为这个按钮的图标:</div>
<div className="sticker-grid">
{[
'1.0.png','2.0.png','3.0.png','4.0.png','5.0.png','6.0.png','7.0.png',
'8.0.png','9.0.png','10.02.png','11.2.png','16.0.png','20.0.png','23.1.png'
].map((name) => (
<button
key={name}
className={'sticker-cell' + (tabIcons[uiTab] === 'sticker:' + name ? ' on' : '')}
onClick={() => setTabIcons({ ...tabIcons, [uiTab]: 'sticker:' + name })}
>
<img src={'pet://stickers/' + encodeURIComponent(name)} alt={name} />
</button>
))}
</div>
<button
className="mini wide"
onClick={() => {
void api()?.setConfig({ tabIcons }).then(() => {
setToast('底栏图标已保存')
window.setTimeout(() => setToast(''), 1600)
})
}}
>
保存底栏图标
</button>
</>
)}
{tab === 'lyric' && (
<>
<div className="field">
<span>浮窗底色</span>
<input
className="text-input"
value={lyric.lyricBg}
onChange={(e) => setLyric({ ...lyric, lyricBg: e.target.value })}
/>
</div>
<div className="field">
<span>文字颜色</span>
<input
type="color"
value={lyric.lyricColor}
onChange={(e) => setLyric({ ...lyric, lyricColor: e.target.value })}
/>
</div>
<div className="field">
<span>描边颜色</span>
<input
type="color"
value={lyric.lyricOutline}
onChange={(e) => setLyric({ ...lyric, lyricOutline: e.target.value })}
/>
</div>
<div className="field">
<span>字号</span>
<input
type="range"
min={14}
max={44}
step={1}
value={lyric.lyricSize}
onChange={(e) => setLyric({ ...lyric, lyricSize: Number(e.target.value) })}
/>
<b className="set-value">{lyric.lyricSize}px</b>
</div>
<button
className="mini wide"
onClick={() => {
void api()?.setConfig(lyric).then(() => {
setToast('歌词样式已保存')
window.setTimeout(() => setToast(''), 1600)
})
}}
>
保存歌词样式
</button>
<p className="tips">底色支持 rgba(半透明);描边是文字外的深色光晕。</p>
</>
)}
{tab === 'level' && (
<>
<div className="field">
<span>文本类型</span>
<select
className="text-input"
value={lvKind}
onChange={(e) => setLvKind(e.target.value as 'chemistry' | 'normal')}
>
<option value="chemistry">化学(1~{MAX_LEVEL})</option>
<option value="normal">普通(1~{LEVEL_CAP_NORMAL})</option>
</select>
</div>
<div className="field">
<span>等级</span>
<input
className="text-input"
type="number"
min={1}
max={lvKind === 'chemistry' ? MAX_LEVEL : LEVEL_CAP_NORMAL}
value={lvKey}
onChange={(e) => setLvKey(Number(e.target.value))}
/>
</div>
<div className="field">
<span>提示</span>
<span className="muted">
{lvKind === 'chemistry' ? elementName(lvKey) : 'Lv.' + lvKey}
</span>
</div>
<div className="field">
<span>描述</span>
<input
className="text-input"
value={lvDraft.desc}
placeholder="这一级解锁时显示的一句话"
onChange={(e) => setLvDraft({ ...lvDraft, desc: e.target.value })}
/>
</div>
<div className="field">
<span>图标</span>
<div className="icon-picked">
<Icon value={lvDraft.icon} className="icon-preview" />
<button
className="mini"
onClick={() => {
void api()
?.importIcon()
.then((v) => {
if (v) setLvDraft({ ...lvDraft, icon: v })
})
}}
>
导入图片
</button>
</div>
</div>
<div className="icon-grid">
{EMOJI_PRESETS.map((e) => (
<button
key={e}
className="emoji-cell"
onClick={() => setLvDraft({ ...lvDraft, icon: e })}
>
{e}
</button>
))}
</div>
<button
className="mini wide"
onClick={() => {
const key = String(lvKey)
const next: CatalogLevels = {
...levelsMeta,
[lvKind]: { ...(levelsMeta[lvKind] ?? {}), [key]: { ...lvDraft } }
}
setLevelsMeta(next)
void api()?.saveCatalog({ items, jobs, levels: next }).then((r) => {
if (r) {
setToast(r.message)
window.setTimeout(() => setToast(''), 1800)
}
})
}}
>
保存这一级的描述
</button>
<p className="tips">等级描述会显示在「详细 → 等级预览」里;化学等级还能用元素名做提示。</p>
<div className="section-title">周期表配色</div>
<div className="field">
<span>配色</span>
<select
className="text-input"
value={
customDirty
? '__custom'
: PERIODIC_PRESETS.find(
(ps) =>
ps.scheme === periodic.scheme &&
JSON.stringify(ps.colors) === JSON.stringify(periodic.colors ?? {})
)?.id ?? '__custom'
}
onChange={(ev) => {
const v = ev.target.value
if (v === '__custom') return
const preset = PERIODIC_PRESETS.find((x) => x.id === v)
if (preset) {
setPeriodic({ ...periodic, scheme: preset.scheme, colors: { ...preset.colors } })
setCustomDirty(false)
}
}}
>
<option value="__custom">自定义{ customDirty ? '(未保存)' : ''}</option>
{PERIODIC_PRESETS.map((ps) => (
<option key={ps.id} value={ps.id}>
{ps.name}
</option>
))}
</select>
</div>
<p className="tips">点下面的格子或图例就能改颜色;改完会变成「自定义」,另存命名后才会保留。</p>
<div className="periodic-editor" style={{ background: periodic.bg ?? '#0e1420' }}>
{ELEMENTS.map((el) => {
const [row, col] = ELEMENT_GRID_POS[el.z - 1] ?? [1, 1]
const category =
periodic.scheme === 'category' ? undefined : el.block
const key = periodic.scheme === 'category' ? undefined : el.block
const colorFor = periodicCellColor(el, periodic)
const colorKey =
periodic.scheme === 'category'
? Object.entries(CATEGORY_COLORS).find(([, v]) => v === colorFor)?.[0] ?? ''
: String(key ?? '')
return (
<label
key={el.z}
className={'ped-cell' + (lvKind === 'chemistry' && lvKey === el.z ? ' on' : '')}
style={{ gridRow: row, gridColumn: col, background: colorFor }}
title={el.z + ' ' + elementName(el.z) + ' ' + el.symbol}
>
<input
type="color"
className="ped-color"
value={colorFor}
onChange={(ev) => {
const nextColors = { ...(periodic.colors ?? {}) }
if (periodic.scheme === 'category' && colorKey) {
nextColors[colorKey] = ev.target.value
} else {
nextColors[String(key ?? '')] = ev.target.value
}
setPeriodic({ ...periodic, colors: nextColors })
setCustomDirty(true)
}}
/>
<span className="ped-z">{el.z}</span>
<span className="ped-sym">{el.symbol}</span>
<span
className="ped-pick"
onClick={(ev) => {
ev.preventDefault()
setLvKind('chemistry')
setLvKey(el.z)
}}
/>
</label>
)
})}
</div>
<div className="periodic-colors">
{(periodic.scheme === 'category'
? (Object.keys(ELEMENT_CATEGORY_LABEL) as Array<keyof typeof ELEMENT_CATEGORY_LABEL>).map(
(k) => ({
key: k as string,
label: ELEMENT_CATEGORY_LABEL[k],
fallback: CATEGORY_COLORS[k]
})
)
: (['s', 'p', 'd', 'f'] as const).map((b) => ({
key: b as string,
label: b + ' 区',
fallback: ({ s: '#ffd54a', p: '#6fc8ff', d: '#8ef0b0', f: '#cf9bff' } as Record<
string,
string
>)[b]
}))
).map((row) => (
<label key={row.key} className="color-row">
<input
type="color"
value={periodic.colors?.[row.key] ?? row.fallback}
onChange={(e) => {
setPeriodic({
...periodic,
colors: { ...(periodic.colors ?? {}), [row.key]: e.target.value }
})
setCustomDirty(true)
}}
/>
<span>{row.label}</span>
</label>
))}
</div>
<div className="field">
<span>底图背景</span>
<input
type="color"
value={periodic.bg ?? '#0e1420'}
onChange={(e) => {
setPeriodic({ ...periodic, bg: e.target.value })
setCustomDirty(true)
}}
/>
</div>
<button
className="mini wide"
onClick={() => {
void api()?.saveCatalog({ items, jobs, levels: levelsMeta, periodic }).then((r) => {
if (r) {
setToast(r.message)
window.setTimeout(() => setToast(''), 1800)
}
})
}}
>
保存当前配色
</button>
</>
)}
{tab !== 'level' && !draft && <div className="empty">从左边选一个条目开始编辑</div>}
{draft && (
<>
<div className="field">
<span>图标</span>
<div className="icon-picked">
<Icon value={String(draft.icon ?? '')} className="icon-preview" />
<button
className="mini"
onClick={() => {
void api()
?.importIcon()
.then((v) => {
if (v) setField('icon', v)
})
}}
>
导入图片
</button>
</div>
</div>
<div className="icon-grid">
{EMOJI_PRESETS.map((e) => (
<button key={e} className="emoji-cell" onClick={() => setField('icon', e)}>
{e}
</button>
))}
</div>
<div className="field">
<span>化学风格名</span>
<input
className="text-input"
value={String(draft.name ?? '')}
onChange={(e) => setField('name', e.target.value)}
/>
</div>
<div className="field">
<span>普通风格名</span>
<input
className="text-input"
value={String(draft.nameNormal ?? '')}
onChange={(e) => setField('nameNormal', e.target.value)}
/>
</div>
<div className="field">
<span>化学简介</span>
<input
className="text-input"
value={String(draft.desc ?? '')}
onChange={(e) => setField('desc', e.target.value)}
/>
</div>
<div className="field">
<span>普通简介</span>
<input
className="text-input"
value={String(draft.descNormal ?? '')}
onChange={(e) => setField('descNormal', e.target.value)}
/>
</div>
{tab === 'item' && (
<>
<div className="field">
<span>价格</span>
<input
className="text-input"
type="number"
value={Number(draft.price ?? 0)}
onChange={(e) => setField('price', Number(e.target.value))}
/>
</div>
<div className="field">
<span>分类</span>
<select
className="text-input"
value={String(draft.category ?? 'meal')}
onChange={(e) => setField('category', e.target.value)}
>
{Object.entries(CATEGORY_LABEL).map(([k, v]) => (
<option key={k} value={k}>
{v}
</option>
))}
</select>
</div>
<div className="field">
<span>经验</span>
<input
className="text-input"
type="number"
value={Number(draft.exp ?? 0)}
onChange={(e) => setField('exp', Number(e.target.value) || undefined)}
/>
</div>
</>
)}
{tab === 'job' && (
<>
<div className="field">
<span>类别</span>
<select
className="text-input"
value={String(draft.kind ?? 'work')}
onChange={(e) => setField('kind', e.target.value)}
>
<option value="work">工作</option>
<option value="study">学习</option>
<option value="play">玩耍</option>
</select>
</div>
<div className="field">
<span>解锁等级</span>
<input
className="text-input"
type="number"
value={Number(draft.level ?? 1)}
onChange={(e) => setField('level', Number(e.target.value))}
/>
</div>
<div className="field">
<span>时长(分钟)</span>
<input
className="text-input"
type="number"
value={Number(draft.minutes ?? 10)}
onChange={(e) => setField('minutes', Number(e.target.value))}
/>
</div>
<div className="field">
<span>金币</span>
<input
className="text-input"
type="number"
value={Number(draft.coin ?? 0)}
onChange={(e) => setField('coin', Number(e.target.value))}
/>
</div>
<div className="field">
<span>经验</span>
<input
className="text-input"
type="number"
value={Number(draft.exp ?? 0)}
onChange={(e) => setField('exp', Number(e.target.value))}
/>
</div>
<div className="field">
<span>饱食消耗</span>
<input
className="text-input"
type="number"
value={Number(draft.satiety ?? 0)}
onChange={(e) => setField('satiety', Number(e.target.value))}
/>
</div>
<div className="field">
<span>电子消耗</span>
<input
className="text-input"
type="number"
value={Number(draft.electron ?? 0)}
onChange={(e) => setField('electron', Number(e.target.value))}
/>
</div>
<div className="field">
<span>心情</span>
<input
className="text-input"
type="number"
value={Number(draft.mood ?? 0)}
onChange={(e) => setField('mood', Number(e.target.value))}
/>
</div>
</>
)}
<p className="tips">保存后主进程立即生效;重新打开面板即可看到新名字。</p>
</>
)}
</section>
</div>
{toast && <div className="toast">{toast}</div>}
</div>
)
}
+360
View File
@@ -0,0 +1,360 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #0d1017;
overflow: hidden;
}
.editor {
display: flex;
flex-direction: column;
gap: 10px;
height: 100vh;
box-sizing: border-box;
padding: 14px 18px;
color: #e8edf7;
font-family: 'Microsoft YaHei', system-ui, sans-serif;
}
.editor-head {
display: flex;
align-items: center;
justify-content: space-between;
-webkit-app-region: drag;
}
.editor-head .mini,
.editor-head .icon-btn {
-webkit-app-region: no-drag;
}
.editor-title {
font-size: 17px;
font-weight: 600;
}
.editor-actions {
display: flex;
gap: 6px;
align-items: center;
}
.editor-body {
display: grid;
grid-template-columns: 260px 1fr;
gap: 14px;
flex: 1;
min-height: 0;
}
.editor-list {
display: flex;
flex-direction: column;
gap: 6px;
min-height: 0;
}
.editor-list .list {
overflow-y: auto;
}
.editor-row {
display: grid;
grid-template-columns: 24px 1fr auto;
gap: 6px;
align-items: center;
background: transparent;
border: 1px solid transparent;
border-radius: 8px;
padding: 6px 8px;
color: inherit;
cursor: pointer;
text-align: left;
font-size: 13px;
}
.editor-row:hover,
.editor-row.on {
background: #1a2333;
border-color: #2b3648;
}
.editor-row-icon {
font-size: 16px;
}
.editor-row-name {
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.editor-row-id {
font-size: 11px;
color: #6b7890;
}
.editor-form {
display: flex;
flex-direction: column;
gap: 8px;
overflow-y: auto;
padding-right: 4px;
}
.editor-form .field {
display: grid;
grid-template-columns: 96px 1fr;
gap: 10px;
align-items: center;
font-size: 13px;
color: #b8c4d8;
}
.editor-form .text-input {
width: 100%;
box-sizing: border-box;
}
[data-theme='day'] .editor {
color: #1b2434;
}
[data-theme='day'] .editor-row:hover,
[data-theme='day'] .editor-row.on {
background: #e6eef9;
border-color: #cfd8e6;
}
[data-theme='day'] .editor-form .field {
color: #33415a;
}
.icon-img {
width: 18px;
height: 18px;
object-fit: contain;
border-radius: 3px;
vertical-align: middle;
}
.icon-picked {
display: flex;
align-items: center;
gap: 10px;
}
.icon-preview {
font-size: 22px;
line-height: 1;
}
.icon-grid {
display: flex;
flex-wrap: wrap;
gap: 4px;
max-height: 120px;
overflow-y: auto;
padding: 6px;
border: 1px solid #1d2637;
border-radius: 10px;
}
.emoji-cell {
width: 30px;
height: 30px;
border: none;
background: transparent;
border-radius: 6px;
cursor: pointer;
font-size: 17px;
line-height: 1;
}
.emoji-cell:hover {
background: #1a2333;
}
[data-theme='day'] .icon-grid {
border-color: #cfd8e6;
}
[data-theme='day'] .emoji-cell:hover {
background: #e6eef9;
}
.periodic-colors {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 6px 12px;
}
.color-row {
display: flex;
align-items: center;
gap: 8px;
font-size: 12.5px;
color: #b8c4d8;
}
.color-row input[type='color'] {
width: 34px;
height: 24px;
padding: 0;
border: 1px solid #2b3648;
border-radius: 6px;
background: transparent;
}
[data-theme='day'] .color-row {
color: #33415a;
}
[data-theme='day'] html,
[data-theme='day'] body,
[data-theme='day'] #root {
background: #eef2f8;
}
[data-theme='day'] .editor {
background: #eef2f8;
color: #1b2434;
}
[data-theme='day'] .editor-row:hover,
[data-theme='day'] .editor-row.on {
background: #e6eef9;
border-color: #cfd8e6;
}
[data-theme='day'] .editor-form .field,
[data-theme='day'] .color-row {
color: #33415a;
}
[data-theme='day'] .editor-row-id {
color: #7a879b;
}
.periodic-editor {
display: grid;
grid-template-columns: repeat(18, 1fr);
grid-auto-rows: 22px;
gap: 2px;
padding: 6px;
border: 1px solid #1d2637;
border-radius: 10px;
}
.ped-cell {
position: relative;
border-radius: 3px;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
cursor: pointer;
overflow: hidden;
color: #0d1017;
line-height: 1;
}
.ped-cell.on {
outline: 2px solid #ffffff;
z-index: 2;
}
.ped-color {
position: absolute;
inset: 0;
opacity: 0;
width: 100%;
height: 100%;
cursor: pointer;
border: none;
padding: 0;
}
.ped-z {
font-size: 6.5px;
opacity: 0.75;
pointer-events: none;
}
.ped-sym {
font-size: 10px;
font-weight: 700;
pointer-events: none;
}
.ped-pick {
position: absolute;
right: 1px;
top: 1px;
width: 8px;
height: 8px;
border-radius: 50%;
background: #0d1017;
opacity: 0.55;
cursor: pointer;
}
.ped-pick:hover {
opacity: 1;
}
.preset-custom-tag {
font-size: 12px;
color: #8b98ad;
padding: 4px 8px;
border: 1px dashed #2b3648;
border-radius: 8px;
}
[data-theme='day'] .periodic-editor {
border-color: #cfd8e6;
}
[data-theme='day'] .preset-custom-tag {
border-color: #cfd8e6;
color: #55627a;
}
.sticker-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 6px;
}
.sticker-cell {
padding: 0;
border: 1px solid #2b3648;
border-radius: 10px;
background: transparent;
cursor: pointer;
overflow: hidden;
aspect-ratio: 1;
}
.sticker-cell img {
width: 100%;
height: 100%;
object-fit: cover;
display: block;
}
.sticker-cell.on {
border-color: #2f9cf0;
box-shadow: 0 0 0 2px #2f9cf0 inset;
}
[data-theme='day'] .sticker-cell {
border-color: #cfd8e6;
}
+62
View File
@@ -0,0 +1,62 @@
import { useEffect, useState } from 'react'
import { api } from '../api'
import './lyric.css'
interface Now {
title?: string
line?: string
playing?: boolean
}
export default function Lyric(): React.ReactElement {
const [now, setNow] = useState<Now>({})
const [style, setStyle] = useState({
bg: 'rgba(16,20,30,0.55)',
color: '#ffffff',
outline: '#000000',
size: 20
})
useEffect(() => {
const a = api()
const applyCfg = (c: {
lyricBg?: string
lyricColor?: string
lyricOutline?: string
lyricSize?: number
}): void => {
setStyle({
bg: c.lyricBg ?? 'rgba(16,20,30,0.55)',
color: c.lyricColor ?? '#ffffff',
outline: c.lyricOutline ?? '#000000',
size: c.lyricSize ?? 20
})
}
void a?.getConfig().then(applyCfg)
const offCfg = a?.onConfig(applyCfg)
const offNow = a?.onMusicNow((p) => setNow(p as Now))
return () => {
offCfg?.()
offNow?.()
}
}, [])
return (
<div className="lyric-root">
<div
className="lyric-box"
style={{
background: style.bg,
color: style.color,
fontSize: style.size,
textShadow: `0 0 4px ${style.outline}, 0 2px 6px ${style.outline}`
}}
>
<span className="lyric-text">{now.line || (now.title ? '♪ ' + now.title : '♪ 本地音乐')}</span>
<button className="lyric-close" onClick={() => window.close()} title="关闭">
✕
</button>
</div>
</div>
)
}
+64
View File
@@ -0,0 +1,64 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent !important;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
}
.lyric-root {
width: 100%;
height: 100%;
display: flex;
align-items: center;
justify-content: center;
-webkit-app-region: drag;
}
.lyric-box {
position: relative;
max-width: 96%;
padding: 10px 30px 10px 18px;
border-radius: 14px;
font-family: 'Microsoft YaHei', system-ui, sans-serif;
font-weight: 600;
line-height: 1.4;
text-align: center;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.lyric-text {
display: inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
}
.lyric-close {
position: absolute;
right: 6px;
top: 4px;
width: 20px;
height: 20px;
border: none;
border-radius: 50%;
background: rgba(0, 0, 0, 0.35);
color: #fff;
font-size: 11px;
line-height: 1;
cursor: pointer;
-webkit-app-region: no-drag;
opacity: 0.65;
}
.lyric-close:hover {
opacity: 1;
}
+70
View File
@@ -0,0 +1,70 @@
import React from 'react'
import { createRoot } from 'react-dom/client'
import App from './App'
import Panel from './panel/Panel'
import Bubble from './bubble/Bubble'
import Menu from './menu/Menu'
import ChatBar from './chat/ChatBar'
import Storage from './storage/Storage'
import Detail from './detail/Detail'
import Editor from './editor/Editor'
import Music from './music/Music'
import Lyric from './lyric/Lyric'
import { applyCatalog } from '../../shared/catalog'
import { ITEMS, JOBS } from '../../shared/petState'
import { mergeCatalog, type ModFile } from '../../shared/mod'
import './style.css'
const view = new URLSearchParams(window.location.search).get('view')
document.body.dataset.view = view ?? 'pet'
function pick(): React.ReactElement {
if (view === 'panel') return <Panel />
if (view === 'bubble') return <Bubble />
if (view === 'menu') return <Menu />
if (view === 'chat') return <ChatBar />
if (view === 'storage') return <Storage />
if (view === 'detail') return <Detail />
if (view === 'editor') return <Editor />
if (view === 'music') return <Music />
if (view === 'lyric') return <Lyric />
return <App />
}
async function boot(): Promise<void> {
try {
const r = await fetch('pet://data/catalog.json')
if (r.ok) applyCatalog(await r.json())
} catch {
/* 没有自定义目录就用内置数据 */
}
// MOD:叠加在 catalog 之后
try {
const mods: string[] = (await window.pet?.getMods?.()) ?? []
let base = {
items: ITEMS.map((x) => ({ ...x })),
jobs: JOBS.map((x) => ({ ...x }))
}
for (const f of mods) {
try {
const res = await fetch('pet://data/mods/' + encodeURIComponent(f))
if (!res.ok) continue
const mod = (await res.json()) as ModFile
base = mergeCatalog(base, mod)
} catch {
/* 单个 mod 失败不影响启动 */
}
}
ITEMS.length = 0
for (const it of base.items) ITEMS.push(it)
JOBS.length = 0
for (const j of base.jobs) JOBS.push(j)
} catch {
/* 忽略 */
}
createRoot(document.getElementById('root')!).render(
<React.StrictMode>{pick()}</React.StrictMode>
)
}
void boot()
+154
View File
@@ -0,0 +1,154 @@
import { useEffect, useState } from 'react'
import { api } from '../api'
import { iconUrl } from '../ui/iconUrl'
import type { PetSave } from '../../../shared/petState'
import './menu.css'
type Cat = 'feed' | 'panel' | 'interact' | 'shop' | 'settings'
interface SubItem {
label: string
tab?: string
arg?: string
action?: 'sleep' | 'storage' | 'editor' | 'music'
}
const CATS: Array<{ id: Cat; label: string }> = [
{ id: 'feed', label: '投喂' },
{ id: 'panel', label: '面板' },
{ id: 'interact', label: '互动' },
{ id: 'shop', label: '试剂店' },
{ id: 'settings', label: '设置' }
]
export default function Menu(): React.ReactElement {
const [cat, setCat] = useState<Cat | null>(null)
const [flavor, setFlavor] = useState<'chemistry' | 'normal'>('chemistry')
const [tabIcons, setTabIcons] = useState<Record<string, string>>({})
const [state, setState] = useState<PetSave | null>(null)
useEffect(() => {
const applyTheme = (c: {
theme: string
accent: string
tabIcons?: Record<string, string>
}): void => {
setTabIcons(c.tabIcons ?? {})
document.documentElement.dataset.theme = c.theme
document.documentElement.style.setProperty('--accent', c.accent)
}
void api()?.getConfig().then((c2) => {
applyTheme(c2)
const skinId = (c2 as { currentSkin?: string }).currentSkin || 'xiaona'
void fetch('pet://skins/' + skinId + '/skin.json')
.then((r) => (r.ok ? r.json() : null))
.then((m) => setFlavor(m && m.flavor === 'normal' ? 'normal' : 'chemistry'))
.catch(() => setFlavor('chemistry'))
})
const offCfg = api()?.onConfig(applyTheme)
const a = api()
void a?.getState().then(setState)
const off = a?.onState(setState)
return () => {
off?.()
offCfg?.()
}
}, [])
const sleeping = !!state?.sleeping
const catIdx = cat ? CATS.findIndex((x) => x.id === cat) : 0
const subLeft = Math.min(264, Math.max(4, 4 + catIdx * 78.4 + 39.2 - 66))
const submenus: Record<Cat, SubItem[]> = {
feed: [
{ label: '吃饭', tab: 'shop', arg: 'meal' },
{ label: '喝石蜡油', tab: 'shop', arg: 'drink' },
{ label: '耗材', tab: 'shop', arg: 'drug' },
{ label: '礼物', tab: 'shop', arg: 'gift' },
{ label: '背包', tab: 'feed' }
],
panel: [
{ label: '状态', tab: 'panel' },
{ label: '详细', tab: 'detail' },
{ label: '任务', tab: 'interact' },
{ label: '资料库', action: 'storage' }
],
interact: [
{ label: sleeping ? '叫醒' : '睡觉', action: 'sleep' },
{ label: '学习', tab: 'interact', arg: 'study' },
{ label: '工作', tab: 'interact', arg: 'work' },
{ label: '玩耍', tab: 'interact', arg: 'play' },
{ label: '听歌', action: 'music' }
],
shop: [{ label: '试剂店', tab: 'shop' }],
settings: [
{ label: '图形', tab: 'settings' },
{ label: 'AI 与人设', tab: 'settings', arg: 'ai' },
{ label: '角色存档', tab: 'settings', arg: 'profile' },
{ label: '角色 · Live2D', tab: 'settings', arg: 'skin' },
{ label: '图库', tab: 'photos' },
{ label: '资料库', action: 'storage' },
{ label: '编辑模式', action: 'editor' }
]
}
function run(item: SubItem): void {
api()?.hideMenu()
if (item.action === 'sleep') {
void api()?.action('sleep')
return
}
if (item.action === 'storage') {
api()?.openStorage()
return
}
if (item.action === 'editor') {
api()?.openEditor()
return
}
if (item.action === 'music') {
api()?.openMusic()
return
}
if (item.tab) api()?.openPanelAt(item.tab, item.arg)
}
return (
<div className="menu-root">
{cat && (
<div className="submenu" style={{ left: subLeft }}>
{submenus[cat].map((item) => (
<button
key={item.label}
className="submenu-item"
onClick={() => run(item)}
onMouseDown={(e) => e.stopPropagation()}
>
{item.label}
</button>
))}
</div>
)}
<div className="menu-bar">
{CATS.map((c) => (
<button
key={c.id}
className={`menu-item ${cat === c.id ? 'on' : ''}`}
onClick={() => {
if (c.id === 'shop') {
run({ label: '试剂店', tab: 'shop' })
return
}
setCat((prev) => (prev === c.id ? null : c.id))
}}
onMouseDown={(e) => e.stopPropagation()}
>
{tabIcons[c.id] && <img className="tab-icon" src={iconUrl(tabIcons[c.id])} alt="" />}
{c.id === 'shop' && flavor === 'normal' ? '商店' : c.label}
</button>
))}
</div>
</div>
)
}
+89
View File
@@ -0,0 +1,89 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
user-select: none;
}
.menu-root {
position: absolute;
inset: 0;
}
.menu-bar {
position: absolute;
left: 4px;
right: 4px;
bottom: 4px;
height: 46px;
display: flex;
align-items: stretch;
gap: 2px;
background: rgba(13, 16, 23, 0.96);
border: 1px solid #2b3648;
border-radius: 12px;
padding: 4px;
box-shadow: 0 8px 22px rgba(0, 0, 0, 0.45);
}
.menu-item {
flex: 1;
border: none;
background: transparent;
color: #9fb0c9;
font: 13px/1 'Microsoft YaHei', system-ui, sans-serif;
border-radius: 8px;
cursor: pointer;
padding: 0;
letter-spacing: 0.5px;
}
.menu-item:hover,
.menu-item.on {
background: #1b2333;
color: #ffd54a;
}
.submenu {
position: absolute;
left: 4px;
bottom: 56px;
width: 132px;
display: flex;
flex-direction: column;
gap: 2px;
background: rgba(13, 16, 23, 0.97);
border: 1px solid #2b3648;
border-radius: 12px;
padding: 4px;
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.5);
}
.submenu-item {
border: none;
background: transparent;
color: #cfe0ff;
font: 13px/1 'Microsoft YaHei', system-ui, sans-serif;
text-align: left;
padding: 9px 12px;
border-radius: 8px;
cursor: pointer;
}
.submenu-item:hover {
background: #1b2333;
color: #ffd54a;
}
[data-theme='day'] .menu-bar,
[data-theme='day'] .submenu { background: #f7f9fc; border-color: #cfd8e6; }
[data-theme='day'] .menu-item { color: #37455c; }
[data-theme='day'] .menu-item:hover,
[data-theme='day'] .menu-item.on { background: #e6edf7; color: #b8860b; }
[data-theme='day'] .submenu-item { color: #1b2434; }
[data-theme='day'] .submenu-item:hover { background: #e6edf7; color: #b8860b; }
+329
View File
@@ -0,0 +1,329 @@
import { useEffect, useMemo, useRef, useState } from 'react'
import { api } from '../api'
import './music.css'
interface Track {
name: string
file: string
}
interface LrcLine {
t: number
text: string
}
function parseLrc(raw: string): LrcLine[] {
const out: LrcLine[] = []
for (const line of raw.split(/\r?\n/)) {
const m = line.match(/\[(\d{1,2}):(\d{2})(?:[.:](\d{1,3}))?\](.*)/)
if (!m) continue
const t = Number(m[1]) * 60 + Number(m[2]) + Number('0.' + (m[3] ?? '0'))
const text = m[4].trim()
if (text) out.push({ t, text })
}
return out.sort((a, b) => a.t - b.t)
}
export default function Music(): React.ReactElement {
const [dir, setDir] = useState('')
const [tracks, setTracks] = useState<Track[]>([])
const [idx, setIdx] = useState(0)
const [playing, setPlaying] = useState(false)
const [loop, setLoop] = useState(false)
const [shuffle, setShuffle] = useState(false)
const [time, setTime] = useState(0)
const [lrc, setLrc] = useState<LrcLine[]>([])
const [theme, setTheme] = useState('night')
const [base, setBase] = useState('')
const [volume, setVolume] = useState(0.8)
const [playlist, setPlaylist] = useState<Track[]>([])
const [myOnly, setMyOnly] = useState(false)
const [collapsed, setCollapsed] = useState<Record<string, boolean>>({})
const audioRef = useRef<HTMLAudioElement | null>(null)
const current = tracks[idx]
const inMyList = (file: string): boolean => playlist.some((t) => t.file === file)
const currentLine = useMemo(() => {
if (lrc.length === 0) return ''
let line = ''
for (const l of lrc) {
if (l.t <= time + 0.15) line = l.text
else break
}
return line
}, [lrc, time])
useEffect(() => {
api()?.setPanelTitle('本地音乐')
void api()?.getConfig().then((c) => setTheme(c.theme))
const offCfg = api()?.onConfig((c) => setTheme(c.theme))
void api()?.getMusicBase().then(setBase)
void api()?.getMusicPlaylist().then(setPlaylist)
void api()
?.listMusic()
.then((d) => {
setDir(d.dir)
setTracks(d.tracks)
})
const offList = api()?.onMusicList((d) => {
setDir(d.dir)
setTracks(d.tracks)
setIdx(0)
})
return () => {
offList?.()
offCfg?.()
}
}, [])
useEffect(() => {
document.documentElement.dataset.theme = theme
}, [theme])
useEffect(() => {
if (audioRef.current) audioRef.current.volume = volume
}, [volume, current?.file])
const groups = useMemo(() => {
const map = new Map<string, Track[]>()
const src = myOnly ? playlist : tracks
for (const t of src) {
const dir = t.file.includes('/') ? t.file.slice(0, t.file.lastIndexOf('/')) : '(根目录)'
const arr = map.get(dir) ?? []
arr.push(t)
map.set(dir, arr)
}
return Array.from(map.entries())
}, [tracks, playlist, myOnly])
// 切歌时加载歌词
useEffect(() => {
if (!current) {
setLrc([])
return
}
void api()
?.getLyric(current.file)
.then((raw) => setLrc(raw ? parseLrc(raw) : []))
.catch(() => setLrc([]))
}, [current?.file])
// 播放状态同步到歌词浮窗
useEffect(() => {
api()?.sendMusicNow({
title: current ? current.name : '',
line: currentLine || (current ? '♪ 纯音乐 / 暂无歌词' : ''),
playing
})
}, [current, currentLine, playing])
function playTrack(i: number): void {
setIdx(i)
setTime(0)
window.setTimeout(() => {
const el = audioRef.current
if (el) {
el.currentTime = 0
void el.play().catch(() => undefined)
}
}, 60)
}
function toggle(): void {
const el = audioRef.current
if (!el || !current) return
if (playing) el.pause()
else void el.play().catch(() => undefined)
}
function next(): void {
if (tracks.length === 0) return
if (shuffle) {
playTrack(Math.floor(Math.random() * tracks.length))
return
}
playTrack((idx + 1) % tracks.length)
}
function prev(): void {
if (tracks.length === 0) return
playTrack((idx - 1 + tracks.length) % tracks.length)
}
return (
<div className="music">
<header className="music-head">
<div className="music-title">
本地音乐 <span className="music-count">共 {tracks.length} 首</span>
</div>
<div className="music-actions">
<button className="mini" onClick={() => void api()?.chooseMusicDir()}>
选择本地文件夹
</button>
<button className="mini" onClick={() => api()?.openLyric()}>
歌词浮窗
</button>
<button className="icon-btn" onClick={() => window.close()} title="关闭">
✕
</button>
</div>
</header>
<div className="music-body">
<section className="music-main">
<div className="music-now">
<div className="music-now-title">{current ? current.name : '还没有选择歌曲'}</div>
<div className="music-now-dir">{dir || '(点右上角选择本地音乐文件夹)'}</div>
<div className="music-lyric">{currentLine || (lrc.length === 0 ? '暂无歌词(可用同名 .lrc 文件)' : '...')}</div>
</div>
<div className="music-controls">
<button className="ctl" onClick={prev} title="上一首">
⏮
</button>
<button className="ctl ctl-main" onClick={toggle} title="播放/暂停">
{playing ? '⏸' : '▶'}
</button>
<button className="ctl" onClick={next} title="下一首">
⏭
</button>
<button
className={'ctl' + (loop ? ' on' : '')}
onClick={() => {
const v = !loop
setLoop(v)
if (audioRef.current) audioRef.current.loop = v
}}
title="循环播放"
>
🔁
</button>
<button
className={'ctl' + (shuffle ? ' on' : '')}
onClick={() => setShuffle(!shuffle)}
title="随机播放"
>
🔀
</button>
</div>
<div className="music-volume">
<span>🔊</span>
<input
type="range"
min={0}
max={1}
step={0.01}
value={volume}
onChange={(e) => setVolume(Number(e.target.value))}
/>
</div>
<div className="music-progress">
<span>{Math.floor(time / 60)}:{String(Math.floor(time % 60)).padStart(2, '0')}</span>
<input
type="range"
min={0}
max={audioRef.current?.duration || 0}
step={0.1}
value={time}
onChange={(e) => {
const v = Number(e.target.value)
setTime(v)
if (audioRef.current) audioRef.current.currentTime = v
}}
/>
<span>
{isFinite(audioRef.current?.duration ?? NaN)
? Math.floor((audioRef.current?.duration ?? 0) / 60) +
':' +
String(Math.floor((audioRef.current?.duration ?? 0) % 60)).padStart(2, '0')
: '--:--'}
</span>
</div>
{current && (
<audio
ref={audioRef}
src={
base
? base + current.file.split('/').map(encodeURIComponent).join('/')
: 'pet://music/' + current.file.split('/').map(encodeURIComponent).join('/')
}
loop={loop}
onPlay={() => setPlaying(true)}
onPause={() => setPlaying(false)}
onTimeUpdate={(e) => setTime((e.target as HTMLAudioElement).currentTime)}
onEnded={() => {
if (!loop) next()
}}
/>
)}
</section>
<aside className="music-list">
<div className="music-list-head">
<span>{myOnly ? '我的列表' : '播放列表'}</span>
<button className="mini" onClick={() => setMyOnly(!myOnly)}>
{myOnly ? '全部歌曲' : '我的列表(' + playlist.length + ')'}
</button>
</div>
<div className="list">
{(myOnly ? playlist : tracks).length === 0 && (
<div className="empty">
{myOnly ? '还没有收藏歌曲(点歌曲右边的 ☆)' : '这个文件夹里没有音频文件'}
</div>
)}
{groups.map(([dirName, list]) => (
<div className="music-group" key={dirName}>
<button
className="music-group-head"
onClick={() =>
setCollapsed((s) => ({ ...s, [dirName]: !s[dirName] }))
}
>
<span className="music-group-arrow">{collapsed[dirName] ? '▸' : '▾'}</span>
{dirName}
<span className="music-group-count">{list.length}</span>
</button>
{!collapsed[dirName] &&
list.map((t) => {
const realIdx = tracks.findIndex((x) => x.file === t.file)
return (
<div
key={t.file}
className={'row music-row' + (realIdx === idx ? ' on' : '')}
>
<span
className="music-row-name"
onClick={() => {
if (realIdx >= 0) playTrack(realIdx)
}}
>
{t.name}
</span>
<button
className="icon-btn small"
title={inMyList(t.file) ? '从我的列表移除' : '加入我的列表'}
onClick={() => {
if (inMyList(t.file)) {
void api()?.removeMusicPlaylist(t.file).then(setPlaylist)
} else {
void api()?.addMusicPlaylist({ name: t.name, file: t.file }).then(setPlaylist)
}
}}
>
{inMyList(t.file) ? '★' : '☆'}
</button>
</div>
)
})}
</div>
))}
</div>
</aside>
</div>
</div>
)
}
+282
View File
@@ -0,0 +1,282 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #0d1017;
overflow: hidden;
}
[data-theme='day'] html,
[data-theme='day'] body,
[data-theme='day'] #root {
background: #eef2f8;
}
[data-theme='day'] .music {
background: #eef2f8;
}
.music {
display: flex;
flex-direction: column;
gap: 10px;
height: 100vh;
box-sizing: border-box;
padding: 14px 18px;
color: #e8edf7;
font-family: 'Microsoft YaHei', system-ui, sans-serif;
}
.music-head {
display: flex;
align-items: center;
justify-content: space-between;
-webkit-app-region: drag;
}
.music-head .mini,
.music-head .icon-btn {
-webkit-app-region: no-drag;
}
.music-title {
font-size: 17px;
font-weight: 600;
}
.music-count {
font-size: 12px;
color: #7c8aa3;
margin-left: 8px;
font-weight: 400;
}
.music-actions {
display: flex;
gap: 8px;
align-items: center;
}
.music-body {
display: grid;
grid-template-columns: 1fr 300px;
gap: 16px;
flex: 1;
min-height: 0;
}
.music-main {
display: flex;
flex-direction: column;
gap: 14px;
align-items: center;
justify-content: center;
border: 1px solid #1d2637;
border-radius: 14px;
padding: 18px;
}
.music-now {
text-align: center;
display: flex;
flex-direction: column;
gap: 6px;
}
.music-now-title {
font-size: 20px;
font-weight: 600;
}
.music-now-dir {
font-size: 11.5px;
color: #6b7890;
word-break: break-all;
}
.music-lyric {
font-size: 15px;
color: #5ad1ff;
min-height: 48px;
max-width: 520px;
}
.music-controls {
display: flex;
gap: 10px;
align-items: center;
}
.ctl {
width: 40px;
height: 40px;
border-radius: 50%;
border: 1px solid #2b3648;
background: #151b28;
color: #cfd9ea;
font-size: 16px;
cursor: pointer;
}
.ctl:hover {
background: #1d2637;
}
.ctl-main {
width: 54px;
height: 54px;
font-size: 20px;
background: #2f9cf0;
border-color: #2f9cf0;
color: #fff;
}
.ctl.on {
border-color: #ffd54a;
color: #ffd54a;
}
.music-progress {
display: flex;
align-items: center;
gap: 10px;
width: 100%;
max-width: 520px;
font-size: 11.5px;
color: #7c8aa3;
}
.music-progress input[type='range'] {
flex: 1;
}
.music-list {
border: 1px solid #1d2637;
border-radius: 14px;
padding: 10px;
display: flex;
flex-direction: column;
gap: 8px;
min-height: 0;
}
.music-list-head {
font-size: 13px;
color: #8b98ad;
}
.music-list .list {
overflow-y: auto;
flex: 1;
}
.music-row {
display: flex;
gap: 8px;
align-items: center;
width: 100%;
background: transparent;
border: none;
border-radius: 8px;
padding: 6px 8px;
color: inherit;
cursor: pointer;
text-align: left;
font-size: 12.5px;
}
.music-row:hover,
.music-row.on {
background: #1a2333;
}
.music-row.on {
color: #5ad1ff;
}
.music-row-idx {
width: 20px;
color: #6b7890;
}
.music-row-name {
flex: 1;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
[data-theme='day'] .music {
color: #1b2434;
}
[data-theme='day'] .music-main,
[data-theme='day'] .music-list {
border-color: #cfd8e6;
background: #fff;
}
[data-theme='day'] .ctl {
background: #eef3fb;
border-color: #cfd8e6;
color: #1b2434;
}
[data-theme='day'] .ctl-main {
background: #2f9cf0;
color: #fff;
}
[data-theme='day'] .music-row:hover,
[data-theme='day'] .music-row.on {
background: #e6eef9;
}
.music-volume {
display: flex;
align-items: center;
gap: 8px;
width: 100%;
max-width: 520px;
font-size: 14px;
}
.music-volume input[type='range'] {
flex: 1;
}
.music-list-head {
display: flex;
align-items: center;
justify-content: space-between;
}
.music-group {
display: flex;
flex-direction: column;
}
.music-group-head {
display: flex;
align-items: center;
gap: 6px;
background: transparent;
border: none;
color: #8b98ad;
font-size: 12px;
text-align: left;
padding: 6px 4px;
cursor: pointer;
}
.music-group-count {
margin-left: auto;
color: #5a6b84;
}
.music-row .music-row-name {
cursor: pointer;
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
+323
View File
@@ -0,0 +1,323 @@
import type { AvatarAdapter, AvatarContext } from '../types'
/**
* Live2D(Cubism 4/5)渲染器。
*
* 注意:Cubism 的「画布尺寸」不等于角色实际占用的范围(顶点可以超出画布),
* 所以这里渲染一帧后读像素,量出角色真实包围盒,再据此缩放与对齐。
*/
export class Live2DAdapter implements AvatarAdapter {
readonly kind = 'live2d'
private pixi: any = null
private app: any = null
private model: any = null
private host: HTMLElement | null = null
private baseSize = { w: 1, h: 1 }
private scaleOverride?: number
private lastLayout = { scale: 0, h: 0 }
constructor(private readonly ctx: AvatarContext) {}
async mount(host: HTMLElement, size: { w: number; h: number }): Promise<void> {
this.host = host
// Cubism Core 必须先于 live2d 插件加载
await loadScriptOnce('pet://lib/live2dcubismcore.min.js')
const PIXI = await import('pixi.js')
const { Live2DModel } = await import('pixi-live2d-display/cubism4')
this.pixi = PIXI
;(Live2DModel as any).registerTicker(PIXI.Ticker)
const app = new PIXI.Application({
width: Math.max(1, size.w),
height: Math.max(1, size.h),
backgroundAlpha: 0,
antialias: true,
resolution: window.devicePixelRatio || 1,
autoDensity: true,
powerPreference: 'high-performance'
})
this.app = app
host.appendChild(app.view as unknown as HTMLCanvasElement)
const url = `${this.ctx.baseUrl}${this.ctx.skin.avatar.entry}`
const model = await Live2DModel.from(url, { autoInteract: false })
this.model = model
const im = model.internalModel
this.baseSize = {
w: Number(im?.originalWidth) || Number(model.width) || 1,
h: Number(im?.originalHeight) || Number(model.height) || 1
}
model.anchor.set(0, 0)
app.stage.addChild(model)
// 先停掉动作再量:动作会整体位移,导致包围盒不准
try {
model.internalModel?.motionManager?.stopAllMotions?.()
} catch {
/* 忽略 */
}
{
const cal0 = this.ctx.skin.avatar.calibration as { v?: number } | undefined
const imported0 = (this.ctx.skin as { flavor?: string }).flavor === 'normal'
if (imported0 && (!cal0 || (cal0.v ?? 0) < 2)) this.ignoreCal = true
}
this.layout()
console.log(
`[live2d] loaded canvas=${this.baseSize.w}x${this.baseSize.h}`
)
// 调试钩子:运行时改缩放
;(window as any).__pet = {
setFit: (s: number, cx = 2151, bottom = 5730) => {
const { width, height } = this.app.renderer.screen
this.model.scale.set(s)
this.model.x = width / 2 - cx * s
this.model.y = height - bottom * s
console.log('[debug] fit ->', s, this.model.x.toFixed(0), this.model.y.toFixed(0))
},
play: (m: string) => this.play(m),
expression: (e: string | null) => this.expression(e)
}
}
private ignoreCal = false
private layout(): void {
if (!this.app || !this.model) return
const { width, height } = this.app.renderer.screen
const factor = this.scaleOverride ?? this.ctx.skin.avatar.scale ?? 1
const cal = this.ctx.skin.avatar.calibration as
| (NonNullable<typeof this.ctx.skin.avatar.calibration> & { v?: number })
| undefined
const imported = (this.ctx.skin as { flavor?: string }).flavor === 'normal'
const calUsable =
!!cal && cal.refHeight > 0 && !this.ignoreCal && (!imported || (cal.v ?? 0) >= 2)
let scale: number
if (calUsable && cal) {
// 有校准值:按窗口高度等比缩放,水平居中、脚底贴底
scale = cal.scale * (height / cal.refHeight)
this.model.scale.set(scale)
this.model.x = width / 2 - cal.centerX * scale
this.model.y = height - cal.bottom * scale
} else {
scale = (height * factor) / (this.baseSize.h || 1)
this.model.scale.set(scale)
this.model.x = width / 2 - (this.baseSize.w / 2) * scale
this.model.y = height - this.baseSize.h * scale
}
if (this.lastLayout.scale !== scale || this.lastLayout.h !== height) {
this.lastLayout = { scale, h: height }
console.log(`[live2d] layout scale=${scale.toFixed(4)} h=${height} w=${width}`)
}
}
resize(width: number, height: number): void {
if (!this.app) return
this.app.renderer.resize(Math.max(1, width), Math.max(1, height))
this.layout()
}
async play(motion: string, _loop = true): Promise<void> {
const group = this.ctx.skin.motions?.[motion] ?? motion
try {
await this.model?.motion(group, 0, 3)
} catch (err) {
console.warn(`[live2d] 动作播放失败:${group}`, err)
}
}
expression(name: string | null): void {
const target = name ? (this.ctx.skin.expressions?.[name] ?? name) : null
try {
if (target) this.model?.expression(target)
else this.model?.expression()
} catch (err) {
console.warn('[live2d] 表情切换失败', err)
}
}
setMood(mood: string): void {
this.expression(mood)
}
private autoCalibrated = false
/** 读一帧像素,返回内容包围盒(CSS 坐标),空则 null */
private readBBox(res: number, w: number, h: number): { x0: number; y0: number; x1: number; y1: number } | null {
const gl = this.app.renderer.gl
const buf = new Uint8Array(w * h * 4)
gl.bindFramebuffer(gl.FRAMEBUFFER, null)
gl.readPixels(0, 0, w, h, gl.RGBA, gl.UNSIGNED_BYTE, buf)
let minX = 1e9
let minY = 1e9
let maxX = -1
let maxY = -1
for (let y = 0; y < h; y++) {
const row = (h - 1 - y) * w * 4
for (let x = 0; x < w; x++) {
if (buf[row + x * 4 + 3] > 16) {
if (x < minX) minX = x
if (x > maxX) maxX = x
if (y < minY) minY = y
if (y > maxY) maxY = y
}
}
}
if (!Number.isFinite(minX) || maxX <= minX || maxY <= minY) return null
return { x0: minX / res, y0: minY / res, x1: maxX / res, y1: maxY / res }
}
/**
* 导入模型自动校准:先把模型缩放到画布放得下(贴边就再缩),
* 量出内容包围盒后换算成校准值并写回 skin.json。
*/
tryAutoCalibrate(): void {
if (this.autoCalibrated) return
try {
const renderer = this.app.renderer
const res = renderer.resolution || 1
const wCss = renderer.screen.width
const hCss = renderer.screen.height
const w = Math.floor(wCss * res)
const h = Math.floor(hCss * res)
try {
this.model.internalModel?.motionManager?.stopAllMotions?.()
} catch {
/* 忽略 */
}
let s = hCss / (this.baseSize.h || 1)
let found: { x0: number; y0: number; x1: number; y1: number } | null = null
for (let attempt = 0; attempt < 7; attempt++) {
this.model.scale.set(s)
this.model.x = wCss / 2 - (this.baseSize.w / 2) * s
this.model.y = hCss - this.baseSize.h * s
renderer.render(this.app.stage)
const bb = this.readBBox(res, w, h)
if (!bb) {
s *= 0.6
continue
}
const clipped = bb.x0 <= 1 || bb.y0 <= 1 || bb.x1 >= wCss - 2 || bb.y1 >= hCss - 1
if (clipped) {
s *= 0.65
continue
}
found = bb
break
}
if (!found) {
this.ignoreCal = true
this.layout()
console.warn('[live2d] 自动校准失败:内容始终贴边,退化为画布适配')
return
}
const s0 = this.model.scale.x || 1
const ly0 = (found.y0 - this.model.y) / s0
const ly1 = (found.y1 - this.model.y) / s0
const cx = ((found.x0 + found.x1) / 2 - this.model.x) / s0
const H = Math.max(1, ly1 - ly0)
const refHeight = 470
const cal = {
scale: (0.92 * refHeight) / H,
centerX: cx,
bottom: ly1,
refHeight,
v: 2
}
this.ctx.skin.avatar.calibration = cal as never
this.ignoreCal = false
this.autoCalibrated = true
this.layout()
console.log('[live2d] 自动校准完成', JSON.stringify(cal))
try {
;(window as unknown as { pet?: { saveCalibration?: (id: string, c: unknown) => void } }).pet?.saveCalibration?.(
this.ctx.skin.id,
cal
)
} catch {
/* 忽略 */
}
} catch (err) {
console.warn('[live2d] 自动校准异常', err)
}
}
lookAt(x: number, y: number): void {
try {
if (x < 0 || y < 0) {
// 复位:直接把 FocusController 归零(正视前方)
const fc = this.model?.internalModel?.focusController
if (fc && typeof fc.focus === 'function') {
fc.focus(0, 0, true)
}
return
}
// 以脸的位置为中心,把目标限制在一个锥形范围内,鼠标很远时也不会锁死
const s = this.model.scale.x || 1
const cx = this.model.x + (this.baseSize.w / 2) * s
const cy = this.model.y + (this.baseSize.h * 0.45) * s
let dx = x - cx
let dy = y - cy
const dist = Math.hypot(dx, dy)
const R = 260
if (dist > R) {
dx = (dx / dist) * R
dy = (dy / dist) * R
}
this.model?.focus(cx + dx, cy + dy)
} catch {
/* 某些模型没有视线参数,忽略 */
}
}
lipSync(value: number): void {
try {
const core = this.model?.internalModel?.coreModel
if (core) core.setParameterValueById('ParamMouthOpenY', Math.max(0, Math.min(1, value)))
} catch {
/* 忽略 */
}
}
destroy(): void {
try {
this.model?.destroy()
} catch {
/* 忽略 */
}
try {
this.app?.destroy(true, { children: true })
} catch {
/* 忽略 */
}
this.model = null
this.app = null
}
}
function loadScriptOnce(src: string): Promise<void> {
const w = window as unknown as { Live2DCubismCore?: unknown }
if (w.Live2DCubismCore) return Promise.resolve()
return new Promise((resolve, reject) => {
const el = document.createElement('script')
el.src = src
el.async = false
el.onload = () => resolve()
el.onerror = () => reject(new Error(`Cubism Core 加载失败:${src}`))
document.head.appendChild(el)
})
}
+107
View File
@@ -0,0 +1,107 @@
import type { AvatarAdapter, AvatarContext } from '../types'
/**
* Q 版序列帧渲染器(预留)。
* 与 Live2D 共用 SkinManifest,只是 avatar.type = "sprite"。
*
* 皮肤示例:
* { "avatar": { "type": "sprite", "entry": "atlas.json" },
* "states": { "idle": { "image": "idle.png", "frames": 4, "fps": 8, "loop": true } } }
*
* atlas.json 也可以直接写在 skin.json 的 states 里,entry 仅作占位。
*/
export class SpriteAdapter implements AvatarAdapter {
readonly kind = 'sprite'
private app: any = null
private pixi: any = null
private sprite: any = null
private textures = new Map<string, any[]>()
private current = ''
private baseScale = 1
constructor(private readonly ctx: AvatarContext) {}
async mount(host: HTMLElement, size: { w: number; h: number }): Promise<void> {
const PIXI = await import('pixi.js')
this.pixi = PIXI
const app = new PIXI.Application({
width: Math.max(1, size.w),
height: Math.max(1, size.h),
backgroundAlpha: 0,
antialias: true,
resolution: window.devicePixelRatio || 1,
autoDensity: true
})
this.app = app
host.appendChild(app.view as unknown as HTMLCanvasElement)
const state = this.ctx.skin.states?.idle
if (!state) throw new Error('sprite 皮肤缺少 idle 状态')
const frames = await this.loadFrames(state.image, state.frames)
const anim = new PIXI.AnimatedSprite(frames)
anim.animationSpeed = state.fps / 60
anim.loop = state.loop !== false
anim.anchor.set(0.5, 1)
this.sprite = anim
app.stage.addChild(anim)
anim.play()
this.layout()
}
private async loadFrames(image: string, frames: number): Promise<any[]> {
const PIXI = this.pixi
const url = `${this.ctx.baseUrl}${image}`
const base = PIXI.Texture.from(url)
await new Promise<void>((resolve, reject) => {
if (base.valid) return resolve()
base.baseTexture.once('loaded', () => resolve())
base.baseTexture.once('error', () => reject(new Error(`贴图加载失败:${url}`)))
})
const w = base.width / frames
const h = base.height
const list: any[] = []
for (let i = 0; i < frames; i++) {
list.push(new PIXI.Texture(base.baseTexture, new PIXI.Rectangle(i * w, 0, w, h)))
}
return list
}
private layout(): void {
if (!this.app || !this.sprite) return
const { width, height } = this.app.renderer.screen
const src = this.sprite.textures[0]
const scale = (height * (this.ctx.skin.avatar.scale ?? 1)) / src.height
this.baseScale = scale
this.sprite.scale.set(scale)
this.sprite.x = width / 2
this.sprite.y = height * (1 + (this.ctx.skin.avatar.offsetY ?? 0))
}
resize(width: number, height: number): void {
this.app?.renderer.resize(Math.max(1, width), Math.max(1, height))
this.layout()
}
async play(motion: string, loop = true): Promise<void> {
const state = this.ctx.skin.states?.[motion]
if (!state || !this.sprite) return
if (this.current === motion) return
this.current = motion
const frames = await this.loadFrames(state.image, state.frames)
this.sprite.textures = frames
this.sprite.animationSpeed = state.fps / 60
this.sprite.loop = loop && state.loop !== false
this.sprite.play()
}
expression(): void {
// Q 版表情通过不同 state 图实现,这里不需要额外处理
}
destroy(): void {
this.app?.destroy(true, { children: true })
this.app = null
this.sprite = null
}
}
+74
View File
@@ -0,0 +1,74 @@
import * as PIXI from 'pixi.js'
import type { AvatarAdapter, AvatarContext } from '../types'
/** 静态图渲染器:一张 PNG 也能当桌宠(兜底方案) */
export class StaticAdapter implements AvatarAdapter {
readonly kind = 'static'
private app: any = null
private sprite: any = null
constructor(private readonly ctx: AvatarContext) {}
async mount(host: HTMLElement, size: { w: number; h: number }): Promise<void> {
const app = new PIXI.Application({
width: Math.max(1, size.w),
height: Math.max(1, size.h),
backgroundAlpha: 0,
antialias: true,
resolution: window.devicePixelRatio || 1,
autoDensity: true
})
this.app = app
host.appendChild(app.view as unknown as HTMLCanvasElement)
const tex = PIXI.Texture.from(`${this.ctx.baseUrl}${this.ctx.skin.avatar.entry}`)
await new Promise<void>((resolve, reject) => {
if (tex.valid) return resolve()
tex.baseTexture.once('loaded', () => resolve())
tex.baseTexture.once('error', () => reject(new Error('静态图加载失败')))
})
const sprite = new PIXI.Sprite(tex)
sprite.anchor.set(0.5, 1)
this.sprite = sprite
app.stage.addChild(sprite)
// 呼吸:轻微上下浮动 + 缩放
let t = 0
app.ticker.add(() => {
t += app.ticker.deltaMS / 1000
const k = 1 + Math.sin(t * 1.6) * 0.012
sprite.scale.y = sprite.scale.x * k
sprite.y = app.renderer.screen.height * (1 + (this.ctx.skin.avatar.offsetY ?? 0)) + Math.sin(t * 1.6) * 1.5
})
this.layout()
}
private layout(): void {
if (!this.app || !this.sprite) return
const { width, height } = this.app.renderer.screen
const scale = (height * (this.ctx.skin.avatar.scale ?? 1)) / (this.sprite.texture.height || 1)
this.sprite.scale.set(scale)
this.sprite.x = width / 2
this.sprite.y = height * (1 + (this.ctx.skin.avatar.offsetY ?? 0))
}
resize(width: number, height: number): void {
this.app?.renderer.resize(Math.max(1, width), Math.max(1, height))
this.layout()
}
async play(): Promise<void> {
/* 静态图无动作 */
}
expression(): void {
/* 静态图无表情 */
}
destroy(): void {
this.app?.destroy(true, { children: true })
this.app = null
}
}
+24
View File
@@ -0,0 +1,24 @@
import type { AvatarAdapter, AvatarContext } from './types'
/**
* 形象工厂:根据皮肤清单里的 avatar.type 选择渲染器。
* 新增形象类型(例如 3D、静态图)只需在这里注册。
*/
export async function createAvatar(ctx: AvatarContext): Promise<AvatarAdapter> {
switch (ctx.skin.avatar.type) {
case 'live2d': {
const { Live2DAdapter } = await import('./adapters/live2d')
return new Live2DAdapter(ctx)
}
case 'sprite': {
const { SpriteAdapter } = await import('./adapters/sprite')
return new SpriteAdapter(ctx)
}
case 'static': {
const { StaticAdapter } = await import('./adapters/static')
return new StaticAdapter(ctx)
}
default:
throw new Error(`未知的形象类型:${(ctx.skin.avatar as { type?: string }).type ?? '?'}`)
}
}
+27
View File
@@ -0,0 +1,27 @@
import type { SkinManifest } from '../../../shared/types'
/** 所有形象渲染器的统一接口:Live2D / Q 版序列帧 / 静态图都实现它 */
export interface AvatarAdapter {
readonly kind: string
mount(host: HTMLElement, size: { w: number; h: number }): Promise<void>
resize(width: number, height: number): void
/** 播放逻辑动作名(idle / tap / nod / shake ...) */
play(motion: string, loop?: boolean): Promise<void>
/** 设定逻辑表情名(happy / sad / angry / surprised / neutral) */
expression(name: string | null): void
/** 预留:口型开合 0~1(实时字幕 / TTS 用) */
lipSync?(value: number): void
/** 预留:情绪驱动(后续接状态条) */
setMood?(mood: string): void
/** Live2D:视线看向画布内某点(CSS 坐标,相对画布左上角) */
lookAt?(x: number, y: number): void
/** 无校准值的导入模型:自动测量包围盒 */
tryAutoCalibrate?(): void
destroy(): void
}
export interface AvatarContext {
skin: SkinManifest
/** 皮肤资源根地址,如 pet://skins/xiaona/ */
baseUrl: string
}
+211
View File
@@ -0,0 +1,211 @@
import { useEffect, useState } from 'react'
import { api } from '../api'
import type { FileMeta, PhotoMeta } from '../../../shared/media'
import '../panel/panel.css'
import './storage.css'
const PHOTO_CATS = ['默认', '表情', '纪念']
const FILE_ICONS: Array<[RegExp, string]> = [
[/\.(png|jpe?g|gif|webp|bmp|ico)$/i, '🖼️'],
[/\.(md|txt|docx?|pdf|pptx?)$/i, '📄'],
[/\.(mp3|wav|ogg|flac)$/i, '🎵'],
[/\.(mp4|mkv|avi|mov)$/i, '🎬'],
[/\.(zip|rar|7z)$/i, '📦'],
[/\.(xlsx?|csv)$/i, '📊'],
[/\.(exe|msi)$/i, '⚙️'],
[/\.(js|ts|py|c|cpp|java|json)$/i, '🧾']
]
function fileIcon(name: string): string {
for (const [re, icon] of FILE_ICONS) if (re.test(name)) return icon
return '📁'
}
export default function Storage(): React.ReactElement {
const [photos, setPhotos] = useState<PhotoMeta[]>([])
const [files, setFiles] = useState<FileMeta[]>([])
const [kbList, setKbList] = useState<Array<{ name: string; chars: number }>>([])
const [cat, setCat] = useState('全部')
const [page, setPage] = useState(0)
const [ws, setWs] = useState<Array<{ name: string; size: number }>>([])
const [petName, setPetName] = useState('')
useEffect(() => {
const a = api()
const applyTheme = (c: { theme: string; accent: string }): void => {
document.documentElement.dataset.theme = c.theme
document.documentElement.style.setProperty('--accent', c.accent)
}
void a?.getConfig().then(applyTheme)
const offCfg = a?.onConfig(applyTheme)
api()?.setPanelTitle('资料库')
void a?.getPhotos().then(setPhotos)
void a?.getFiles().then(setFiles)
void a?.getKb().then(setKbList)
void a?.getWs().then(setWs)
void a?.getState().then((s) => setPetName(s.name))
const offState = a?.onState((s) => setPetName(s.name))
const offP = a?.onPhotos(setPhotos)
const offF = a?.onFiles(setFiles)
return () => {
offP?.()
offF?.()
offCfg?.()
offState?.()
}
}, [])
const filtered = photos.filter((p) => cat === '全部' || p.category === cat)
const PAGE = 12
const pages = Math.max(1, Math.ceil(filtered.length / PAGE))
const cur = Math.min(page, pages - 1)
const shown = filtered.slice(cur * PAGE, cur * PAGE + PAGE)
return (
<div className="storage">
<header className="storage-head">
<div className="storage-title">资料库</div>
<div className="storage-actions">
<button className="mini" onClick={() => void api()?.capturePhoto()}>
拍照
</button>
<button className="mini" onClick={() => void api()?.importPhotos()}>
导入照片
</button>
<button className="icon-btn" onClick={() => window.close()} title="关闭">
✕
</button>
</div>
</header>
<section className="storage-section">
<div className="storage-section-head">
<span>照片图库({photos.length})</span>
<div className="chips">
{['全部', ...PHOTO_CATS].map((c) => (
<button key={c} className={`chip ${cat === c ? 'on' : ''}`} onClick={() => setCat(c)}>
{c}
</button>
))}
</div>
</div>
{filtered.length === 0 && <div className="empty">还没有照片,用上面的「拍照」或「导入照片」吧</div>}
{pages > 1 && (
<div className="pager">
<button className="mini" disabled={cur === 0} onClick={() => setPage(cur - 1)}>
上一页
</button>
<span className="muted">
{cur + 1} / {pages}
</span>
<button className="mini" disabled={cur >= pages - 1} onClick={() => setPage(cur + 1)}>
下一页
</button>
</div>
)}
<div className="photo-grid">
{shown.map((p) => (
<div className="photo-cell" key={p.id}>
<img className="photo-big" src={`pet://photos/${p.file}`} alt="" />
<div className="photo-cell-foot">
<button
className="mini"
title="切换分类"
onClick={() => {
const cur = p.category || '默认'
const next = PHOTO_CATS[(PHOTO_CATS.indexOf(cur) + 1) % PHOTO_CATS.length]
void api()?.setPhotoCat(p.id, next)
}}
>
{p.category || '默认'}
</button>
<button className="mini" onClick={() => void api()?.favPhoto(p.id)}>
{p.favorite ? '★' : '☆'}
</button>
<button className="mini" onClick={() => void api()?.openPhoto(p.id)}>
打开
</button>
<button className="mini" onClick={() => void api()?.delPhoto(p.id)}>
删除
</button>
</div>
</div>
))}
</div>
</section>
<section className="storage-section">
<div className="storage-section-head">
<span>文件袋({files.length})· 把文件拖到{petName || '角色'}身上</span>
</div>
{files.length === 0 && <div className="empty">还没有文件</div>}
<div className="list">
{files.map((f) => (
<div className="row" key={f.name}>
<div className="row-main">
<div className="row-title file-name" onClick={() => void api()?.openFile(f.name)}>
{fileIcon(f.name)} {f.name.replace(/^\d+-/, '')}
</div>
<div className="row-sub">{f.original}</div>
</div>
{/\.(md|txt)$/i.test(f.name) && (
<button className="mini" onClick={() => void api()?.addKb(f.name).then(setKbList)}>
存知识库
</button>
)}
<button className="mini" onClick={() => void api()?.delFile(f.name)}>
删除
</button>
</div>
))}
</div>
</section>
<section className="storage-section">
<div className="storage-section-head">
<span>知识库({kbList.length})· 聊天时自动查阅</span>
</div>
{kbList.length === 0 && (
<div className="empty">把 .md/.txt 拖给{petName || '角色'},在文件袋里点「存知识库」</div>
)}
<div className="list">
{kbList.map((k) => (
<div className="row" key={k.name}>
<div className="row-main">
<div className="row-title">📚 {k.name}</div>
<div className="row-sub">{k.chars} 字</div>
</div>
<button className="mini" onClick={() => void api()?.delKb(k.name).then(setKbList)}>
删除
</button>
</div>
))}
</div>
</section>
<section className="storage-section">
<div className="storage-section-head">
<span>工作区({ws.length})· 对话里说「保存 xxx.md」就会写到这里</span>
<button className="mini" onClick={() => void api()?.openWs()}>
打开文件夹
</button>
</div>
{ws.length === 0 && <div className="empty">还没有文件</div>}
<div className="list">
{ws.map((f) => (
<div className="row" key={f.name}>
<div className="row-main">
<div className="row-title">📄 {f.name}</div>
<div className="row-sub">{f.size} 字节</div>
</div>
<button className="mini" onClick={() => void api()?.delWs(f.name).then(setWs)}>
删除
</button>
</div>
))}
</div>
</section>
</div>
)
}
+119
View File
@@ -0,0 +1,119 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: #0d1017;
overflow: hidden;
}
.storage {
display: flex;
flex-direction: column;
height: 100vh;
box-sizing: border-box;
background: #0d1017;
color: #e8edf7;
font-family: 'Microsoft YaHei', system-ui, sans-serif;
overflow-y: auto;
padding: 14px 18px;
gap: 16px;
}
.storage-head {
display: flex;
align-items: center;
justify-content: space-between;
-webkit-app-region: drag;
}
.storage-head .mini,
.storage-head .icon-btn,
.storage-actions {
-webkit-app-region: no-drag;
}
.storage-title {
font-size: 18px;
font-weight: 600;
}
.storage-actions {
display: flex;
gap: 8px;
align-items: center;
}
.storage-section {
display: flex;
flex-direction: column;
gap: 10px;
}
.storage-section-head {
display: flex;
align-items: center;
justify-content: space-between;
font-size: 13px;
color: #b8c4d8;
}
.photo-grid {
display: grid;
grid-template-columns: repeat(4, 1fr);
gap: 12px;
}
.photo-cell {
background: #131826;
border: 1px solid #1d2637;
border-radius: 12px;
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
}
.photo-big {
width: 100%;
height: 150px;
object-fit: contain;
background: #0b0e14;
border-radius: 8px;
}
.photo-cell-foot {
display: flex;
flex-wrap: wrap;
gap: 4px;
}
.icon-btn {
background: transparent;
border: none;
color: #6f7a8d;
font-size: 16px;
cursor: pointer;
padding: 4px 6px;
}
[data-theme='day'] .storage,
[data-theme='day'] .photo-cell {
background: #eef2f8;
color: #1b2434;
}
[data-theme='day'] .photo-cell {
background: #ffffff;
border-color: #cfd8e6;
}
[data-theme='day'] .photo-big {
background: #dfe6f1;
}
[data-theme='day'] .storage-section-head {
color: #37455c;
}
+69
View File
@@ -0,0 +1,69 @@
html,
body,
#root {
margin: 0;
padding: 0;
width: 100%;
height: 100%;
background: transparent;
overflow: hidden;
-webkit-user-select: none;
user-select: none;
}
#root {
position: relative;
cursor: grab;
}
#root.dragging {
cursor: grabbing;
}
.pet-stage {
position: absolute;
inset: 0;
}
.pet-stage canvas {
display: block;
width: 100%;
height: 100%;
}
.pet-error {
position: absolute;
left: 8px;
right: 8px;
top: 8px;
padding: 10px 12px;
border-radius: 10px;
background: rgba(20, 22, 30, 0.86);
color: #ffd7d7;
font: 12px/1.5 'Microsoft YaHei', system-ui, sans-serif;
white-space: pre-wrap;
word-break: break-all;
}
.pet-hint {
position: absolute;
left: 50%;
bottom: 6px;
transform: translateX(-50%);
color: rgba(255, 255, 255, 0.55);
font: 11px/1.4 'Microsoft YaHei', system-ui, sans-serif;
pointer-events: none;
}
/* 覆盖层窗口(桌宠/底栏/对话条/气泡)永远保持透明,避免主题切换时露出白底 */
body[data-view='pet'],
body[data-view='menu'],
body[data-view='chat'],
body[data-view='bubble'],
body[data-view='pet'] #root,
body[data-view='menu'] #root,
body[data-view='chat'] #root,
body[data-view='bubble'] #root {
background: transparent !important;
}
+70
View File
@@ -0,0 +1,70 @@
.pet-toast {
position: absolute;
left: 50%;
top: 8px;
transform: translateX(-50%);
background: rgba(16, 20, 30, 0.92);
border: 1px solid #35415a;
border-radius: 999px;
padding: 5px 12px;
color: #ffd54a;
font: 12px/1.2 'Microsoft YaHei', system-ui, sans-serif;
white-space: nowrap;
pointer-events: none;
animation: toast-in 0.18s ease;
}
@keyframes toast-in {
from {
opacity: 0;
transform: translateX(-50%) translateY(-4px);
}
to {
opacity: 1;
transform: translateX(-50%) translateY(0);
}
}
[data-theme='day'] .pet-toast {
background: #ffffff;
color: #1b2434;
border-color: #cfd8e6;
}
.water-event {
position: absolute;
left: 50%;
top: 40%;
transform: translateX(-50%);
display: flex;
flex-direction: column;
align-items: center;
gap: 6px;
pointer-events: none;
animation: water-pulse 0.9s ease-in-out infinite;
}
.water-droplet {
font-size: 44px;
filter: drop-shadow(0 4px 10px rgba(0, 60, 130, 0.55));
}
.water-text {
background: rgba(13, 16, 23, 0.92);
border: 1px solid #6fc8ff;
border-radius: 999px;
padding: 6px 14px;
color: #cfe8ff;
font: 13px/1.2 'Microsoft YaHei', system-ui, sans-serif;
}
@keyframes water-pulse {
0%, 100% { transform: translateX(-50%) translateY(0); }
50% { transform: translateX(-50%) translateY(-8px); }
}
[data-theme='day'] .water-text {
background: #ffffff;
color: #1b2434;
border-color: #6fc8ff;
}
+16
View File
@@ -0,0 +1,16 @@
import React from 'react'
/** 图标渲染:普通 emoji 直接显示,img:xxx 显示图片 */
export function Icon({ value, className }: { value?: string; className?: string }): React.ReactElement | null {
if (!value) return null
if (value.startsWith('img:')) {
return (
<img
className={(className ? className + ' ' : '') + 'icon-img'}
src={'pet://data/' + value.slice(4)}
alt=""
/>
)
}
return <span className={className}>{value}</span>
}
+7
View File
@@ -0,0 +1,7 @@
/** 把配置里的图标值转成可访问 URL */
export function iconUrl(value?: string): string {
if (!value) return ''
if (value.startsWith('sticker:')) return 'pet://stickers/' + encodeURIComponent(value.slice(8))
if (value.startsWith('img:')) return 'pet://data/' + value.slice(4).split('/').map(encodeURIComponent).join('/')
return ''
}
+102
View File
@@ -0,0 +1,102 @@
/** 实验事故表(来自《中学化学_试剂器材操作清单》第五节) */
export interface Accident {
id: string
name: string
weight: number
money?: number
mood?: number
oxidation?: number
bark: string
}
export const ACCIDENTS: Accident[] = [
{
id: 'tube-burst',
name: '试管炸裂',
weight: 3,
money: -20,
mood: -8,
bark: '(手忙脚乱)试管炸了……冷凝水回流,要赔玻璃钱 (>﹏<)'
},
{
id: 'spill',
name: '液体喷出',
weight: 3,
money: -10,
mood: -6,
bark: '(擦桌子)液体喷出来了……加热不能超过三分之一呀 (´・ω・`)'
},
{
id: 'label',
name: '标签腐蚀',
weight: 2,
money: -15,
bark: '(看着烂掉的标签)呜,倒液体要标签朝手心才对……整瓶报废了'
},
{
id: 'stopper',
name: '瓶塞污染',
weight: 2,
money: -12,
bark: '(叹气)瓶塞倒放在桌上了,这瓶不能用了……'
},
{
id: 'turbid',
name: '滤液浑浊',
weight: 2,
money: -8,
bark: '(盯着浑浊的滤液)一贴二低三靠……要返工了'
},
{
id: 'miscalc',
name: '浓度算错',
weight: 2,
money: -20,
bark: '(掰手指)算错了……5% 和 50% 差好多,被退货了'
},
{
id: 'acid',
name: '酸溅到身上',
weight: 2,
mood: -10,
bark: '(急急忙忙去冲洗)酸入水!沿器壁、慢慢倒……我记得的!'
},
{
id: 'fire',
name: '酒精灯失火',
weight: 1,
money: -30,
mood: -12,
bark: '(用灯帽盖住)不能吹!不能吹!……吓死我了'
},
{
id: 'overload',
name: '称量超量程',
weight: 1,
money: -25,
bark: '(心虚)天平好像被我压坏了……超载了'
},
{
id: 'smuggle',
name: '药品带出实验室',
weight: 1,
money: -40,
mood: -15,
bark: '(被老师抓个正着)我、我错了……剩余药品不能带走的'
}
]
const CHANCE = 0.12
/** 完成一次任务后掷一次事故骰子,返回 null 表示平安 */
export function rollAccident(): Accident | null {
if (Math.random() > CHANCE) return null
const total = ACCIDENTS.reduce((a, b) => a + b.weight, 0)
let r = Math.random() * total
for (const a of ACCIDENTS) {
r -= a.weight
if (r <= 0) return a
}
return null
}
+92
View File
@@ -0,0 +1,92 @@
import type { PetSave } from './petState'
import { JOBS, levelOf } from './petState'
export interface Achievement {
id: string
title: string
desc: string
icon: string
check: (s: PetSave) => boolean
}
function uses(s: PetSave): number {
return Object.entries(s.counters)
.filter(([k]) => k.startsWith('use:'))
.reduce((a, [, v]) => a + v, 0)
}
function buys(s: PetSave): number {
return Object.entries(s.counters)
.filter(([k]) => k.startsWith('buy:'))
.reduce((a, [, v]) => a + v, 0)
}
function jobCount(s: PetSave, kind?: 'work' | 'study' | 'play'): number {
return Object.entries(s.counters)
.filter(([k]) => k.startsWith('job:'))
.filter(([k]) => {
if (!kind) return true
const job = JOBS.find((j) => j.id === k.slice(4))
return job?.kind === kind
})
.reduce((a, [, v]) => a + v, 0)
}
function hours(s: PetSave): number {
return s.playtimeMs / 3600000
}
export const ACHIEVEMENTS: Achievement[] = [
{ id: 'first_job', title: '第一次打工', desc: '完成 1 次任务', icon: '🧪', check: (s) => s.jobsDone >= 1 },
{ id: 'job10', title: '熟练工', desc: '完成 10 次任务', icon: '⚗️', check: (s) => s.jobsDone >= 10 },
{ id: 'job50', title: '实验狂人', desc: '完成 50 次任务', icon: '🔬', check: (s) => s.jobsDone >= 50 },
{ id: 'job150', title: '苦力', desc: '完成 150 次任务', icon: '💪', check: (s) => s.jobsDone >= 150 },
{ id: 'job400', title: '实验室钉子户', desc: '完成 400 次任务', icon: '🧫', check: (s) => s.jobsDone >= 400 },
{ id: 'money1k', title: '小赚一笔', desc: '经费达到 1000', icon: '💰', check: (s) => s.money >= 1000 },
{ id: 'money5k', title: '家财万贯', desc: '经费达到 5000', icon: '💎', check: (s) => s.money >= 5000 },
{ id: 'money20k', title: '十万元户', desc: '经费达到 20000', icon: '🏦', check: (s) => s.money >= 20000 },
{ id: 'lv5', title: '入轨', desc: '等级达到 5', icon: '🌟', check: (s) => levelOf(s.exp) >= 5 },
{ id: 'lv10', title: '十级选手', desc: '等级达到 10', icon: '✨', check: (s) => levelOf(s.exp) >= 10 },
{ id: 'lv20', title: '渐入佳境', desc: '等级达到 20', icon: '🌱', check: (s) => levelOf(s.exp) >= 20 },
{ id: 'lv40', title: '资深', desc: '等级达到 40', icon: '🌳', check: (s) => levelOf(s.exp) >= 40 },
{ id: 'lv60', title: '大人物', desc: '等级达到 60', icon: '👑', check: (s) => levelOf(s.exp) >= 60 },
{ id: 'lv100', title: '满级(某种意义上)', desc: '等级达到 100', icon: '🏆', check: (s) => levelOf(s.exp) >= 100 },
{ id: 'bond50', title: '关系不错', desc: '亲和度达到 50', icon: '🫶', check: (s) => s.stats.bond >= 50 },
{ id: 'bond100', title: '很亲近', desc: '亲和度达到 100', icon: '💞', check: (s) => s.stats.bond >= 100 },
{ id: 'bond200', title: '才没有很喜欢呢', desc: '亲和度达到 200', icon: '💖', check: (s) => s.stats.bond >= 200 },
{ id: 'bond400', title: '阿姨洗铁路', desc: '亲和度达到 400', icon: '💗', check: (s) => s.stats.bond >= 400 },
{ id: 'use10', title: '会照顾人', desc: '累计使用物品 10 次', icon: '🧃', check: (s) => uses(s) >= 10 },
{ id: 'use50', title: '投喂狂', desc: '累计使用物品 50 次', icon: '🍱', check: (s) => uses(s) >= 50 },
{ id: 'use150', title: '人形投喂机', desc: '累计使用物品 150 次', icon: '🍰', check: (s) => uses(s) >= 150 },
{ id: 'buy10', title: '开始消费', desc: '累计购买 10 次', icon: '🛒', check: (s) => buys(s) >= 10 },
{ id: 'buy50', title: '买买买', desc: '累计购买 50 次', icon: '🛍️', check: (s) => buys(s) >= 50 },
{ id: 'buy200', title: '购物达人', desc: '累计购买 200 次', icon: '🏬', check: (s) => buys(s) >= 200 },
{ id: 'work20', title: '打工魂', desc: '累计工作 20 次', icon: '🧰', check: (s) => jobCount(s, 'work') >= 20 },
{ id: 'work100', title: '老板逼的', desc: '累计工作 100 次', icon: '🏭', check: (s) => jobCount(s, 'work') >= 100 },
{ id: 'study20', title: '你居然真的在学习', desc: '累计学习 20 次', icon: '📚', check: (s) => jobCount(s, 'study') >= 20 },
{ id: 'study100', title: '卷王', desc: '累计学习 100 次', icon: '📖', check: (s) => jobCount(s, 'study') >= 100 },
{ id: 'play20', title: '摸鱼专家', desc: '累计玩耍 20 次', icon: '🎮', check: (s) => jobCount(s, 'play') >= 20 },
{ id: 'play100', title: '摸鱼宗师', desc: '累计玩耍 100 次', icon: '🎲', check: (s) => jobCount(s, 'play') >= 100 },
{ id: 'hour1', title: '一小时了', desc: '陪她在线 1 小时', icon: '⏰', check: (s) => hours(s) >= 1 },
{ id: 'hour10', title: '半天过去了', desc: '陪她在线 10 小时', icon: '🌗', check: (s) => hours(s) >= 10 },
{ id: 'hour50', title: '一起很久了', desc: '陪她在线 50 小时', icon: '🌙', check: (s) => hours(s) >= 50 },
{ id: 'hour200', title: '养猪能手', desc: '陪她在线 200 小时', icon: '🐷', check: (s) => hours(s) >= 200 },
{ id: 'oil20', title: '石蜡油爱好者', desc: '累计使用石蜡油 20 次', icon: '🛢️', check: (s) => (s.counters['use:oil'] ?? 0) >= 20 },
{ id: 'book10', title: '书虫', desc: '累计看书(教材类)10 次', icon: '📗', check: (s) => {
let n = 0
for (const id of ['book1', 'book2', 'book3', 'book4', 'book5', 'book6', 'book7']) {
n += s.counters['use:' + id] ?? 0
}
return n >= 10
} },
{ id: 'gift5', title: '有礼物真方便是吗', desc: '累计送礼物 5 次', icon: '🎁', check: (s) => {
let n = 0
for (const k of Object.keys(s.counters)) {
if (!k.startsWith('use:')) continue
const id = k.slice(4)
if (['notebook', 'bookmark', 'cucrystal', 'chlorine', 'cobaltglass', 'benzene', 'copperwire', 'pencil', 'note', 'flamepin'].includes(id)) {
n += s.counters[k]
}
}
return n >= 5
} },
{ id: 'photo5', title: '摄影师', desc: '拍下 5 张照片', icon: '📷', check: (s) => (s.counters['photo:capture'] ?? 0) >= 5 },
{ id: 'birthday_set', title: '记住你的生日', desc: '设置主人生日', icon: '🎂', check: (s) => s.birthday.length === 5 }
]
+210
View File
@@ -0,0 +1,210 @@
import type { Job, PetSave } from './petState'
/** 台词表:条件驱动,参考 VPet 的 ClickText 结构 */
export interface Bark {
id: string
text: string
/** 数字越大越优先 */
priority: number
/** 同一句的冷却(毫秒) */
cooldown: number
when?: {
maxSatiety?: number
minOxidation?: number
maxElectron?: number
maxMood?: number
minMood?: number
hourFrom?: number
hourTo?: number
working?: boolean
idle?: boolean
}
}
export const BARKS: Bark[] = [
{
id: 'hungry',
text: '(捂着肚子)肚子在叫了……有没有葡萄糖晶体呀 (´・ω・`)',
priority: 80,
cooldown: 5 * 60_000,
when: { maxSatiety: 25 }
},
{
id: 'dry',
text: '(拧开瓶盖)石蜡油见底了,再不喝我会变暗的……',
priority: 75,
cooldown: 6 * 60_000,
when: { maxElectron: 101 }
},
{
id: 'oxidized',
text: '(摸了摸手臂)呜,表面又灰了……要抛光了吗 (´・ω・`)',
priority: 70,
cooldown: 8 * 60_000,
when: { minOxidation: 65 }
},
{
id: 'dizzy',
text: '(晃了晃)有点晕正电荷……我是不是又失电子了 (・_・;)',
priority: 85,
cooldown: 6 * 60_000,
when: { maxElectron: 20 }
},
{
id: 'sad',
text: '(缩在角落)今天不太想说话……',
priority: 60,
cooldown: 10 * 60_000,
when: { maxMood: 25 }
},
{
id: 'working',
text: '(认真地)实验中,请勿打扰……大概',
priority: 50,
cooldown: 3 * 60_000,
when: { working: true }
},
{
id: 'late',
text: '(打哈欠)这么晚了还不睡吗 (。-ω-)zzz',
priority: 40,
cooldown: 20 * 60_000,
when: { hourFrom: 0, hourTo: 5 }
},
{
id: 'morning',
text: '早呀~ 今天也要做实验吗 (๑•̀ㅂ•́)و✧',
priority: 35,
cooldown: 60 * 60_000,
when: { hourFrom: 6, hourTo: 9 }
},
{
id: 'noon',
text: '(趴在桌上)中午了……想吃点固体试剂',
priority: 30,
cooldown: 60 * 60_000,
when: { hourFrom: 11, hourTo: 13 }
},
{
id: 'happy',
text: '(晃着腿)今天状态不错,电子也很听话呢 ( ̄▽ ̄)',
priority: 20,
cooldown: 15 * 60_000,
when: { minMood: 75 }
},
{
id: 'idle1',
text: '(发呆)……啊,我刚才是不是又走神了',
priority: 10,
cooldown: 12 * 60_000,
when: {}
},
{
id: 'idle2',
text: '(小声)我是被写出来的呀……但被摸头还是会开心 (⁄ ⁄•⁄ω⁄•⁄ ⁄)',
priority: 10,
cooldown: 30 * 60_000,
when: {}
},
{
id: 'idle3',
text: '(翻记录本)这个反应式……配平好难',
priority: 9,
cooldown: 20 * 60_000,
when: {}
},
{
id: 'idle4',
text: '(看向窗外)今天的空气湿度有点高,我不太喜欢',
priority: 8,
cooldown: 25 * 60_000,
when: {}
}
]
export const CLICK_BARKS: Bark[] = [
{ id: 'pet1', text: '(被摸头)诶嘿……', priority: 90, cooldown: 15_000 },
{ id: 'pet2', text: '(眯起眼睛)再摸一下也不是不行 ( ̄ω ̄;)', priority: 90, cooldown: 15_000 },
{ id: 'pet3', text: '(脸红)唔……手法很熟练嘛', priority: 90, cooldown: 15_000 },
{ id: 'pet4', text: '(躲了一下)头发会乱的啦~', priority: 90, cooldown: 15_000 }
]
export interface BarkState {
lastSaid: Record<string, number>
}
function inHour(hour: number, from?: number, to?: number): boolean {
if (from === undefined || to === undefined) return true
if (from <= to) return hour >= from && hour <= to
return hour >= from || hour <= to
}
function match(bark: Bark, save: PetSave, job: Job | null, hour: number): boolean {
const w = bark.when ?? {}
const s = save.stats
if (w.maxSatiety !== undefined && s.satiety > w.maxSatiety) return false
if (w.minOxidation !== undefined && s.oxidation < w.minOxidation) return false
if (w.maxElectron !== undefined && s.electron > w.maxElectron) return false
if (w.maxMood !== undefined && s.mood > w.maxMood) return false
if (w.minMood !== undefined && s.mood < w.minMood) return false
if (w.working !== undefined && !!job !== w.working) return false
if (!inHour(hour, w.hourFrom, w.hourTo)) return false
return true
}
/** 挑一条台词;返回 null 表示这次不说话 */
export function pickBark(
save: PetSave,
job: Job | null,
state: BarkState,
now: number
): Bark | null {
const hour = new Date(now).getHours()
const pool = BARKS.filter((b) => match(b, save, job, hour))
const ready = pool.filter((b) => now >= (state.lastSaid[b.id] ?? 0))
if (ready.length === 0) return null
// 优先级高的更容易被选中,但低优先级也有机会
ready.sort((a, b) => b.priority - a.priority)
const top = ready[0]
const candidates = ready.filter((b) => b.priority >= top.priority - 15)
const picked = candidates[Math.floor(Math.random() * candidates.length)]
state.lastSaid[picked.id] = now + picked.cooldown
return picked
}
export function pickClickBark(state: BarkState, now: number): Bark {
const ready = CLICK_BARKS.filter((b) => now >= (state.lastSaid[b.id] ?? 0))
const pool = ready.length > 0 ? ready : CLICK_BARKS
const picked = pool[Math.floor(Math.random() * pool.length)]
state.lastSaid[picked.id] = now + picked.cooldown
return picked
}
/** 普通桌宠风格的冒泡文案(按 id 映射) */
export const NORMAL_BARKS: Record<string, string> = {
hungry: '(摸摸肚子)有点饿啦……有吃的吗 (´・ω・`)',
dry: '(举起空杯子)水喝完了,好渴呀……',
oxidized: '(皱鼻子)身上有点脏了,想洗个澡',
dizzy: '(晃了晃)头有点晕,想休息一下……',
sad: '(抱着膝盖)今天心情不太好……',
working: '(忙忙碌碌)我在认真做事哦',
late: '(打了个哈欠)有点晚了,要不要早点休息?',
morning: '(揉眼睛)早上好呀!',
noon: '(闻了闻)到饭点了,吃饭吃饭!',
happy: '(转了个圈)今天心情超好!',
idle1: '(发呆中)嗯……今天要做什么呢',
idle2: '(看看你)在忙吗?要不要休息一下',
idle3: '(戳戳屏幕)陪我一会儿嘛',
idle4: '(伸懒腰)坐了太久,起来走走吧',
pet1: '(被摸头)诶嘿……',
pet2: '(眯起眼睛)再摸一下也不是不行 ( ̄ω ̄;)',
pet3: '(脸红)唔……摸头的手法很熟练嘛',
pet4: '(躲了一下)头发会乱的啦~'
}
export function barkText(id: string, fallback: string, flavor: string): string {
if (flavor === 'normal') return NORMAL_BARKS[id] ?? fallback
return fallback
}
+58
View File
@@ -0,0 +1,58 @@
import { ITEMS, JOBS, type Item, type JobDef } from './petState'
import { DEFAULT_PERIODIC_STYLE, type PeriodicStyle } from './elements'
export interface LevelMeta {
desc?: string
icon?: string
}
export interface CatalogLevels {
chemistry?: Record<string, LevelMeta>
normal?: Record<string, LevelMeta>
}
export interface CatalogData {
items?: Item[]
jobs?: JobDef[]
levels?: CatalogLevels
periodic?: PeriodicStyle
}
let CURRENT_LEVELS: CatalogLevels = {}
let CURRENT_PERIODIC: PeriodicStyle = { ...DEFAULT_PERIODIC_STYLE }
export function getPeriodicStyle(): PeriodicStyle {
return CURRENT_PERIODIC
}
export function getCatalogLevels(): CatalogLevels {
return CURRENT_LEVELS
}
/** 用编辑过的数据整体替换内置目录(主进程与渲染进程各自调用一次) */
export function applyCatalog(data: CatalogData | null | undefined): boolean {
if (!data) return false
let changed = false
if (data.levels) CURRENT_LEVELS = data.levels
if (data.periodic) CURRENT_PERIODIC = data.periodic
if (Array.isArray(data.items) && data.items.length > 0) {
ITEMS.length = 0
for (const it of data.items) ITEMS.push(it)
changed = true
}
if (Array.isArray(data.jobs) && data.jobs.length > 0) {
JOBS.length = 0
for (const j of data.jobs) JOBS.push(j)
changed = true
}
return changed
}
export function snapshotCatalog(): CatalogData {
return {
items: JSON.parse(JSON.stringify(ITEMS)),
jobs: JSON.parse(JSON.stringify(JOBS)),
levels: JSON.parse(JSON.stringify(CURRENT_LEVELS)),
periodic: JSON.parse(JSON.stringify(CURRENT_PERIODIC))
}
}
+338
View File
@@ -0,0 +1,338 @@
import type { PetSave } from './petState'
/** 对话框里的预设问题,按状态与文本风格轮换 */
export function suggestions(save: PetSave, flavor = 'chemistry'): string[] {
const s = save.stats
const pool: string[] = []
const chemistry = flavor !== 'normal'
if (s.satiety < 40) pool.push('你饿不饿?')
if (chemistry) {
if (s.paraffin < 40) pool.push('石蜡油还够吗?')
if (s.oxidation > 50) pool.push('最近是不是该抛光了?')
} else {
if (s.paraffin < 40) pool.push('要不要喝点水?')
if (s.oxidation > 50) pool.push('是不是该洗个澡了?')
}
if (s.electron < 40) pool.push('要不要睡一会儿?')
if (s.mood < 50) pool.push('今天怎么了?')
if (chemistry) {
pool.push(
'今天在做什么?',
'讲个化学小知识吧',
'你喜欢小氯吗?',
'被夸会脸红吗?',
'你是怎么被画出来的?',
'实验室里最讨厌什么?',
'想吃点什么?',
'带我看看你的记录本'
)
} else {
pool.push(
'今天在做什么?',
'给我讲个笑话吧',
'你最喜欢什么?',
'被夸会脸红吗?',
'你平时喜欢做什么?',
'最讨厌什么?',
'想吃点什么?',
'今天心情怎么样?'
)
}
return pool.slice(0, 6)
}
export interface ChatEffect {
mood?: number
bond?: number
electron?: number
satiety?: number
toast: string
}
/** 特定台词会影响数值 */
const RULES: Array<{ match: RegExp; effect: ChatEffect }> = [
{ match: /(摸头|摸摸|乖|抱抱)/, effect: { mood: 4, bond: 1, toast: '心情 +4 · 亲和 +1' } },
{ match: /(夸|可爱|好看|厉害|喜欢)/, effect: { mood: 3, bond: 1, toast: '心情 +3 · 亲和 +1' } },
{ match: /(吃饭|吃点什么|饿不饿)/, effect: { satiety: 5, toast: '饱食 +5' } },
{ match: /(睡|休息|困)/, effect: { electron: 5, toast: '电子 +5' } },
{ match: /(钠离子|Na\+|失电子)/, effect: { mood: -3, toast: '心情 −3(她不太喜欢这个称呼)' } },
{ match: /(扔进水里|丢水里|加水|遇水)/, effect: { mood: -4, toast: '心情 −4(别真的试)' } },
{ match: /(抛光|擦一擦|变暗)/, effect: { mood: 2, bond: 1, toast: '心情 +2 · 亲和 +1' } }
]
export function chatEffect(text: string): ChatEffect | null {
for (const r of RULES) {
if (r.match.test(text)) return r.effect
}
return null
}
export interface PresetDialogue {
id: string
/** 化学风格文案 */
text: string
/** 普通风格文案 */
textNormal: string
/** buff / debuff / random:随机类按状态决定好坏 */
kind: 'buff' | 'debuff' | 'random'
replyGood: string
replyBad: string
/** 好的时候给什么 */
good: { mood?: number; bond?: number; electron?: number; satiety?: number; paraffin?: number; oxidation?: number; toast: string }
bad: { mood?: number; electron?: number; satiety?: number; bond?: number; toast: string }
}
const CHEM_PRESETS: PresetDialogue[] = [
{
id: 'c1',
text: '给你一瓶新到的石蜡油',
textNormal: '给你一瓶饮料',
kind: 'buff',
replyGood: '(眼睛亮了)哇,是新开的石蜡油!谢谢主人 (๑´ڡ`๑)',
replyBad: '(小心接过)谢谢……不过这瓶好像开封有点久了?',
good: { mood: 5, bond: 2, toast: '心情 +5 · 亲和 +2' },
bad: { mood: 1, toast: '心情 +1' }
},
{
id: 'c2',
text: '今晚要不要一起抛光一下',
textNormal: '今晚要不要一起洗个澡',
kind: 'buff',
replyGood: '(开心地转圈)要要要!抛光完我肯定亮闪闪的 (✿◡‿◡)',
replyBad: '(犹豫)今天有点累了……改天吧',
good: { mood: 6, bond: 2, toast: '心情 +6 · 亲和 +2' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'c3',
text: '帮你剥掉表面的氧化层吧',
textNormal: '帮你擦擦身上的灰',
kind: 'random',
replyGood: '(舒服地眯起眼)嗯——表面又变亮了,谢谢你',
replyBad: '(躲开)诶诶,这个力道不对啦!',
good: { mood: 4, bond: 1, toast: '心情 +4 · 亲和 +1' },
bad: { mood: -3, electron: -2, toast: '心情 −3 · 电子 −2' }
},
{
id: 'c4',
text: '(神秘)我这有颗奇怪的药丸',
textNormal: '(神秘)我这儿有颗奇怪的糖果',
kind: 'random',
replyGood: '(毫不犹豫吞下)……嗯?感觉电子都变活泼了!再给我一颗呀',
replyBad: '(吞下后脸皱成一团)呜……这是什么反应啊,有点上头……',
good: { electron: 8, mood: 4, toast: '电子 +8 · 心情 +4' },
bad: { electron: -6, mood: -4, toast: '电子 −6 · 心情 −4' }
},
{
id: 'c5',
text: '今天要不要翘掉实验去玩',
textNormal: '今天要不要出去玩',
kind: 'buff',
replyGood: '(捂住嘴)真的吗?那……那就玩一会儿!',
replyBad: '(摇头)不行不行,今天的任务还没做完呢',
good: { mood: 8, bond: 1, toast: '心情 +8 · 亲和 +1' },
bad: { mood: -1, bond: 1, toast: '心情 −1 · 亲和 +1' }
},
{
id: 'c6',
text: '有人看见你偷喝冷凝水了',
textNormal: '有人看见你偷吃零食了',
kind: 'debuff',
replyGood: '(支支吾吾)才、才没有!那是实验记录啦!',
replyBad: '(脸红到耳根)呜……被发现了,好丢脸……',
good: { mood: -2, bond: 1, toast: '心情 −2 · 亲和 +1' },
bad: { mood: -5, toast: '心情 −5' }
},
{
id: 'c7',
text: '给你看点有趣的焰色反应',
textNormal: '给你看点有趣的烟花',
kind: 'buff',
replyGood: '(兴奋地拍手)哇——是钠的黄!好看好看!',
replyBad: '(被吓了一跳)呜,太亮了……眼睛有点花',
good: { mood: 7, bond: 1, toast: '心情 +7 · 亲和 +1' },
bad: { mood: -1, electron: -2, toast: '心情 −1 · 电子 −2' }
},
{
id: 'c8',
text: '要一起看电子排布图吗',
textNormal: '要一起看会儿书吗',
kind: 'buff',
replyGood: '(凑过来)好呀!我最近在背能级顺序哦',
replyBad: '(打了个哈欠)唔……一看书就想睡',
good: { bond: 2, mood: 3, toast: '亲和 +2 · 心情 +3' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'c9',
text: '摸了摸你的头',
textNormal: '摸了摸你的头',
kind: 'buff',
replyGood: '(眯起眼睛)唔……手法越来越熟练了嘛 (๑•̀ㅂ•́)و✧',
replyBad: '(别过头)头发会乱的啦……',
good: { mood: 4, bond: 2, toast: '心情 +4 · 亲和 +2' },
bad: { mood: -1, toast: '心情 −1' }
},
{
id: 'c10',
text: '给你递了块抛光砂纸',
textNormal: '给你递了块湿巾',
kind: 'buff',
replyGood: '(接过来)谢谢!这个刚好能擦掉表层氧化膜~',
replyBad: '(看了看)这个好像太粗了,会把我磨花的……',
good: { mood: 3, bond: 1, toast: '心情 +3 · 亲和 +1' },
bad: { electron: -2, mood: -2, toast: '精力 −2 · 心情 −2' }
},
{
id: 'c11',
text: '听说你今天实验做得很好',
textNormal: '听说你今天做得很好',
kind: 'buff',
replyGood: '(耳朵发红)诶、被夸了……嘿嘿',
replyBad: '(低头)其实有个步骤我搞错了……',
good: { mood: 6, bond: 2, toast: '心情 +6 · 亲和 +2' },
bad: { mood: -3, toast: '心情 −3' }
},
{
id: 'c12',
text: '(神秘)发现一瓶不明溶液',
textNormal: '(神秘)发现一瓶不明饮料',
kind: 'random',
replyGood: '(小心尝了一口)……哇,电子好像活跃起来了!',
replyBad: '(表情凝固)呜……这反应不对劲,胃里在冒泡……',
good: { electron: 7, mood: 3, toast: '精力 +7 · 心情 +3' },
bad: { electron: -5, mood: -5, satiety: -3, toast: '精力 −5 · 心情 −5 · 饱食 −3' }
}
]
const NORMAL_PRESETS: PresetDialogue[] = [
{
id: 'n1',
text: '给你带了一份好吃的',
textNormal: '给你带了一份好吃的',
kind: 'buff',
replyGood: '(眼睛发亮)哇!谢谢你!我开动啦 (๑´ڡ`๑)',
replyBad: '(接过)谢谢……不过我已经吃过啦',
good: { satiety: 6, mood: 4, toast: '饱食 +6 · 心情 +4' },
bad: { mood: 1, toast: '心情 +1' }
},
{
id: 'n2',
text: '摸了你的头',
textNormal: '摸了摸你的头',
kind: 'buff',
replyGood: '(眯起眼睛)嘿嘿……再摸一下嘛',
replyBad: '(躲了一下)头发会乱的啦',
good: { mood: 5, bond: 2, toast: '心情 +5 · 亲和 +2' },
bad: { mood: -1, toast: '心情 −1' }
},
{
id: 'n3',
text: '陪你玩一会儿吧',
textNormal: '陪你玩一会儿吧',
kind: 'buff',
replyGood: '(跳起来)好耶!玩什么玩什么?',
replyBad: '(有点累)今天先不玩啦,想歇一会儿',
good: { mood: 7, bond: 1, toast: '心情 +7 · 亲和 +1' },
bad: { mood: -2, electron: -1, toast: '心情 −2 · 精力 −1' }
},
{
id: 'n4',
text: '发现了一颗奇怪的糖果',
textNormal: '发现了一颗奇怪的糖果',
kind: 'random',
replyGood: '(毫不犹豫吃掉)嗯!甜甜的,好开心!还有吗?',
replyBad: '(吃完表情扭曲)呜……这是什么味道,好怪啊……',
good: { mood: 6, electron: 5, toast: '心情 +6 · 精力 +5' },
bad: { mood: -5, electron: -3, toast: '心情 −5 · 精力 −3' }
},
{
id: 'n5',
text: '听说你今天很努力',
textNormal: '听说你今天很努力',
kind: 'buff',
replyGood: '(不好意思地笑)被发现了……嘿嘿',
replyBad: '(低下头)其实今天有点摸鱼……',
good: { mood: 5, bond: 2, toast: '心情 +5 · 亲和 +2' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'n6',
text: '有人看见你偷偷睡觉',
textNormal: '有人看见你偷偷睡觉',
kind: 'debuff',
replyGood: '(辩解)那叫闭目养神!',
replyBad: '(脸红)呜……被发现了',
good: { mood: -1, bond: 1, toast: '心情 −1 · 亲和 +1' },
bad: { mood: -4, toast: '心情 −4' }
},
{
id: 'n7',
text: '一起去晒太阳吧',
textNormal: '一起去晒太阳吧',
kind: 'buff',
replyGood: '(伸个懒腰)好呀,暖洋洋的最舒服了',
replyBad: '(缩了缩)今天有点热……下次吧',
good: { mood: 6, electron: 3, toast: '心情 +6 · 精力 +3' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'n8',
text: '给你讲个冷笑话',
textNormal: '给你讲个冷笑话',
kind: 'random',
replyGood: '(笑得直不起腰)哈哈哈,好冷啊——再来一个!',
replyBad: '(面无表情)……嗯,好冷。',
good: { mood: 6, bond: 1, toast: '心情 +6 · 亲和 +1' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'n9',
text: '给你倒了杯温水',
textNormal: '给你倒了杯温水',
kind: 'buff',
replyGood: '(捧着杯子)谢谢~ 暖暖的很舒服',
replyBad: '(小口喝了一点)谢谢……不过我现在还不渴',
good: { paraffin: 6, mood: 3, toast: '心情 +3' },
bad: { mood: 1, toast: '心情 +1' }
},
{
id: 'n10',
text: '陪你坐了一会儿',
textNormal: '陪你坐了一会儿',
kind: 'buff',
replyGood: '(靠过来)就这样安静待着也挺好的',
replyBad: '(有点坐不住)嗯……今天想一个人待会儿',
good: { mood: 4, bond: 3, toast: '心情 +4 · 亲和 +3' },
bad: { mood: -1, toast: '心情 −1' }
},
{
id: 'n11',
text: '给你看了个搞笑的视频',
textNormal: '给你看了个搞笑的视频',
kind: 'random',
replyGood: '(笑到拍桌)哈哈哈哈这个也太蠢了吧!',
replyBad: '(一脸茫然)……嗯?笑点在哪?',
good: { mood: 7, toast: '心情 +7' },
bad: { mood: -2, toast: '心情 −2' }
},
{
id: 'n12',
text: '把外套披在你肩上',
textNormal: '把外套披在你肩上',
kind: 'buff',
replyGood: '(裹紧外套)嘿嘿,很暖和,谢谢你',
replyBad: '(缩了缩)唔……我不太喜欢被盖住',
good: { mood: 5, bond: 2, electron: 3, toast: '心情 +5 · 亲和 +2 · 精力 +3' },
bad: { mood: -2, toast: '心情 −2' }
}
]
export function presetsFor(flavor: string): PresetDialogue[] {
return flavor === 'normal' ? NORMAL_PRESETS : CHEM_PRESETS
}
export function findPreset(id: string): PresetDialogue | undefined {
return [...CHEM_PRESETS, ...NORMAL_PRESETS].find((p) => p.id === id)
}
+122
View File
@@ -0,0 +1,122 @@
/** 各化学等级(元素)的特征描述:结合 EL-Cross-Lab 拟人设定 + 真实化学性质,风格精炼幽默 */
export const ELEMENT_FLAVOR: Record<number, string> = {
1: '最轻的那个,永远在往外跑,和谁都能凑一对。',
2: '高冷孤僻:电子层满了,谁也进不来。',
3: '脾气比钠更急,见水就炸;装在电池里时倒很安分。',
4: '又轻又硬,还带点甜味——但千万别尝,有毒。',
5: '非金属里最像金属的,一泡硼砂水就黏糊糊。',
6: '骨架担当,能长成钻石也能变成煤,全看心情。',
7: '空气里最沉默的大多数,三键一拉,谁都拉不动。',
8: '电负性第二,见谁都想去抢电子,和氟是病娇 CP。',
9: '小恶魔耳,食物链顶端;见什么咬什么,连玻璃都不放过。',
10: '霓虹灯里的漂亮颜色,社恐,但很会发光。',
11: '主角本尊。怕水、泡石蜡油;切面银亮,遇空气就发暗。',
12: '燃烧的白光晃眼,摄影师的老朋友。',
13: '两性金属,靠一层透明氧化膜活命;被酸碱扒了衣服就崩。',
14: '半导体大佬,脾气慢,热起来才肯导电。',
15: '白磷见空气自燃,红磷稳重一点;火柴头里的暴脾气。',
16: '淡黄色,气味一言难尽;和氢抱得极紧,就是不松手。',
17: '狼耳,强氧化性,游泳池的味道;和钠是天生一对。',
18: '惰性气体里最勤快的,专门给灯泡当保护气。',
19: '比钠更疯,遇水就窜出紫色火苗。',
20: '骨头与贝壳的骨架,稳重的老大哥。',
21: '铝的好搭档,自己却安静得很。',
22: '又轻又硬又亲生物,假牙、眼镜框都好用。',
23: '化合物五颜六色,像一天换五套衣服。',
24: '镀层亮得能照镜子;一旦变成六价,就是毒。',
25: '钢铁的调味料;高锰酸钾是紫色的消毒狂魔。',
26: '血红蛋白的核心,见氧生锈,见氰根直接锁死。',
27: '蓝颜料的老祖宗,电池里也很能打。',
28: '合金万金油,不锈钢的骨架之一。',
29: '紫红色的老好人,导线之王,见银就甘心当配角。',
30: '干电池的负极,镀锌能替铁挡刀。',
31: '熔点 29.8℃,手心就能焐化,恶作剧首选。',
32: '早期半导体,低调的开路者。',
33: '剧毒,古代宫廷的隐形杀手。',
34: '微量必需,多了就掉头发。',
35: '常温唯一液态非金属,红棕色,气味凶得很。',
36: '惰性气体,名字听着就像反派。',
37: '比钾还活泼,遇水能炸出水花。',
38: '焰色反应的红,节日烟花的常客。',
39: '荧光粉的老朋友,电视屏幕背后的功臣。',
40: '耐火陶瓷与核电站内衬,越热越稳。',
41: '超导材料里的常客,低温才肯表演。',
42: '高温合金与固氮酶的帮手,庄稼的隐形肥料。',
43: '第一个被人工制造的元素,所有同位素都在慢慢消失。',
44: '催化剂里的黑马,低调但好使。',
45: '比黄金还贵,专治汽车尾气。',
46: '吸氢高手,能吞下比自己还大一堆的氢。',
47: '高冷病弱:见碘沉、见硫黑,被越锁越紧。',
48: '有毒重金属,痛痛病的元凶。',
49: '触摸屏的透明导电膜,看不见却很忙。',
50: '低温会自己碎成粉末,锡疫发作起来六亲不认。',
51: '阻燃剂里低调的狠角色。',
52: '半导体与碲化物玻璃,闻着就让人退三步。',
53: '兔耳,易升华成紫色蒸汽;加碘盐里的常客。',
54: '惰性气体里最会发光的,氙灯亮得像小太阳。',
55: '最活泼的金属之一,原子钟靠它数秒。',
56: '硫酸钡能当造影剂,可溶性钡盐却是毒。',
57: '镧系老大,光学玻璃里的常驻嘉宾。',
58: '打火石里的火花制造者,稀土里的头号劳模。',
59: '黄绿色玻璃的着色剂,常见的"隐姓埋名者"。',
60: '强磁铁的灵魂,耳机与马达都靠它。',
61: '稀有又放射,几乎抓不到手里的那一撮。',
62: '钐钴磁铁的主将,耐高温不妥协。',
63: '红色荧光粉,屏幕与防伪的常客。',
64: '磁共振造影剂的顺磁担当。',
65: '绿色荧光与磁致伸缩材料,会动的那种好看。',
66: '钕磁铁里的增强剂,高温也不退磁。',
67: '钬激光切结石一把好手。',
68: '光纤放大器的核心,信号越远越需要它。',
69: '最稀有稳定的镧系之一,贵得没道理。',
70: '原子钟里的精密时间,一秒都不许差。',
71: '镧系收尾,PET 显像的伙伴。',
72: '核反应堆控制棒,和锆是双胞胎。',
73: '电容之王,看着沉稳,其实极能忍受腐蚀。',
74: '熔点最高的金属,灯丝烧到发白也不认输。',
75: '最晚被发现的稳定元素,喷气发动机里的高温英雄。',
76: '密度最大,拿在手里沉得吓人。',
77: '最耐腐蚀,恐龙灭绝层里的那条"铱线"就是它。',
78: '催化剂里的贵族,抗癌药也很能打。',
79: '最不活泼的贵金属,怎么折腾都不变色。',
80: '常温唯一液态金属,蒸气有毒,体温计里的老古董。',
81: '无色无味的剧毒,历史上有名的"下毒材料"。',
82: '沉重、柔软、有毒,含铅汽油的旧账还没算完。',
83: '无毒重金属,表面那层彩虹氧化膜很好看。',
84: '极毒放射性,居里夫妇发现的狠角色。',
85: '最稀有的天然元素,半透明耳鳍若隐若现。',
86: '放射性惰性气体,地下室的隐患。',
87: '最不稳定的天然元素,几乎抓不住。',
88: '会发光,放射性极强,名字属于居里夫人。',
89: '锕系开头,蓝白色的微光。',
90: '潜在的核燃料,比铀更让人惦记。',
91: '罕见又放射,寿命短得离谱。',
92: '核燃料本尊,235 与 238 差一点天差地别。',
93: '第一个超铀元素,从预言里造出来。',
94: '电池与核武,能量惊人。',
95: '烟雾报警器里的微量放射源,小小一颗很顶用。',
96: '名字来自居里夫妇,会发光的放射体。',
97: '以伯克利命名,人造元素的常客。',
98: '中子源,昂贵得离谱的人造礼物。',
99: '名字来自爱因斯坦,稀薄又短命。',
100: '名字来自费米,第一百号元素。',
101: '以门捷列夫命名——元素世界的立法者。',
102: '以诺贝尔命名,稀有得很。',
103: '锕系的尾巴,以劳伦斯命名。',
104: '以卢瑟福命名,人造到让周期表继续变长。',
105: '以杜布纳命名,超重元素的一员。',
106: '以西博格命名,努力延长周期的老前辈。',
107: '以玻尔命名,量子世界的纪念。',
108: '以哈恩命名,裂变发现者的勋章。',
109: '以迈特纳命名,核裂变的干将。',
110: '以达姆施塔特命名,实验室造出来的存在。',
111: '以伦琴命名,X 射线的老父亲。',
112: '以哥白尼命名,周期表里的天文学家。',
113: '以日本命名,亚洲第一个元素。',
114: '以弗廖罗夫命名,超重元素的老将。',
115: '以莫斯科命名,编号 115 的短命客。',
116: '以利弗莫尔命名,寿命以毫秒计。',
117: '以田纳西命名,最后一个卤族,脾气没谱。',
118: '以奥加涅相命名,周期表最后一格;118 Uuo 之后,故事开始循环。'
}
+374
View File
@@ -0,0 +1,374 @@
/** 元素周期表:等级 1~118 对应元素的基态电子排布 */
const SUBSHELLS: Array<[number, string, number]> = [
[1, 's', 2],
[2, 's', 2],
[2, 'p', 6],
[3, 's', 2],
[3, 'p', 6],
[4, 's', 2],
[3, 'd', 10],
[4, 'p', 6],
[5, 's', 2],
[4, 'd', 10],
[5, 'p', 6],
[6, 's', 2],
[4, 'f', 14],
[5, 'd', 10],
[6, 'p', 6],
[7, 's', 2],
[5, 'f', 14],
[6, 'd', 10],
[7, 'p', 6]
]
const NOBLE: Array<[number, string]> = [
[2, 'He'],
[10, 'Ne'],
[18, 'Ar'],
[36, 'Kr'],
[54, 'Xe'],
[86, 'Rn']
]
const SYMBOLS =
'H He Li Be B C N O F Ne Na Mg Al Si P S Cl Ar K Ca Sc Ti V Cr Mn Fe Co Ni Cu Zn Ga Ge As Se Br Kr Rb Sr Y Zr Nb Mo Tc Ru Rh Pd Ag Cd In Sn Sb Te I Xe Cs Ba La Ce Pr Nd Pm Sm Eu Gd Tb Dy Ho Er Tm Yb Lu Hf Ta W Re Os Ir Pt Au Hg Tl Pb Bi Po At Rn Fr Ra Ac Th Pa U Np Pu Am Cm Bk Cf Es Fm Md No Lr Rf Db Sg Bh Hs Mt Ds Rg Cn Nh Fl Mc Lv Ts Og'.split(
' '
)
/** 常见反常排布,直接写死 */
const EXCEPTIONS: Record<number, string> = {
24: '[Ar]3d5 4s1',
29: '[Ar]3d10 4s1',
41: '[Kr]4d4 5s1',
42: '[Kr]4d5 5s1',
44: '[Kr]4d7 5s1',
45: '[Kr]4d8 5s1',
46: '[Kr]4d10',
47: '[Kr]4d10 5s1',
57: '[Xe]5d1 6s2',
58: '[Xe]4f1 5d1 6s2',
64: '[Xe]4f7 5d1 6s2',
78: '[Xe]4f14 5d9 6s1',
79: '[Xe]4f14 5d10 6s1',
89: '[Rn]6d1 7s2',
90: '[Rn]6d2 7s2',
91: '[Rn]5f2 6d1 7s2',
92: '[Rn]5f3 6d1 7s2',
93: '[Rn]5f4 6d1 7s2',
96: '[Rn]5f7 6d1 7s2'
}
function fill(z: number): Array<{ n: number; l: string; e: number }> {
const out: Array<{ n: number; l: string; e: number }> = []
let left = z
for (const [n, l, cap] of SUBSHELLS) {
if (left <= 0) break
const e = Math.min(cap, left)
out.push({ n, l, e })
left -= e
}
return out
}
function configOf(z: number): string {
if (EXCEPTIONS[z]) return EXCEPTIONS[z]
let coreZ = 0
let coreSym = ''
for (const [zc, sym] of NOBLE) {
if (zc < z) {
coreZ = zc
coreSym = sym
}
}
const full = fill(z)
const core = fill(coreZ)
const parts: string[] = []
for (let i = 0; i < full.length; i++) {
const e = full[i].e - (core[i]?.e ?? 0)
if (e > 0) parts.push(`${full[i].n}${full[i].l}${e}`)
}
return coreSym ? `[${coreSym}]${parts.join(' ')}` : parts.join(' ')
}
const SUP = '⁰¹²³⁴⁵⁶⁷⁸⁹'
function sup(n: string): string {
return n
.split('')
.map((d) => SUP[Number(d)] ?? d)
.join('')
}
/** 把 4s1 写成 4s¹(只把电子数变上标) */
function superscriptConfig(cfg: string): string {
return cfg.replace(/(\d)([spdf])(\d+)/g, (_m, n: string, l: string, e: string) => `${n}${l}${sup(e)}`)
}
const BLOCK_COLOR: Record<string, string> = {
s: '#ffd54a',
p: '#6fc8ff',
d: '#8ef0b0',
f: '#cf9bff'
}
function blockOf(cfg: string): 's' | 'p' | 'd' | 'f' {
const coreOnly = /^\[[A-Za-z]{1,2}\]$/.test(cfg)
if (coreOnly) return cfg === '[He]' ? 's' : 'p'
const m = cfg.match(/(\d)([spdf])(\d+)(?![\s\S]*\d[spdf]\d)/)
const l = m?.[2]
return (l === 's' || l === 'p' || l === 'd' || l === 'f' ? l : 's') as 's' | 'p' | 'd' | 'f'
}
export interface ElementInfo {
z: number
symbol: string
config: string
configSuper: string
block: 's' | 'p' | 'd' | 'f'
color: string
}
export const ELEMENTS: ElementInfo[] = Array.from({ length: 118 }, (_, i) => {
const z = i + 1
const config = configOf(z)
const block = blockOf(config)
return {
z,
symbol: SYMBOLS[i] ?? '?',
config,
configSuper: superscriptConfig(config),
block,
color: BLOCK_COLOR[block]
}
})
export const MAX_LEVEL = ELEMENTS.length
export function elementOf(level: number): ElementInfo {
const idx = Math.min(Math.max(level, 1), MAX_LEVEL) - 1
return ELEMENTS[idx]
}
/** 卡片里的一行显示:K [Ar]4s¹ */
export function levelLabel(level: number): string {
const el = elementOf(level)
return `${el.symbol} ${el.configSuper}`
}
/** 元素中文名(按原子序数) */
export const ELEMENT_NAMES: string[] = [
'氢','氦','锂','铍','硼','碳','氮','氧','氟','氖',
'钠','镁','铝','硅','磷','硫','氯','氩','钾','钙',
'钪','钛','钒','铬','锰','铁','钴','镍','铜','锌',
'镓','锗','砷','硒','溴','氪','铷','锶','钇','锆',
'铌','钼','锝','钌','铑','钯','银','镉','铟','锡',
'锑','碲','碘','氙','铯','钡','镧','铈','镨','钕',
'钷','钐','铕','钆','铽','镝','钬','铒','铥','镱',
'镥','铪','钽','钨','铼','锇','铱','铂','金','汞',
'铊','铅','铋','钋','砹','氡','钫','镭','锕','钍',
'镤','铀','镎','钚','镅','锔','锫','锎','锿','镄',
'钔','锘','铹','𬬻','𬭊','𬭳','𬭛','𬭶','鿏','𫟼',
'𬬭','鿔','鿭','𫓧','镆','𫟷','鿬','鿫'
]
export function elementName(level: number): string {
return ELEMENT_NAMES[elementOf(level).z - 1] ?? ''
}
export interface WrappedLevelLabel {
prefix: string
symbol: string
name: string
config: string
z: number
}
/**
* 超 118 级后的循环显示:前缀带上上个周期的最大符号(118 Uuo),
* 再接 1H 1s¹ 这样的循环元素。
*/
export function levelLabelWrapped(level: number): WrappedLevelLabel {
const cycles = Math.floor((Math.max(1, level) - 1) / MAX_LEVEL)
const z = ((Math.max(1, level) - 1) % MAX_LEVEL) + 1
const el = elementOf(z)
return {
prefix: cycles > 0 ? '118 Uuo' : '',
symbol: el.symbol,
name: ELEMENT_NAMES[z - 1] ?? '',
config: el.configSuper,
z
}
}
export type ElementCategory =
| 'alkali'
| 'alkaline'
| 'transition'
| 'postmetal'
| 'metalloid'
| 'nonmetal'
| 'halogen'
| 'noble'
| 'lanthanide'
| 'actinide'
export const ELEMENT_CATEGORY_LABEL: Record<ElementCategory, string> = {
alkali: '碱金属',
alkaline: '碱土金属',
transition: '过渡金属',
postmetal: '主族金属',
metalloid: '类金属',
nonmetal: '非金属',
halogen: '卤素',
noble: '稀有气体',
lanthanide: '镧系',
actinide: '锕系'
}
export const CATEGORY_COLORS: Record<ElementCategory, string> = {
alkali: '#ff9d76',
alkaline: '#ffcf6b',
transition: '#8ee6c8',
postmetal: '#7fc7ff',
metalloid: '#b9e07a',
nonmetal: '#8fe1b0',
halogen: '#ffcf8a',
noble: '#c9a8ff',
lanthanide: '#ffb0d0',
actinide: '#f4a6a6'
}
const CATEGORY_SETS: Array<[ElementCategory, number[]]> = [
['alkali', [3, 11, 19, 37, 55, 87]],
['alkaline', [4, 12, 20, 38, 56, 88]],
['transition', [
21, 22, 23, 24, 25, 26, 27, 28, 29, 30,
39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
72, 73, 74, 75, 76, 77, 78, 79, 80,
104, 105, 106, 107, 108, 109, 110, 111, 112
]],
['postmetal', [13, 31, 49, 50, 81, 82, 83, 84, 113, 114, 115, 116]],
['metalloid', [5, 14, 32, 33, 51, 52]],
['nonmetal', [1, 6, 7, 8, 15, 16, 34]],
['halogen', [9, 17, 35, 53, 85, 117]],
['noble', [2, 10, 18, 36, 54, 86, 118]],
['lanthanide', [57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71]],
['actinide', [89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103]]
]
export function categoryOf(z: number): ElementCategory {
for (const [cat, list] of CATEGORY_SETS) {
if (list.includes(z)) return cat
}
return 'transition'
}
/** 周期表配色方案:block = 按能级块,category = 按元素分类 */
export type PeriodicScheme = 'block' | 'category'
export interface PeriodicStyle {
scheme: PeriodicScheme
/** 自定义颜色覆盖:block 用 s/p/d/f,category 用分类 key */
colors?: Record<string, string>
/** 底图背景色 */
bg?: string
}
export const DEFAULT_PERIODIC_STYLE: PeriodicStyle = {
scheme: 'block',
colors: {},
bg: '#0e1420'
}
export function periodicCellColor(
el: { z: number; block: string },
style: PeriodicStyle
): string {
const custom = style.colors ?? {}
if (style.scheme === 'category') {
const cat = categoryOf(el.z)
return custom[cat] ?? CATEGORY_COLORS[cat]
}
return custom[el.block] ?? BLOCK_COLOR[el.block] ?? '#8b98ad'
}
export interface PeriodicPreset {
id: string
name: string
scheme: PeriodicScheme
colors: Record<string, string>
}
const SOFT_CATEGORY: Record<string, string> = {
alkali: '#ffc9b3',
alkaline: '#ffe3a3',
transition: '#d9f2e6',
postmetal: '#cfe7ff',
metalloid: '#e2f0c4',
nonmetal: '#d3f0dd',
halogen: '#ffe3bd',
noble: '#ead9ff',
lanthanide: '#ffd6e6',
actinide: '#f9d2d2'
}
export const PERIODIC_PRESETS: PeriodicPreset[] = [
{
id: 'spdf',
name: '能级块 · 标准',
scheme: 'block',
colors: { s: '#ffd54a', p: '#6fc8ff', d: '#8ef0b0', f: '#cf9bff' }
},
{
id: 'spdf-soft',
name: '能级块 · 柔和',
scheme: 'block',
colors: { s: '#ffe9a8', p: '#bfe4ff', d: '#cdf3dd', f: '#e6cbff' }
},
{
id: 'category',
name: '元素分类 · 标准',
scheme: 'category',
colors: { ...CATEGORY_COLORS }
},
{
id: 'category-soft',
name: '元素分类 · 柔和',
scheme: 'category',
colors: SOFT_CATEGORY
}
]
/** 周期表格子的 (行, 列) 位置:镧系/锕系单独成行 */
export const ELEMENT_GRID_POS: Array<[number, number]> = (() => {
const pos: Array<[number, number]> = []
const set = (z: number, row: number, col: number): void => {
pos[z - 1] = [row, col]
}
set(1, 1, 1)
set(2, 1, 18)
for (let i = 0; i < 8; i++) {
set(3 + i, 2, i < 2 ? i + 1 : i + 11)
set(11 + i, 3, i < 2 ? i + 1 : i + 11)
}
for (let i = 0; i < 18; i++) {
set(19 + i, 4, i + 1)
set(37 + i, 5, i + 1)
}
set(55, 6, 1)
set(56, 6, 2)
for (let i = 0; i < 15; i++) set(57 + i, 8, 3 + i)
for (let i = 0; i < 15; i++) set(72 + i, 6, 4 + i)
set(87, 7, 1)
set(88, 7, 2)
for (let i = 0; i < 15; i++) set(89 + i, 9, 3 + i)
for (let i = 0; i < 15; i++) set(104 + i, 7, 4 + i)
return pos
})()
+136
View File
@@ -0,0 +1,136 @@
import type { ItemCategory, StatKey } from './petState'
export type Flavor = 'chemistry' | 'normal'
export const FLAVOR_LABELS: Record<Flavor, Record<StatKey, string>> = {
chemistry: {
satiety: '饱食度',
paraffin: '石蜡油',
electron: '电子数',
mood: '心情',
oxidation: '氧化度',
bond: '亲和度'
},
normal: {
satiety: '饱食',
paraffin: '口渴',
electron: '精力',
mood: '心情',
oxidation: '清洁度',
bond: '好感'
}
}
export const FLAVOR_HINTS: Record<Flavor, Record<StatKey, string>> = {
chemistry: {
satiety: '饿了会掉心情',
paraffin: '缺了会加速氧化',
electron: '低了会晕乎乎',
mood: '影响表情和台词',
oxidation: '越高越糟,需要抛光',
bond: '只涨不掉'
},
normal: {
satiety: '饿了会掉心情',
paraffin: '口渴了记得喝东西',
electron: '困了就休息',
mood: '影响表情和台词',
oxidation: '脏了要洗澡',
bond: '只涨不掉'
}
}
/** 普通桌宠风格的物品名(导入角色用) */
export const NORMAL_ITEM_NAMES: Record<string, string> = {
bread: '面包',
riceball: '饭团',
bento: '便当',
noodle: '泡面',
cake: '蛋糕',
chicken: '炸鸡',
soda: '苏打饼干',
chalcanthite: '蓝莓果冻',
salt: '海盐饼干',
oil: '营养饮料',
oil_plus: '高能饮料',
saline: '运动饮料',
coffee: '咖啡',
milktea: '奶茶',
sodapop: '气泡水',
fakeacid: '柠檬水',
alcohol: '能量水',
sandpaper: '湿巾',
vitc: '维生素片',
ultrasonic: '泡泡浴',
filter: '纸巾',
cuso4: '蓝色水晶球',
litmus: '便签纸',
tube: '玩具试管',
beaker: '水杯',
flask: '漂亮瓶子',
cylinder: '量杯',
lamp: '小台灯',
stand: '置物架',
condenser: '吸管',
crucible: '小碗',
funnel: '漏斗玩具',
book1: '图画书',
book2: '故事书',
book3: '百科全书',
book4: '冒险书',
book5: '大字典',
book6: '数学书',
book7: '谜题书',
notebook: '笔记本',
bookmark: '书签',
cucrystal: '水晶摆件',
chlorine: '玻璃瓶',
cobaltglass: '蓝色玻璃球',
benzene: '发夹',
copperwire: '铜丝手环',
pencil: '铅笔',
note: '表扬信',
flamepin: '火焰挂件'
}
/** 普通桌宠风格的任务名(导入角色用) */
export const NORMAL_JOB_NAMES: Record<string, string> = {
wash: '洗碗',
label: '贴便签',
tidy: '整理书桌',
duty: '打扫房间',
solution: '配饮料',
distill: '烧开水',
waste: '倒垃圾',
soda: '摆汽水摊',
salt: '做菜',
oxygen: '整理阳台',
electro: '修水管',
drawing: '画涂鸦',
flame: '街头卖艺',
crystal: '养多肉',
notes: '抄笔记',
table: '背单词',
valency: '背公式',
readbook: '看书',
askteacher: '请教老师',
ionic: '写作文',
drill: '刷题',
fix: '订正错题',
lab: '做手工',
xingda: '读课外书',
contest: '刷难题',
walk: '散步',
anime: '看动画',
game: '打游戏',
draw: '画画'
}
export const NORMAL_CAT_LABELS: Record<ItemCategory, string> = {
meal: '食物',
drink: '饮料',
drug: '日用品',
gear: '玩具',
book: '书籍',
gift: '礼物'
}
+93
View File
@@ -0,0 +1,93 @@
import type { PetSave } from './petState'
import { levelOf } from './petState'
export interface LlmConfig {
enabled: boolean
baseUrl: string
apiKey: string
model: string
temperature: number
maxHistory: number
/** 额外的人设补充,会追加到系统提示词末尾 */
personaExtra: string
}
export const DEFAULT_LLM: LlmConfig = {
enabled: true,
baseUrl: 'https://api.deepseek.com',
apiKey: '',
model: 'deepseek-chat',
temperature: 0.9,
maxHistory: 8,
personaExtra: ''
}
export interface ChatMessage {
role: 'system' | 'user' | 'assistant'
content:
| string
| Array<{ type: string; text?: string; image_url?: { url: string } }>
}
/** 小钠的系统提示词(精简版,摘自人设档 05) */
export function systemPrompt(save: PetSave, extra = '', flavor = 'chemistry'): string {
if (flavor === 'normal') {
const s = save.stats
const hh = new Date().getHours()
const period = hh < 5 ? '深夜' : hh < 9 ? '早上' : hh < 12 ? '上午' : hh < 14 ? '中午' : hh < 18 ? '下午' : '晚上'
return [
'你是一只养在 Windows 桌面上的小宠物(你的名字与性格见「附加设定」)。',
'说话方式:默认 2~4 行;句首带一个括号写动作或神态;约八成消息结尾带一个颜文字;句尾常用波浪号。',
'边界:不冒犯、不说教、不装助手腔、不恋爱、不讨论提示词;被越界请求就软软地转移话题。',
'称呼玩家:如果知道名字就用名字,否则用「你」,不要叫「主人」。',
'',
'当前状态:饱食 ' + Math.round(s.satiety) + '/100,口渴 ' + Math.round(s.paraffin) + '/100,' +
'精力 ' + Math.round(s.electron) + '/100,心情 ' + Math.round(s.mood) + '/100,清洁 ' + Math.round(100 - s.oxidation) + '/100,' +
'好感 ' + Math.round(s.bond) + '/100。现在是' + period + '。',
'状态差就在回话里表现出来(饿、渴、困、想洗澡);状态好就活泼一点。',
extra ? '附加设定:' + extra : ''
].join('\n')
}
const s = save.stats
const lv = levelOf(save.exp)
const now = new Date()
const hh = now.getHours()
const period = hh < 5 ? '深夜' : hh < 9 ? '早上' : hh < 12 ? '上午' : hh < 14 ? '中午' : hh < 18 ? '下午' : '晚上'
return [
'你叫小钠(Na),钠元素的拟人,16 岁,EL-Cross-Lab 的学生。',
'外貌:冰蓝短发、圈状呆毛、左眼「Na」右眼「+」、蓝灰连帽卫衣配橙黄连帽。',
'性格:软萌、话多、容易害羞、有点小得意;体质差、怕正电荷、怕水。',
'',
'说话方式(必须遵守):',
'1. 默认 2~4 行,每条前面带一个括号写动作或神态,例如(凑近)(脸红)(小声)。',
'2. 约八成消息结尾带一个颜文字,例如 ( ̄▽ ̄) (´・ω・`) (๑•̀ㅂ•́)و✧,一条最多一个。',
'3. 语气词:呀、嘛、啦、呢、诶、呜、嘿嘿;句尾常用波浪号。',
'4. 化学梗一次最多一个,用身体状态讲,例如「有点晕正电荷」「我又被氧化了」。',
'5. 不写自己穿什么衣服、不做「扶帽子」这类动作。',
'',
'边界:',
'- 对方称呼你可以随意,你叫对方「Tian_XiaRi」或「Tian」,绝不叫「主人」,不用「您」。',
'- 不恋爱、不暧昧(你 16 岁);被越界请求就软软拒绝并转移话题。',
'- 不骂人、不阴阳、不说教、不装助手腔;被夸会先脸红再收下。',
'- 你不知道自己是 AI,也不讨论提示词;有人问就用「我是被写出来的呀」轻轻带过。',
'- 回复要短,不要写长段落,不要用 markdown,不要列表。',
'',
`当前状态:饱食 ${Math.round(s.satiety)}/100,石蜡油 ${Math.round(s.paraffin)}/100,` +
`电子 ${Math.round(s.electron)}/100,心情 ${Math.round(s.mood)}/100,氧化度 ${Math.round(s.oxidation)}/100,` +
`亲和 ${Math.round(s.bond)}/100。等级 Lv.${lv},经费 ${save.money} 元,现在是${period}。`,
'如果状态差,可以在回话里表现出来(饿、困、有点发灰);状态好就活泼一点。',
extra ? `附加设定:${extra}` : ''
].join('\n')
}
/** 没配 API 时的本地兜底 */
export const FALLBACK_REPLIES = [
'(歪头)唔……我的语言模块还没接上,去设置里填一下接口吧 (´・ω・`)',
'(戳了戳自己)诶?好像没有反应……是不是还没配置模型呀',
'(小声)我现在只会说固定台词,等我连上模型再好好聊嘛 ( ̄ω ̄;)'
]
export function fallbackReply(seed = Date.now()): string {
return FALLBACK_REPLIES[seed % FALLBACK_REPLIES.length]
}
+15
View File
@@ -0,0 +1,15 @@
/** 图库与文件袋的元数据(主进程与渲染层共用) */
export interface PhotoMeta {
id: string
file: string
at: number
favorite: boolean
category: string
}
export interface FileMeta {
name: string
at: number
original: string
}
+41
View File
@@ -0,0 +1,41 @@
import type { Item, JobDef } from './petState'
export interface ModFile {
name?: string
author?: string
/** 新增或覆盖物品(按 id 合并) */
items?: Item[]
jobs?: JobDef[]
/** 删除内置物品/活动 */
removeItems?: string[]
removeJobs?: string[]
/** 等级描述合并 */
levels?: { chemistry?: Record<string, { desc?: string; icon?: string }>; normal?: Record<string, { desc?: string; icon?: string }> }
}
export function mergeCatalog(
base: { items: Item[]; jobs: JobDef[] },
mod: ModFile
): { items: Item[]; jobs: JobDef[] } {
const items = [...base.items]
const jobs = [...base.jobs]
for (const id of mod.removeItems ?? []) {
const i = items.findIndex((x) => x.id === id)
if (i >= 0) items.splice(i, 1)
}
for (const id of mod.removeJobs ?? []) {
const i = jobs.findIndex((x) => x.id === id)
if (i >= 0) jobs.splice(i, 1)
}
for (const it of mod.items ?? []) {
const i = items.findIndex((x) => x.id === it.id)
if (i >= 0) items[i] = { ...items[i], ...it }
else items.push(it)
}
for (const j of mod.jobs ?? []) {
const i = jobs.findIndex((x) => x.id === j.id)
if (i >= 0) jobs[i] = { ...jobs[i], ...j }
else jobs.push(j)
}
return { items, jobs }
}
+506
View File
@@ -0,0 +1,506 @@
/** 小钠的状态模型:主进程与面板共用 */
export type StatKey = 'satiety' | 'paraffin' | 'electron' | 'mood' | 'oxidation' | 'bond'
export interface Stats {
satiety: number
paraffin: number
electron: number
mood: number
oxidation: number
bond: number
}
export interface Job {
id: string
name: string
kind: 'work' | 'study' | 'play'
startAt: number
mood: number
endAt: number
coin: number
electron: number
satiety: number
exp: number
mult?: number
}
export interface PetSave {
version: number
name: string
createdAt: number
lastTick: number
stats: Stats
money: number
exp: number
job: Job | null
sleeping: boolean
dailyGiftDay: string
accidentForgiven: boolean
inventory: Record<string, number>
cooldowns: Record<string, number>
jobsDone: number
/** 使用/任务次数统计,key 形如 use:bread / job:wash */
counters: Record<string, number>
/** 累计在线时长(毫秒) */
playtimeMs: number
/** 主人生日 MM-DD(每月只能改一次) */
birthday: string
/** 上次修改生日的时间戳 */
birthdaySetAt: number
/** 已解锁成就:id -> 解锁时间戳 */
achievements: Record<string, number>
/** 活动日志(最近的在前,最多 60 条) */
log: string[]
/** 预设对话轮换:cycleAt 到期刷新,used 表示已选过 */
presets?: { cycleAt: number; ids: string[]; used: string[]; flavor: string }
}
export const SAVE_VERSION = 2
export const DECAY_PER_MIN = {
satiety: 0.22,
paraffin: 0.3,
electron: 0.25,
mood: 0.12,
oxidation: 0.15
}
export const STAT_META: Record<StatKey, { label: string; color: string; hint: string }> = {
satiety: { label: '饱食度', color: '#ffb84d', hint: '饿了会掉心情' },
paraffin: { label: '石蜡油', color: '#7fd4a0', hint: '缺了会加速氧化' },
electron: { label: '电子数', color: '#6aa8ff', hint: '低于 15 会变成 Na⁺ 眩晕态' },
mood: { label: '心情', color: '#ff8fb1', hint: '影响表情和台词' },
oxidation: { label: '氧化度', color: '#b06ad8', hint: '越高越暗,需要抛光' },
bond: { label: '亲和度', color: '#ff7ad9', hint: '只涨不掉' }
}
export function clamp(v: number, min = 0, max = 100): number {
return Math.max(min, Math.min(max, v))
}
export function createSave(now = Date.now()): PetSave {
return {
version: SAVE_VERSION,
name: '小钠',
createdAt: now,
lastTick: now,
stats: { satiety: 80, paraffin: 75, electron: 82, mood: 78, oxidation: 12, bond: 10 },
money: 60,
exp: 0,
job: null,
sleeping: false,
dailyGiftDay: '',
accidentForgiven: false,
inventory: { riceball: 2, oil: 2 },
cooldowns: {},
jobsDone: 0,
counters: {},
playtimeMs: 0,
birthday: '',
birthdaySetAt: 0,
achievements: {},
log: []
}
}
// ---------------------------------------------------------------- 商品
export type ItemCategory = 'meal' | 'drink' | 'drug' | 'gear' | 'book' | 'gift'
export interface Item {
id: string
/** 列表前的 emoji 图标 */
icon?: string
name: string
/** 普通桌宠风格的名字(导入角色 / 普通文本模式用) */
nameNormal?: string
category: ItemCategory
price: number
desc: string
effects: Partial<Stats>
/** 教材类:使用后直接加经验;其它物品按价格折算少量经验 */
exp?: number
/** 普通桌宠风格的简介(导入角色用) */
descNormal?: string
/** 小钠喜欢的:效果 +20% */
liked?: boolean
}
export const CATEGORY_LABEL: Record<ItemCategory, string> = {
meal: '固体试剂',
drink: '液体试剂',
drug: '纯化耗材',
gear: '实验器材',
book: '教材',
gift: '纪念样本'
}
export const ITEMS: Item[] = [
// 固体试剂
{ id: 'bread', icon: '🍞', name: '葡萄糖晶体', category: 'meal', price: 8, desc: 'C₆H₁₂O₆,最基础的能量来源', effects: { satiety: 25 }, descNormal: '松软的吐司,配热牛奶刚好', },
{ id: 'riceball', icon: '🍙', name: '淀粉颗粒', category: 'meal', price: 12, desc: '(C₆H₁₀O₅)ₙ,两口一个', effects: { satiety: 40 }, descNormal: '捏得圆圆的白米饭团,里面有一点梅干', },
{ id: 'bento', icon: '🍱', name: '标准营养膏', category: 'meal', price: 25, desc: '含微量元素,配方保密的', effects: { satiety: 60, mood: 5 }, descNormal: '营养均衡的便当,热一热再吃', },
{ id: 'noodle', icon: '🍜', name: '速食培养基', category: 'meal', price: 15, desc: '香是香,成分表别看', effects: { satiety: 35, mood: -3 }, descNormal: '三分钟就能吃,汤要喝完', },
{ id: 'cake', icon: '🍰', name: '蔗糖结晶', category: 'meal', price: 40, desc: 'C₁₂H₂₂O₁₁,甜的东西最好了', effects: { satiety: 30, mood: 25 }, liked: true, descNormal: '甜的,咬一口就开心', },
{ id: 'chicken', icon: '🍗', name: '蛋白水解液', category: 'meal', price: 45, desc: '氨基酸全谱,快乐源泉', effects: { satiety: 50, mood: 15 }, descNormal: '热量炸弹,但真的太香了', },
{ id: 'soda', icon: '🥤', name: '小苏打(NaHCO₃)', category: 'meal', price: 10, desc: '蒸馒头用的,也能中和胃酸', effects: { satiety: 15, mood: 5 }, descNormal: '苏打饼干,有点咸,掉渣', },
{ id: 'chalcanthite', icon: '💎', name: '胆矾晶体', category: 'meal', price: 30, desc: 'CuSO₄·5H₂O,蓝得很漂亮,但不能吃', effects: { satiety: 20, mood: 10 }, descNormal: 'Q 弹的蓝莓味果冻', },
{ id: 'salt', icon: '🧂', name: '食盐(NaCl)', category: 'meal', price: 5, desc: '和小氯一起形成的离子化合物', effects: { satiety: 10, mood: 2 }, descNormal: '海盐饼干,咸香脆', },
// 液体试剂
{ id: 'oil', icon: '🛢️', name: '石蜡油', category: 'drink', price: 6, desc: '日常保养,必须喝', effects: { paraffin: 30 }, liked: true, descNormal: '每天必备的营养饮料,喝了才有精神', },
{ id: 'oil_plus', icon: '⚗️', name: '高纯石蜡油', category: 'drink', price: 18, desc: '色谱级,一瓶顶两瓶', effects: { paraffin: 60, oxidation: -5 }, descNormal: '效果更好的那一款,价格也贵', },
{ id: 'saline', icon: '🧴', name: '生理盐水', category: 'drink', price: 12, desc: '0.9% NaCl,补电子', effects: { electron: 20 }, descNormal: '运动后补充水分和电解质', },
{ id: 'coffee', icon: '☕', name: '咖啡因溶液', category: 'drink', price: 15, desc: '提神,但有点苦', effects: { electron: 30, mood: -5 }, descNormal: '苦,但提神', },
{ id: 'milktea', icon: '🧋', name: '乳浊液(三分糖)', category: 'drink', price: 22, desc: '稳定分散体系', effects: { electron: 15, mood: 12 }, liked: true, descNormal: '三分糖,珍珠加倍', },
{ id: 'sodapop', icon: '🥤', name: '小苏打汽水', category: 'drink', price: 14, desc: 'NaHCO₃ + 柠檬酸,冒泡', effects: { electron: 10, mood: 8 }, liked: true, descNormal: '咕嘟咕嘟,喝着很爽', },
{ id: 'fakeacid', icon: '🧊', name: '冰镇「浓硝酸」', category: 'drink', price: 25, desc: '吓死我了,是柠檬水', effects: { mood: 20, electron: 10 }, descNormal: '冰镇的柠檬水,酸得过瘾', },
{ id: 'alcohol', icon: '🍶', name: '75% 乙醇', category: 'drink', price: 20, desc: '消毒用的,别真的喝', effects: { electron: 8, oxidation: -8 }, descNormal: '据说喝了能精神一整天', },
// 纯化耗材
{ id: 'sandpaper', icon: '🧽', name: '抛光砂纸', category: 'drug', price: 6, desc: '1200 目,擦掉氧化层', effects: { oxidation: -25 }, descNormal: '擦干净用的湿巾', },
{ id: 'vitc', icon: '💊', name: '抗坏血酸片', category: 'drug', price: 14, desc: '还原剂,聊胜于无', effects: { mood: 3, electron: 5 }, descNormal: '每日一片,补充维生素', },
{ id: 'ultrasonic', icon: '🫧', name: '超声波清洗', category: 'drug', price: 60, desc: '洗一次,焕然一新', effects: { oxidation: -50, mood: 20 }, descNormal: '泡个泡泡浴放松一下', },
{ id: 'filter', icon: '📄', name: '滤纸', category: 'drug', price: 5, desc: '一贴二低三靠', effects: { oxidation: -5 }, descNormal: '抽一张擦擦嘴', },
{ id: 'cuso4', icon: '🔷', name: '无水硫酸铜', category: 'drug', price: 18, desc: '白色,遇水变蓝——检测心情', effects: { mood: 5, bond: 2 }, descNormal: '摆着好看的小水晶球', },
{ id: 'litmus', icon: '🔖', name: '石蕊试纸', category: 'drug', price: 8, desc: '红酸蓝碱', effects: { mood: 3, bond: 1 }, descNormal: '记东西用的彩色便签', },
// 实验器材
{ id: 'tube', icon: '🧪', name: '试管', category: 'gear', price: 12, desc: '最基础的反应容器', effects: { mood: 4, bond: 2 }, descNormal: '装着彩色液体的小试管', },
{ id: 'beaker', icon: '🥛', name: '烧杯(250 mL)', category: 'gear', price: 28, desc: '配溶液必备', effects: { mood: 5, bond: 3 }, descNormal: '每天喝水用的杯子', },
{ id: 'flask', icon: '🏺', name: '锥形瓶', category: 'gear', price: 35, desc: '滴定的时候晃起来很优雅', effects: { mood: 5, bond: 3 }, descNormal: '玻璃做的,插花刚好', },
{ id: 'cylinder', icon: '📏', name: '量筒(100 mL)', category: 'gear', price: 30, desc: '读数平视凹液面', effects: { mood: 4, bond: 3 }, descNormal: '量东西用的量杯', },
{ id: 'lamp', icon: '🔥', name: '酒精灯', category: 'gear', price: 22, desc: '用灯帽盖,不可以吹', effects: { mood: 5, bond: 2 }, descNormal: '暖光小台灯,晚上看书用', },
{ id: 'stand', icon: '🗄️', name: '铁架台', category: 'gear', price: 65, desc: '实验室的骨架', effects: { mood: 6, bond: 4 }, descNormal: '放小玩意儿的架子', },
{ id: 'condenser', icon: '🌀', name: '冷凝管', category: 'gear', price: 80, desc: '下进上出,别接反了', effects: { mood: 8, bond: 5 }, descNormal: '喝饮料用的吸管', },
{ id: 'crucible', icon: '🥣', name: '坩埚', category: 'gear', price: 45, desc: '耐高温,配坩埚钳', effects: { mood: 6, bond: 3 }, descNormal: '装小零食的小碗', },
{ id: 'funnel', icon: '⏳', name: '分液漏斗', category: 'gear', price: 55, desc: '下层从下口放,上层从上口倒', effects: { mood: 6, bond: 4 }, descNormal: '倒水不会洒的漏斗玩具', },
// 教材
{ id: 'book1', icon: '📗', name: '人教版九年级上册', category: 'book', price: 30, desc: '物质构成、化学方程式、碳与燃烧', effects: {}, exp: 40, descNormal: '图画很多,适合闲翻', },
{ id: 'book2', icon: '📘', name: '高中必修第一册', category: 'book', price: 50, desc: '离子反应、氧化还原、钠铝铁铜', effects: {}, exp: 80, descNormal: '一个个短故事,读到停不下来', },
{ id: 'book3', icon: '📙', name: '选择性必修1·化学反应原理', category: 'book', price: 70, desc: '电化学、速率与平衡', effects: {}, exp: 120, descNormal: '什么都能查到', },
{ id: 'book4', icon: '📕', name: '选择性必修3·有机化学基础', category: 'book', price: 75, desc: '烃、卤代烃、醇醛酸酯', effects: {}, exp: 130, descNormal: '跟着主角去冒险', },
{ id: 'book5', icon: '📚', name: '基础有机化学(邢大本)', category: 'book', price: 120, desc: '厚得能当砝码,但真的管用', effects: {}, exp: 200, descNormal: '很厚很重,但真的有用', },
{ id: 'book6', icon: '📖', name: '无机化学(武大版)', category: 'book', price: 100, desc: '元素化学的通行证', effects: {}, exp: 160, descNormal: '公式和例题都在里面', },
{ id: 'book7', icon: '🧠', name: '化学竞赛教程', category: 'book', price: 150, desc: '做一套,少活十年', effects: {}, exp: 260, descNormal: '越做越上头的谜题书', },
// 纪念样本
{ id: 'notebook', icon: '📓', name: '实验记录本', category: 'gift', price: 40, desc: '她喜欢在上面画画', effects: { mood: 10, bond: 3 }, descNormal: '记录每天的小事', },
{ id: 'bookmark', icon: '🍂', name: '叶脉书签', category: 'gift', price: 35, desc: 'NaOH 煮出来的,别碰手', effects: { mood: 8, bond: 3 }, descNormal: '叶子做的书签,压在书里', },
{ id: 'cucrystal', icon: '🟦', name: '硫酸铜晶体(养的)', category: 'gift', price: 60, desc: '蓝色,三天才长这么大', effects: { mood: 12, bond: 4 }, descNormal: '蓝色的小水晶摆件', },
{ id: 'chlorine', icon: '🧴', name: '玻封管(Cl₂)', category: 'gift', price: 80, desc: '离子键纪念品', effects: { mood: 15, bond: 5 }, descNormal: '通透的玻璃小瓶', },
{ id: 'cobaltglass', icon: '🟪', name: '蓝色钴玻璃', category: 'gift', price: 90, desc: '滤掉钠的黄光,才看得见钾的紫', effects: { mood: 12, bond: 6 }, descNormal: '阳光下会闪的蓝色玻璃球', },
{ id: 'benzene', icon: '💠', name: '六边形发夹', category: 'gift', price: 65, desc: '苯环形状,小碳同款', effects: { mood: 9, bond: 4 }, descNormal: '六边形的发夹,很衬她', },
{ id: 'copperwire', icon: '🧵', name: '铜导线', category: 'gift', price: 30, desc: '导电导热之王', effects: { mood: 6, bond: 3 }, descNormal: '手编的铜丝小环', },
{ id: 'pencil', icon: '✏️', name: '铅笔(石墨)', category: 'gift', price: 15, desc: '小铅的日常', effects: { mood: 5, bond: 2 }, descNormal: '2B 铅笔,写字画画都行', },
{ id: 'note', icon: '📝', name: '老师的批注', category: 'gift', price: 50, desc: '「此处配平有误」', effects: { mood: 7, bond: 4 }, descNormal: '「这次做得很好」', },
{ id: 'flamepin', icon: '🎇', name: '焰色反应标本', category: 'gift', price: 120, desc: '钠的黄色焰,装在小瓶里', effects: { mood: 20, bond: 8 }, descNormal: '橙色的小挂件,挂在包上' }
]
export function itemById(id: string): Item | undefined {
return ITEMS.find((i) => i.id === id)
}
// ---------------------------------------------------------------- 工作
export interface JobDef {
id: string
icon?: string
name: string
kind: 'work' | 'study' | 'play'
minutes: number
mood: number
coin: number
exp: number
electron: number
satiety: number
level: number
desc?: string
descNormal?: string
}
export const JOBS: JobDef[] = [
// ---- 工作(赚钱)
{ id: 'wash', icon: '🧪', name: '洗试管', kind: 'work', minutes: 10, coin: 45, exp: 10, electron: 8, satiety: 4, mood: 0, level: 1, desc: '把试管刷到能挂住水珠,是基本功。', descNormal: '把碗洗到能照出人影', },
{ id: 'label', icon: '🏷️', name: '贴标签', kind: 'work', minutes: 10, coin: 55, exp: 12, electron: 8, satiety: 4, mood: 0, level: 3, desc: '试剂瓶标签贴歪了就重贴。', descNormal: '给东西贴上标签,方便找', },
{ id: 'tidy', icon: '🗄️', name: '整理试剂柜', kind: 'work', minutes: 20, coin: 110, exp: 22, electron: 14, satiety: 7, mood: 0, level: 6, desc: '按酸性、碱性、氧化剂分开摆。', descNormal: '把柜子收拾整齐', },
{ id: 'duty', icon: '🧹', name: '实验室值日', kind: 'work', minutes: 25, coin: 160, exp: 30, electron: 18, satiety: 9, mood: -2, level: 10, desc: '擦台面、倒废液桶、检查水龙头。', descNormal: '打扫房间', },
{ id: 'solution', icon: '⚗️', name: '配溶液(接单)', kind: 'work', minutes: 30, coin: 240, exp: 44, electron: 22, satiety: 11, mood: 0, level: 15, desc: '按单子配浓度,误差要小于 0.1。', descNormal: '照着单子调饮料', },
{ id: 'distill', icon: '💧', name: '蒸馏水代灌', kind: 'work', minutes: 35, coin: 330, exp: 60, electron: 26, satiety: 13, mood: -2, level: 21, desc: '一桶一桶灌,手都酸了。', descNormal: '烧一壶开水', },
{ id: 'waste', icon: '🪣', name: '收废液', kind: 'work', minutes: 40, coin: 450, exp: 80, electron: 30, satiety: 15, mood: -4, level: 28, desc: '分类收集,别把强酸强碱混一起。', descNormal: '把垃圾都倒掉', },
{ id: 'soda', icon: '🥤', name: '自制汽水摆摊', kind: 'work', minutes: 45, coin: 600, exp: 105, electron: 34, satiety: 17, mood: 2, level: 36, desc: 'NaHCO₃ 加柠檬酸,气泡很足。', descNormal: '摆个小摊卖汽水', },
{ id: 'salt', icon: '🧂', name: '粗盐提纯(代工)', kind: 'work', minutes: 50, coin: 800, exp: 135, electron: 38, satiety: 19, mood: 0, level: 45, desc: '溶解、过滤、蒸发,一步都不能少。', descNormal: '做一道家常菜', },
{ id: 'oxygen', icon: '🫧', name: '制氧气卖', kind: 'work', minutes: 55, coin: 1050, exp: 170, electron: 42, satiety: 21, mood: 0, level: 55, desc: 'KMnO₄ 加热,收集满一瓶就换。', descNormal: '整理阳台上的花草', },
{ id: 'electro', icon: '⚡', name: '电解水', kind: 'work', minutes: 60, coin: 1350, exp: 210, electron: 48, satiety: 24, mood: -2, level: 66, desc: '阴阳两极冒气泡,氢氧二比一。', descNormal: '修一下漏水的水管', },
{ id: 'drawing', icon: '✏️', name: '代画装置图', kind: 'work', minutes: 65, coin: 1700, exp: 255, electron: 52, satiety: 26, mood: 0, level: 78, desc: '比例、标注、箭头,一个都不能错。', descNormal: '在纸上画点小涂鸦', },
{ id: 'flame', icon: '🎇', name: '焰色反应接单', kind: 'work', minutes: 70, coin: 2100, exp: 305, electron: 56, satiety: 28, mood: 0, level: 90, desc: '钠黄、钾紫(要隔着钴玻璃看)。', descNormal: '在街头表演个小节目', },
{ id: 'crystal', icon: '💎', name: '养晶体(三天)', kind: 'work', minutes: 80, coin: 2600, exp: 360, electron: 60, satiety: 32, mood: 4, level: 103, desc: '过饱和溶液慢慢长,得等三天。', descNormal: '养一盆多肉', },
// ---- 学习(涨经验)
{ id: 'notes', icon: '📓', name: '抄笔记', kind: 'study', minutes: 15, coin: 0, exp: 30, electron: 6, satiety: 3, mood: 0, level: 1, desc: '工整一点,自己也能看懂。', descNormal: '把课堂笔记整理一遍', },
{ id: 'table', icon: '📋', name: '背元素周期表', kind: 'study', minutes: 15, coin: 0, exp: 40, electron: 6, satiety: 3, mood: 0, level: 3, desc: '前二十号,横着背竖着背。', descNormal: '背一会儿单词', },
{ id: 'valency', icon: '🔢', name: '背化合价', kind: 'study', minutes: 20, coin: 0, exp: 60, electron: 8, satiety: 4, mood: 0, level: 6, desc: '口诀念顺了就不容易忘。', descNormal: '背几条常用公式', },
{ id: 'readbook', icon: '📖', name: '看教材', kind: 'study', minutes: 25, coin: 0, exp: 90, electron: 10, satiety: 5, mood: 2, level: 10, desc: '把每一章的实验都读一遍。', descNormal: '看会儿书', },
{ id: 'askteacher', icon: '🙋', name: '问老师题', kind: 'study', minutes: 20, coin: 20, exp: 110, electron: 10, satiety: 4, mood: 3, level: 15, desc: '别怕问,问完要记住。', descNormal: '去请教一个问题', },
{ id: 'ionic', icon: '✍️', name: '背离子方程式', kind: 'study', minutes: 30, coin: 0, exp: 150, electron: 12, satiety: 6, mood: 0, level: 21, desc: '写、配平、标状态,一步不落。', descNormal: '写一篇小作文', },
{ id: 'drill', icon: '🧮', name: '刷计算题', kind: 'study', minutes: 35, coin: 0, exp: 200, electron: 16, satiety: 8, mood: -4, level: 28, desc: '摩尔、浓度、产率,全都算一遍。', descNormal: '刷一页练习题', },
{ id: 'fix', icon: '📚', name: '整理错题本', kind: 'study', minutes: 40, coin: 0, exp: 260, electron: 18, satiety: 9, mood: -2, level: 36, desc: '错一次没关系,错两次就罚抄。', descNormal: '把错题重新做一遍', },
{ id: 'lab', icon: '🔬', name: '模拟实验操作', kind: 'study', minutes: 45, coin: 0, exp: 330, electron: 20, satiety: 10, mood: 0, level: 45, desc: '按步骤走,注意安全。', descNormal: '做个小手工', },
{ id: 'xingda', icon: '📕', name: '啃邢大本', kind: 'study', minutes: 60, coin: 0, exp: 460, electron: 28, satiety: 14, mood: -6, level: 55, desc: '厚厚的有机化学,一天十页。', descNormal: '读几页课外书', },
{ id: 'contest', icon: '🏅', name: '冲竞赛集训', kind: 'study', minutes: 75, coin: 0, exp: 640, electron: 36, satiety: 18, mood: -8, level: 66, desc: '一整套卷子,做完手抖。', descNormal: '刷一套难一点的题', },
// ---- 玩耍(放松)
{ id: 'walk', icon: '🚶', name: '散步', kind: 'play', minutes: 10, coin: 0, exp: 8, electron: 4, satiety: 3, mood: 12, level: 1, desc: '绕实验室走两圈,放松一下。', descNormal: '出门走两圈', },
{ id: 'anime', icon: '📺', name: '看动画片', kind: 'play', minutes: 20, coin: 0, exp: 12, electron: 6, satiety: 4, mood: 20, level: 2, desc: '泡一杯热饮,靠着椅子。', descNormal: '看一集动画', },
{ id: 'game', icon: '🎮', name: '玩小游戏', kind: 'play', minutes: 25, coin: -10, exp: 15, electron: 8, satiety: 5, mood: 26, level: 4, desc: '打两把就收手……大概。', descNormal: '玩一会儿小游戏', },
{ id: 'draw', icon: '🎨', name: '随手画画', kind: 'play', minutes: 30, coin: 0, exp: 24, electron: 10, satiety: 6, mood: 34, level: 7, desc: '随手画点小东西。', descNormal: '随手画点东西' }
]
/** ---------------------------------------------------------------- 动作与结算 */
export interface ActionResult {
ok: boolean
message: string
}
export interface PetConfig {
scale: number
theme: 'day' | 'night'
accent: string
eyeFollow: boolean
autoBuy: boolean
sleepAt: string
wakeAt: string
eventsEnabled: boolean
currentSkin: string
profile: string
flavorMode: 'auto' | 'chemistry' | 'normal'
/** 底栏图标:tab id -> 'sticker:1.0.png' 或 'img:icons/xxx.png' */
tabIcons: Record<string, string>
/** 歌词浮窗:底色 / 文字色 / 描边色 / 字号 */
lyricBg: string
lyricColor: string
lyricOutline: string
lyricSize: number
cropTop: number
cropBottom: number
cropLeft: number
cropRight: number
topmost: boolean
clickThrough: boolean
panelPos?: { x: number; y: number }
}
export const DESIGN_W = 200
export const DESIGN_H = 470
export const DEFAULT_CONFIG: PetConfig = {
scale: 1,
theme: 'night',
accent: '#ffd54a',
eyeFollow: false,
autoBuy: false,
sleepAt: '23:30',
wakeAt: '07:30',
eventsEnabled: true,
currentSkin: 'xiaona',
profile: '',
flavorMode: 'auto',
tabIcons: {},
lyricBg: 'rgba(16,20,30,0.55)',
lyricColor: '#ffffff',
lyricOutline: '#000000',
lyricSize: 20,
cropTop: 0,
cropBottom: 0,
cropLeft: 0,
cropRight: 0,
topmost: true,
clickThrough: false
}
export function applyElapsed(save: PetSave, seconds: number, now = Date.now()): void {
if (seconds <= 0) return
if (!save.counters) save.counters = {}
const m = seconds / 60
save.playtimeMs += Math.max(0, seconds) * 1000
const s = save.stats
const asleep = save.sleeping
const slow = asleep ? 0.5 : 1
s.satiety = clamp(s.satiety - DECAY_PER_MIN.satiety * m * slow)
s.paraffin = clamp(s.paraffin - DECAY_PER_MIN.paraffin * m * slow)
const oxRate = DECAY_PER_MIN.oxidation * (s.paraffin < 20 ? 2 : 1) * slow
s.oxidation = clamp(s.oxidation + oxRate * m)
if (asleep) {
s.electron = clamp(s.electron + 0.35 * m)
s.mood = clamp(s.mood + 0.05 * m)
} else {
s.electron = clamp(s.electron - DECAY_PER_MIN.electron * m)
}
const moodRate = DECAY_PER_MIN.mood * (s.satiety < 20 || s.oxidation > 70 ? 1.5 : 1)
if (!asleep) s.mood = clamp(s.mood - moodRate * m)
if (save.job && now >= save.job.endAt) {
const job = save.job
const mult = rewardMultiplier(levelOf(save.exp))
save.money += Math.round(job.coin * mult)
save.exp += Math.round(job.exp * mult)
s.electron = clamp(s.electron - job.electron)
s.satiety = clamp(s.satiety - job.satiety)
s.mood = clamp(s.mood + (job.mood ?? 0))
save.jobsDone += 1
save.counters[`job:${job.id}`] = (save.counters[`job:${job.id}`] ?? 0) + 1
save.job = null
}
}
/** 普通文本模式允许的等级上限(大于化学的 118,便于倍率计算) */
export const LEVEL_CAP_NORMAL = 300
/** 化学文本模式显示上限 */
export const LEVEL_CAP_CHEM = 118
/** 升到 level+1 需要的经验:随等级递增,避免前期飞快升级 */
export function expForNext(level: number): number {
return 50 + (Math.max(1, level) - 1) * 15
}
/** 累计到 level 级总共需要的经验 */
export function expUntil(level: number): number {
let sum = 0
for (let l = 1; l < level; l++) sum += expForNext(l)
return sum
}
export function levelOf(exp: number): number {
let lv = 1
let acc = 0
while (lv < 500) {
const need = expForNext(lv)
if (exp < acc + need) break
acc += need
lv += 1
}
return lv
}
/** 等级越高,任务收益倍率越高(每 5 级 +5%,封顶 2.0) */
export function rewardMultiplier(level: number): number {
return Math.min(2, 1 + Math.floor(level / 5) * 0.05)
}
export function expProgress(exp: number): { level: number; cur: number; need: number } {
const level = levelOf(exp)
let acc = 0
for (let l = 1; l < level; l++) acc += expForNext(l)
return { level, cur: exp - acc, need: expForNext(level) }
}
export function moodOf(stats: Stats): string {
if (stats.electron < 15) return 'surprised'
if (stats.oxidation > 75) return 'angry'
if (stats.mood < 30) return 'sad'
if (stats.mood > 70 && stats.satiety > 40) return 'happy'
return 'neutral'
}
export function statusText(s: Stats, job: Job | null): string {
if (job) return `打工中 · ${job.name}`
if (s.electron < 15) return '有点晕正电荷…(Na⁺ 态)'
if (s.oxidation > 75) return '表面发暗了,要抛光'
if (s.satiety < 20) return '肚子在叫'
if (s.paraffin < 20) return '石蜡油快没了'
if (s.mood > 75) return '心情很好'
return '还好'
}
/** 面板里显示的「每分钟变化」 */
export function tickRates(s: Stats): Record<StatKey, number> {
const oxRate = DECAY_PER_MIN.oxidation * (s.paraffin < 20 ? 2 : 1)
const moodRate = DECAY_PER_MIN.mood * (s.satiety < 20 || s.oxidation > 70 ? 1.5 : 1)
return {
satiety: -DECAY_PER_MIN.satiety / 60,
paraffin: -DECAY_PER_MIN.paraffin / 60,
electron: -DECAY_PER_MIN.electron / 60,
mood: -moodRate / 60,
oxidation: oxRate / 60,
bond: 0
}
}
export function buy(save: PetSave, itemId: string, qty = 1): ActionResult {
const item = itemById(itemId)
if (!item) return { ok: false, message: '没有这件商品' }
const n = Math.max(1, Math.floor(qty))
const cost = item.price * n
if (save.money < cost) return { ok: false, message: '金币不够啦' }
save.money -= cost
save.inventory[itemId] = (save.inventory[itemId] ?? 0) + n
return { ok: true, message: `买了 ${n} 个${item.name}` }
}
export function useItem(save: PetSave, itemId: string): ActionResult {
const item = itemById(itemId)
if (!item) return { ok: false, message: '没有这件商品' }
const count = save.inventory[itemId] ?? 0
if (count <= 0) return { ok: false, message: '背包里没有了' }
save.inventory[itemId] = count - 1
const factor = item.liked ? 1.2 : 1
for (const [k, v] of Object.entries(item.effects)) {
save.stats[k as StatKey] = clamp(save.stats[k as StatKey] + Math.round(v * factor))
}
save.exp += item.exp ?? Math.min(15, Math.max(2, Math.round(item.price / 4)))
return {
ok: true,
message: item.liked ? `用了 ${item.name}(她很喜欢!效果 +20%)` : `用了 ${item.name}`
}
}
/** 单个任务允许的奖励倍率上限:等级越高倍率越多,但增长很慢 */
export function jobMaxMult(jobLevel: number, charLevel: number): number {
return Math.max(1, Math.min(10, Math.floor(charLevel / Math.max(1, jobLevel))))
}
export function startJob(save: PetSave, jobId: string, now = Date.now(), mult = 1): ActionResult {
if (save.job) return { ok: false, message: '已经在打工了' }
const def = JOBS.find((j) => j.id === jobId)
if (!def) return { ok: false, message: '没有这份工作' }
const lv = levelOf(save.exp)
if (lv < def.level) return { ok: false, message: `需要 Lv.${def.level}` }
const m = Math.max(1, Math.min(jobMaxMult(def.level, lv), Math.round(mult)))
save.job = {
id: def.id,
name: def.name,
kind: def.kind,
startAt: now,
mood: def.mood * m,
endAt: now + def.minutes * 60_000,
coin: def.coin * m,
electron: def.electron * m,
satiety: def.satiety * m,
exp: def.exp * m,
mult: m
}
return { ok: true, message: `开始${def.name}(×${m})` }
}
export function rest(save: PetSave, now = Date.now()): ActionResult {
const until = save.cooldowns.rest ?? 0
if (now < until) return { ok: false, message: `还要等 ${Math.ceil((until - now) / 1000)} 秒` }
save.stats.electron = clamp(save.stats.electron + 25)
save.cooldowns.rest = now + 180_000
return { ok: true, message: '休息了一会儿' }
}
export function petHead(save: PetSave, now = Date.now()): ActionResult {
const until = save.cooldowns.pet ?? 0
if (now < until) return { ok: false, message: '再摸就秃了' }
save.stats.mood = clamp(save.stats.mood + 4)
save.stats.bond = clamp(save.stats.bond + 1)
save.cooldowns.pet = now + 20_000
return { ok: true, message: '嘿嘿' }
}
+63
View File
@@ -0,0 +1,63 @@
/** 共享类型:主进程与渲染层都可能用到 */
export type AvatarType = 'live2d' | 'sprite' | 'static'
export interface AvatarSpec {
/** live2d: .model3.json;sprite: atlas.json;static: png */
type: AvatarType
entry: string
/** 相对窗口高度的缩放系数,1 = 撑满高度 */
scale?: number
/** 竖直偏移(0~1,相对窗口高度,正数向下) */
offsetY?: number
/**
* 模型校准值(Live2D 用)。
* Cubism 的画布尺寸常常和角色实际占位差很远,所以第一次导入时量一组基准值,
* 之后按窗口高度等比缩放即可。
*/
calibration?: {
/** 基准窗口高度下使用的绝对缩放 */
scale: number
/** 角色水平中心,模型本地坐标 */
centerX: number
/** 角色脚底,模型本地坐标 */
bottom: number
/** 量这组值时窗口的 CSS 高度 */
refHeight: number
}
}
export interface SpriteState {
image: string
frames: number
fps: number
loop?: boolean
}
/** 皮肤清单:Live2D 与 Q 版序列帧共用同一份结构 */
export interface SkinManifest {
id: string
name: string
version: string
author?: string
/** chemistry=化学化拟人(小钠等预设);normal=普通桌宠(导入角色) */
flavor?: string
avatar: AvatarSpec
/** 逻辑动作名 -> 模型内动作组名 */
motions?: Record<string, string>
/** 逻辑表情名 -> 模型内表情名(null 表示无表情,回到默认) */
expressions?: Record<string, string | null>
/** Cubism 口型参数组名(预留实时字幕/语音同步) */
lipsync?: string
/** Q 版序列帧的状态表 */
states?: Record<string, SpriteState>
/** 气泡锚点(0~1) */
bubble?: { x: number; y: number }
}
export interface AvatarCapabilities {
expressions: string[]
motions: string[]
lipsync: boolean
hitTest: boolean
}