Lashtw commited on
Commit
85d74b8
·
verified ·
1 Parent(s): 3de7df8

Upload 10 files

Browse files
Files changed (5) hide show
  1. css/base.css +13 -3
  2. css/game.css +11 -6
  3. js/db.js +28 -10
  4. js/game.js +69 -22
  5. js/util.js +9 -1
css/base.css CHANGED
@@ -89,10 +89,10 @@ textarea.input { min-height: 120px; resize: vertical; font-family: ui-monospace,
89
 
90
  /* ---------- 卡片 ---------- */
91
  .card {
92
- background: linear-gradient(180deg, rgba(31, 42, 68, .75), rgba(23, 32, 54, .75));
 
93
  border: 1px solid var(--line); border-radius: var(--radius);
94
  padding: 18px; box-shadow: var(--shadow);
95
- backdrop-filter: blur(8px);
96
  }
97
  .card h2, .card h3 { margin: 0 0 10px; }
98
  .card h2 { font-size: 18px; }
@@ -128,9 +128,19 @@ textarea.input { min-height: 120px; resize: vertical; font-family: ui-monospace,
128
  /* ---------- Modal ---------- */
129
  .modal-back {
130
  position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center;
131
- background: rgba(5, 8, 15, .7); backdrop-filter: blur(4px); opacity: 0; transition: opacity .2s; padding: 16px;
132
  }
133
  .modal-back.show { opacity: 1; }
 
 
 
 
 
 
 
 
 
 
134
  .modal {
135
  position: relative; width: min(560px, 100%); max-height: 92vh; overflow: auto;
136
  background: linear-gradient(180deg, var(--bg-2), var(--bg-1)); border: 1px solid var(--line);
 
89
 
90
  /* ---------- 卡片 ---------- */
91
  .card {
92
+ /* 效能:不使用 backdrop-filter(多張卡片疊加模糊會讓 GPU 每幀重算),改用較不透明背景 */
93
+ background: linear-gradient(180deg, rgba(31, 42, 68, .92), rgba(23, 32, 54, .92));
94
  border: 1px solid var(--line); border-radius: var(--radius);
95
  padding: 18px; box-shadow: var(--shadow);
 
96
  }
97
  .card h2, .card h3 { margin: 0 0 10px; }
98
  .card h2 { font-size: 18px; }
 
128
  /* ---------- Modal ---------- */
129
  .modal-back {
130
  position: fixed; inset: 0; z-index: 1000; display: flex; align-items: center; justify-content: center;
131
+ background: rgba(5, 8, 15, .86); opacity: 0; transition: opacity .2s; padding: 16px;
132
  }
133
  .modal-back.show { opacity: 1; }
134
+
135
+ /* Modal(測驗)開啟時,暫停背景所有無限循環動畫,降低 GPU 負擔 */
136
+ body.modal-open #viewApp *,
137
+ body.modal-open #viewApp *::before,
138
+ body.modal-open #viewApp *::after { animation-play-state: paused !important; }
139
+
140
+ /* 使用者系統設定「減少動態效果」時,關閉循環動畫 */
141
+ @media (prefers-reduced-motion: reduce) {
142
+ *, *::before, *::after { animation-iteration-count: 1 !important; transition-duration: .01ms !important; }
143
+ }
144
  .modal {
145
  position: relative; width: min(560px, 100%); max-height: 92vh; overflow: auto;
146
  background: linear-gradient(180deg, var(--bg-2), var(--bg-1)); border: 1px solid var(--line);
css/game.css CHANGED
@@ -21,7 +21,7 @@
21
  /* 頂部資源列 */
22
  .topbar {
23
  position: sticky; top: 0; z-index: 40; display: flex; align-items: center; gap: 14px; justify-content: space-between;
24
- padding: 12px 20px; background: rgba(11, 15, 26, .82); backdrop-filter: blur(12px); border-bottom: 1px solid var(--line);
25
  }
26
  .mode-banner:not(.hidden) ~ #viewApp .topbar { top: 35px; }
27
  .res-group { display: flex; gap: 10px; flex-wrap: wrap; }
@@ -68,7 +68,7 @@
68
  .spot-node {
69
  position: relative; width: 48px; height: 48px; border-radius: 50%;
70
  display: flex; align-items: center; justify-content: center; font-size: 24px;
71
- background: rgba(15,23,42,.85); backdrop-filter: blur(8px);
72
  border: 2px solid rgba(255,255,255,.2); box-shadow: 0 6px 16px rgba(0,0,0,.6);
73
  transition: all .25s ease;
74
  }
@@ -84,12 +84,17 @@
84
 
85
  .map-spot.ready .spot-node {
86
  border-color: var(--gold); background: rgba(245,196,81,.2);
87
- animation: spotPulse 1.6s infinite alternate ease-in-out;
 
 
 
 
 
88
  }
89
  .map-spot.ready .spot-label { border-color: var(--gold); color: var(--gold); }
90
  @keyframes spotPulse {
91
- 0% { box-shadow: 0 0 0 0 rgba(245,196,81,.6); transform: scale(1); }
92
- 100% { box-shadow: 0 0 0 10px rgba(245,196,81,0); transform: scale(1.05); }
93
  }
94
 
95
  .map-spot.active .spot-node {
@@ -276,7 +281,7 @@
276
  .user-box .mute { display: none; }
277
  .tabs {
278
  position: fixed; bottom: 0; left: 0; right: 0; z-index: 45; padding: 8px 8px calc(8px + env(safe-area-inset-bottom));
279
- background: rgba(11,15,26,.95); backdrop-filter: blur(12px); border-top: 1px solid var(--line); justify-content: space-around; gap: 4px;
280
  }
281
  .tab { flex: 1; flex-direction: column; gap: 0; padding: 4px; min-height: 52px; font-size: 18px; border: 0; }
282
  .tab span { font-size: 11px; }
 
21
  /* 頂部資源列 */
22
  .topbar {
23
  position: sticky; top: 0; z-index: 40; display: flex; align-items: center; gap: 14px; justify-content: space-between;
24
+ padding: 12px 20px; background: rgba(11, 15, 26, .95); border-bottom: 1px solid var(--line);
25
  }
26
  .mode-banner:not(.hidden) ~ #viewApp .topbar { top: 35px; }
27
  .res-group { display: flex; gap: 10px; flex-wrap: wrap; }
 
68
  .spot-node {
69
  position: relative; width: 48px; height: 48px; border-radius: 50%;
70
  display: flex; align-items: center; justify-content: center; font-size: 24px;
71
+ background: rgba(15,23,42,.9);
72
  border: 2px solid rgba(255,255,255,.2); box-shadow: 0 6px 16px rgba(0,0,0,.6);
73
  transition: all .25s ease;
74
  }
 
84
 
85
  .map-spot.ready .spot-node {
86
  border-color: var(--gold); background: rgba(245,196,81,.2);
87
+ }
88
+ /* 效能:光圈只動 transform / opacity(GPU 合成),不每幀重繪 box-shadow */
89
+ .map-spot.ready .spot-node::after {
90
+ content: ''; position: absolute; inset: -2px; border-radius: 50%;
91
+ border: 2px solid rgba(245,196,81,.7); pointer-events: none;
92
+ animation: spotPulse 1.6s infinite ease-out;
93
  }
94
  .map-spot.ready .spot-label { border-color: var(--gold); color: var(--gold); }
95
  @keyframes spotPulse {
96
+ 0% { transform: scale(1); opacity: .9; }
97
+ 100% { transform: scale(1.45); opacity: 0; }
98
  }
99
 
100
  .map-spot.active .spot-node {
 
281
  .user-box .mute { display: none; }
282
  .tabs {
283
  position: fixed; bottom: 0; left: 0; right: 0; z-index: 45; padding: 8px 8px calc(8px + env(safe-area-inset-bottom));
284
+ background: rgba(11,15,26,.97); border-top: 1px solid var(--line); justify-content: space-around; gap: 4px;
285
  }
286
  .tab { flex: 1; flex-direction: column; gap: 0; padding: 4px; min-height: 52px; font-size: 18px; border: 0; }
287
  .tab span { font-size: 11px; }
js/db.js CHANGED
@@ -67,7 +67,10 @@ class FirebaseBackend {
67
  if (adm && adm.exists()) role = 'teacher';
68
  else {
69
  const st = await this.F.getDoc(this.d('students', u.uid)).catch(() => null);
70
- if (st && st.exists()) role = 'student';
 
 
 
71
  }
72
  this.user = { uid: u.uid, email: u.email, role };
73
  cb(this.user);
@@ -93,6 +96,11 @@ class FirebaseBackend {
93
 
94
  // ----- 學生 -----
95
  async getStudent(uid) {
 
 
 
 
 
96
  const s = await this.F.getDoc(this.d('students', uid));
97
  return s.exists() ? { uid, ...s.data() } : null;
98
  }
@@ -222,17 +230,27 @@ class FirebaseBackend {
222
  await batch.commit();
223
  }
224
 
225
- async listGiftLog(code) {
226
- const q = this.F.query(this.c('giftLog'), this.F.where('classCode', '==', normCode(code)));
227
- const snap = await this.F.getDocs(q);
228
- return snap.docs.map((x) => ({ id: x.id, ...x.data() })).sort((a, b) => b.at - a.at);
 
 
 
 
 
 
 
 
 
 
 
 
229
  }
230
 
231
- async listAttempts(code) {
232
- const q = this.F.query(this.c('attempts'), this.F.where('classCode', '==', normCode(code)));
233
- const snap = await this.F.getDocs(q);
234
- return snap.docs.map((x) => ({ id: x.id, ...x.data() })).sort((a, b) => b.at - a.at);
235
- }
236
  }
237
 
238
  // -------------------------------------------------------------
 
67
  if (adm && adm.exists()) role = 'teacher';
68
  else {
69
  const st = await this.F.getDoc(this.d('students', u.uid)).catch(() => null);
70
+ if (st && st.exists()) {
71
+ role = 'student';
72
+ this._stCache = { uid: u.uid, data: st.data() }; // 給 getStudent 用,省一次讀取
73
+ }
74
  }
75
  this.user = { uid: u.uid, email: u.email, role };
76
  cb(this.user);
 
96
 
97
  // ----- 學生 -----
98
  async getStudent(uid) {
99
+ if (this._stCache && this._stCache.uid === uid) {
100
+ const data = this._stCache.data;
101
+ this._stCache = null; // 只用一次,之後一律讀最新資料
102
+ return { uid, ...data };
103
+ }
104
  const s = await this.F.getDoc(this.d('students', uid));
105
  return s.exists() ? { uid, ...s.data() } : null;
106
  }
 
230
  await batch.commit();
231
  }
232
 
233
+ // 只取最新 N 筆(每筆文件 = 1 次讀取)。需要複合索引 classCode(↑) + at(↓);
234
+ // 第一次執行時 Console 會印出建立索引的連結,點一下即可。索引建好前暫時退回舊查詢。
235
+ async _latestByClass(col, code, n) {
236
+ const F = this.F;
237
+ try {
238
+ const q = F.query(this.c(col), F.where('classCode', '==', normCode(code)), F.orderBy('at', 'desc'), F.limit(n));
239
+ const snap = await F.getDocs(q);
240
+ return snap.docs.map((x) => ({ id: x.id, ...x.data() }));
241
+ } catch (e) {
242
+ if ((e?.code || '').includes('failed-precondition')) {
243
+ console.error(`[db] ${col} 需要建立複合索引才能省讀取額度,請點下方連結建立:`, e.message);
244
+ const snap = await F.getDocs(F.query(this.c(col), F.where('classCode', '==', normCode(code))));
245
+ return snap.docs.map((x) => ({ id: x.id, ...x.data() })).sort((a, b) => b.at - a.at).slice(0, n);
246
+ }
247
+ throw e;
248
+ }
249
  }
250
 
251
+ async listGiftLog(code) { return this._latestByClass('giftLog', code, 100); }
252
+
253
+ async listAttempts(code) { return this._latestByClass('attempts', code, 100); }
 
 
254
  }
255
 
256
  // -------------------------------------------------------------
js/game.js CHANGED
@@ -18,6 +18,16 @@ let myGifts = [];
18
  let buyMode = 1; // 1, 10, 'max'
19
  let loopTimer = null, saveTimer = null, luckyTimer = null;
20
 
 
 
 
 
 
 
 
 
 
 
21
  // ===================== 初始化 =====================
22
  async function init() {
23
  db = await getDB();
@@ -40,7 +50,15 @@ async function init() {
40
  });
41
  });
42
 
43
- bind($('#btnLogout'), 'click', () => db.logout());
 
 
 
 
 
 
 
 
44
 
45
  db.onAuth(async (u) => {
46
  user = u;
@@ -90,27 +108,52 @@ async function loadStudentData() {
90
  switchTab('build');
91
  }
92
 
93
- async function save() {
94
- if (!user || !game) return;
95
- try {
96
- await db.saveGame(user.uid, { game, progress, stats });
97
- } catch (e) { console.warn('自動存檔失敗', e); }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98
  }
99
 
100
  // ===================== 核心迴圈 =====================
101
  function startLoop() {
102
  stopLoop();
 
103
  loopTimer = setInterval(() => {
104
- advance(game, dState);
 
 
 
105
  renderRes();
106
  updateBuildBtns();
107
  updateLucky();
108
- }, 100); // 10fps UI
109
- saveTimer = setInterval(save, 30000); // 30s 存檔
 
110
  }
111
  function stopLoop() {
112
  clearInterval(loopTimer); clearInterval(saveTimer);
113
- clearTimeout(luckyTimer);
 
114
  }
115
 
116
  function updateHeader() {
@@ -119,11 +162,11 @@ function updateHeader() {
119
  renderRes();
120
  }
121
  function renderRes() {
122
- if (!game) return;
123
- $('#valCoins').textContent = fmt(game.coins);
124
- $('#valPerSec').textContent = fmt(totalProd(game, dState));
125
- $('#valBp').textContent = fmt(game.blueprints);
126
- $('#valMult').textContent = 'x' + fmt(dState.globalMult);
127
  }
128
 
129
  function flyNumber(x, y, text) {
@@ -321,6 +364,7 @@ function renderBuild() {
321
  void $(`#bcard_${id}`).offsetWidth; // trigger reflow
322
  $(`#bcard_${id}`).classList.add('pulse');
323
  renderBuild(); // 懶得局部更新了,直接重繪整個 pane
 
324
  } else {
325
  toast('糧草不足,請巡營催糧或稍候輜重!', 'error');
326
  }
@@ -336,6 +380,7 @@ function renderBuild() {
336
  st.star += 1;
337
  toast(`${BUILDINGS.find(x=>x.id===id).name} 升星成功!產量 x${mult}`, 'success');
338
  renderBuild();
 
339
  } else {
340
  toast('小金虎符不足(前往軍機策驗獲取!)', 'error');
341
  }
@@ -349,18 +394,20 @@ function updateBuildBtns() {
349
  const id = btn.dataset.bid;
350
  const bDef = BUILDINGS.find(x => x.id === id);
351
  const st = game.buildings[id];
 
352
  let amt = buyMode;
353
  if (buyMode === 'max') amt = Math.max(1, maxAffordable(bDef, st.lv, game.coins));
354
  const cost = bulkCost(bDef, st.lv, amt);
355
- btn.querySelector('.up-amt').textContent = amt;
356
- btn.querySelector('.up-cost').textContent = fmt(cost);
357
- btn.disabled = game.coins < cost;
 
358
  });
359
  $$('.btn-star').forEach(btn => {
360
- const id = btn.dataset.bid;
361
- const st = game.buildings[id];
362
- const cost = starCost(st.star);
363
- btn.disabled = game.blueprints < cost;
364
  });
365
  }
366
 
 
18
  let buyMode = 1; // 1, 10, 'max'
19
  let loopTimer = null, saveTimer = null, luckyTimer = null;
20
 
21
+ // ----- 效能與 Firestore 寫入量控制 -----
22
+ const UI_TICK_MS = 200; // 畫面更新頻率(5fps 對數字跳動已足夠)
23
+ const AUTO_SAVE_MS = 3 * 60 * 1000; // 前景定時存檔:每 3 分鐘
24
+ const DIRTY_SAVE_DELAY_MS = 10 * 1000; // 升級等操作後 10 秒合併存檔
25
+ const MIN_LEAVE_SAVE_GAP_MS = 20 * 1000; // 切到背景時,距上次存檔超過 20 秒才補存
26
+ let dirtyTimer = null, lastSaveAt = 0, saving = null, resave = false;
27
+
28
+ // 只在內容真的改變時才寫 DOM,避免無謂的重排版
29
+ function setText(el, s) { if (el && el.textContent !== s) el.textContent = s; }
30
+
31
  // ===================== 初始化 =====================
32
  async function init() {
33
  db = await getDB();
 
50
  });
51
  });
52
 
53
+ bind($('#btnLogout'), 'click', () => withLoading($('#btnLogout'), async () => {
54
+ await save(); // 登出前先存檔
55
+ stopLoop();
56
+ await db.logout();
57
+ }));
58
+
59
+ // 切到背景 / 關閉分頁時補存(取代高頻率定時存檔)
60
+ bind(document, 'visibilitychange', () => { if (document.hidden) saveOnLeave(); });
61
+ bind(window, 'pagehide', saveOnLeave);
62
 
63
  db.onAuth(async (u) => {
64
  user = u;
 
108
  switchTab('build');
109
  }
110
 
111
+ // 存檔:同一時間只會有一個寫入;寫入中又有新請求時,結束後再補存一次(確保最新資料寫入)
112
+ function save() {
113
+ if (!user || !game || user.role !== 'student') return Promise.resolve();
114
+ if (saving) { resave = true; return saving; }
115
+ clearTimeout(dirtyTimer); dirtyTimer = null;
116
+ lastSaveAt = Date.now();
117
+ saving = db.saveGame(user.uid, { game, progress, stats })
118
+ .catch((e) => console.warn('自動存檔失敗', e))
119
+ .finally(() => {
120
+ saving = null;
121
+ if (resave) { resave = false; save(); }
122
+ });
123
+ return saving;
124
+ }
125
+
126
+ // 標記「有重要變動」:10 秒內的多次操作合併成一次寫入
127
+ function markDirty() {
128
+ if (dirtyTimer) return;
129
+ dirtyTimer = setTimeout(() => { dirtyTimer = null; save(); }, DIRTY_SAVE_DELAY_MS);
130
+ }
131
+
132
+ function saveOnLeave() {
133
+ if (!user || !game || user.role !== 'student') return;
134
+ if (dirtyTimer || Date.now() - lastSaveAt > MIN_LEAVE_SAVE_GAP_MS) save();
135
  }
136
 
137
  // ===================== 核心迴圈 =====================
138
  function startLoop() {
139
  stopLoop();
140
+ lastSaveAt = Date.now();
141
  loopTimer = setInterval(() => {
142
+ if (!game || !dState) return;
143
+ advance(game, dState); // 數值照實際經過時間推進,少畫幾幀不影響收益
144
+ // 分頁在背景、或正在作答(modal 開啟)時,不更新被遮住的畫面
145
+ if (document.hidden || document.body.classList.contains('modal-open')) return;
146
  renderRes();
147
  updateBuildBtns();
148
  updateLucky();
149
+ }, UI_TICK_MS);
150
+ // 只在前景定時存檔;背景分頁靠 visibilitychange 補存 + 下次登入的離線結算
151
+ saveTimer = setInterval(() => { if (!document.hidden) save(); }, AUTO_SAVE_MS);
152
  }
153
  function stopLoop() {
154
  clearInterval(loopTimer); clearInterval(saveTimer);
155
+ clearTimeout(luckyTimer); clearTimeout(dirtyTimer);
156
+ loopTimer = saveTimer = luckyTimer = dirtyTimer = null;
157
  }
158
 
159
  function updateHeader() {
 
162
  renderRes();
163
  }
164
  function renderRes() {
165
+ if (!game || !dState) return;
166
+ setText($('#valCoins'), fmt(game.coins));
167
+ setText($('#valPerSec'), fmt(totalProd(game, dState)));
168
+ setText($('#valBp'), fmt(game.blueprints));
169
+ setText($('#valMult'), 'x' + fmt(dState.globalMult));
170
  }
171
 
172
  function flyNumber(x, y, text) {
 
364
  void $(`#bcard_${id}`).offsetWidth; // trigger reflow
365
  $(`#bcard_${id}`).classList.add('pulse');
366
  renderBuild(); // 懶得局部更新了,直接重繪整個 pane
367
+ markDirty();
368
  } else {
369
  toast('糧草不足,請巡營催糧或稍候輜重!', 'error');
370
  }
 
380
  st.star += 1;
381
  toast(`${BUILDINGS.find(x=>x.id===id).name} 升星成功!產量 x${mult}`, 'success');
382
  renderBuild();
383
+ markDirty();
384
  } else {
385
  toast('小金虎符不足(前往軍機策驗獲取!)', 'error');
386
  }
 
394
  const id = btn.dataset.bid;
395
  const bDef = BUILDINGS.find(x => x.id === id);
396
  const st = game.buildings[id];
397
+ if (!bDef || !st) return;
398
  let amt = buyMode;
399
  if (buyMode === 'max') amt = Math.max(1, maxAffordable(bDef, st.lv, game.coins));
400
  const cost = bulkCost(bDef, st.lv, amt);
401
+ setText(btn.querySelector('.up-amt'), String(amt));
402
+ setText(btn.querySelector('.up-cost'), fmt(cost));
403
+ const dis = game.coins < cost;
404
+ if (btn.disabled !== dis) btn.disabled = dis;
405
  });
406
  $$('.btn-star').forEach(btn => {
407
+ const st = game.buildings[btn.dataset.bid];
408
+ if (!st) return;
409
+ const dis = game.blueprints < starCost(st.star);
410
+ if (btn.disabled !== dis) btn.disabled = dis;
411
  });
412
  }
413
 
js/util.js CHANGED
@@ -118,10 +118,18 @@ export function openModal(html, { onClose, wide = false, closable = true } = {})
118
  ${closable ? '<button class="modal-x" aria-label="關閉">✕</button>' : ''}
119
  <div class="modal-body">${html}</div></div>`;
120
  document.body.appendChild(back);
 
121
  requestAnimationFrame(() => back.classList.add('show'));
 
122
  const close = () => {
 
 
123
  back.classList.remove('show');
124
- setTimeout(() => back.remove(), 200);
 
 
 
 
125
  onClose && onClose();
126
  };
127
  if (closable) {
 
118
  ${closable ? '<button class="modal-x" aria-label="關閉">✕</button>' : ''}
119
  <div class="modal-body">${html}</div></div>`;
120
  document.body.appendChild(back);
121
+ document.body.classList.add('modal-open');
122
  requestAnimationFrame(() => back.classList.add('show'));
123
+ let closed = false;
124
  const close = () => {
125
+ if (closed) return; // 防止重複關閉
126
+ closed = true;
127
  back.classList.remove('show');
128
+ setTimeout(() => {
129
+ back.remove();
130
+ // 沒有其他 modal 時才移除 modal-open
131
+ if (!document.querySelector('.modal-back')) document.body.classList.remove('modal-open');
132
+ }, 200);
133
  onClose && onClose();
134
  };
135
  if (closable) {