Lashtw commited on
Commit
0cdf7c7
·
1 Parent(s): 0a32076

feat(lottery): switch bonus draw to roll-dice-first then draw winner

Browse files
Files changed (2) hide show
  1. js/lottery-draw.js +163 -161
  2. lottery-draw.html +9 -9
js/lottery-draw.js CHANGED
@@ -707,7 +707,7 @@ async function initLotteryDrawPage() {
707
  <b style="color:#991b1b;">🎲 班導奇蹟加碼席(已抽 ${bonusDrawsList.length} 名)</b>
708
  <span style="color:#92400e; font-size:0.98rem; font-weight:800;">2顆同點 +1|3顆全同 +2 兵符</span>
709
  </div>
710
- <div>${bonusTags || '<span style="color:#685247; font-size:0.98rem;">按左側「➕ 奇蹟加碼抽 +1 人」抽出加碼同學並擲骰!</span>'}</div>
711
  </div>
712
  `;
713
  $('#drawPrizeBoard').innerHTML = tierRows + bonusRowHtml;
@@ -829,9 +829,11 @@ async function initLotteryDrawPage() {
829
  document.querySelectorAll('[data-draw-tier]').forEach(btn => {
830
  btn.addEventListener('click', () => triggerSingleDraw(btn.dataset.drawTier, false));
831
  });
832
- // 🎲 奇蹟加碼抽人 + 跳出三顆金骰對決舞台(對子 +1、三顆同點 +2)
 
833
  let isDiceRolling = false;
834
  let diceIntervalId = null;
 
835
  const diceTimeouts = [];
836
 
837
  const clearDiceTimers = () => {
@@ -844,36 +846,15 @@ async function initLotteryDrawPage() {
844
  }
845
  };
846
 
847
- const getDrawnWinnerEntries = () => {
848
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
849
  const rankMap = { head: 4, t1: 3, t2: 2, t3: 1 };
850
  const tierLabelMap = Object.fromEntries((drawState?.prizeTiers || []).map(t => [t.tierKey, t.label]));
851
- const list = [];
852
-
853
- const bonusDraws = Array.isArray(drawState?.bonusDraws) ? drawState.bonusDraws : [];
854
- for (let i = bonusDraws.length - 1; i >= 0; i--) {
855
- const bd = bonusDraws[i];
856
- if (!bd?.uid) continue;
857
- const entry = cycle?.entries?.[bd.uid] || {};
858
- list.push({
859
- uid: bd.uid,
860
- isBonusDraw: true,
861
- bonusRecord: bd,
862
- tierKey: 'wonder_bonus',
863
- tierLabel: '🎲 奇蹟加碼席',
864
- rank: 5,
865
- seat: String(entry.seat || bd.seat || '?'),
866
- name: entry.name || bd.name || bd.uid,
867
- });
868
- }
869
-
870
- Object.entries(drawState?.uidToTier || {})
871
  .map(([uid, tierKey]) => {
872
  const entry = cycle?.entries?.[uid] || {};
873
  return {
874
  uid,
875
- isBonusDraw: false,
876
- bonusRecord: null,
877
  tierKey,
878
  tierLabel: tierLabelMap[tierKey] || tierKey,
879
  rank: rankMap[tierKey] || 0,
@@ -881,61 +862,73 @@ async function initLotteryDrawPage() {
881
  name: entry.name || uid,
882
  };
883
  })
884
- .sort((a, b) => b.rank - a.rank)
885
- .forEach(item => list.push(item));
886
 
887
- return list;
 
 
 
 
 
888
  };
889
 
890
- const syncRollUiForTarget = (targetUid) => {
891
- const winners = getDrawnWinnerEntries();
892
- const meta = winners.find(w => w.uid === targetUid);
893
- const cur = extraBonuses[targetUid] || 0;
894
  const capEl = $('#lblWonderDiceCap');
895
  const rollBtn = $('#btnRollWonderDiceAgain');
896
- const bannerEl = $('#wonderDiceResult');
897
- if (capEl) capEl.textContent = `已加碼 +${cur} / 3 兵符`;
898
-
899
- const lockedAlready = Boolean(meta?.bonusRecord?.rolled) || cur >= 3;
900
- if (rollBtn) {
901
- rollBtn.disabled = lockedAlready;
902
- rollBtn.textContent = meta?.bonusRecord?.rolled
903
- ? '✅ 此位加碼人已擲骰定案'
904
- : (cur >= 3 ? '✅ 已達個人上限 (+3)' : '🎲 擲出奇蹟骰!');
905
- }
906
- if (meta?.bonusRecord?.rolled && bannerEl && !isDiceRolling) {
907
- const bd = meta.bonusRecord;
908
- const hit = (bd.bonusBp || 0) > 0;
909
- bannerEl.className = `wonder-dice-result-banner ${hit ? 'hit' : 'miss'}`;
910
- bannerEl.textContent = hit
911
- ? `🎉 ${meta.seat}號 ${meta.name} 已擲出 [${bd.dice.join('・')}] ➔ 獲得 +${bd.bonusBp} 兵符!`
912
- : `💨 ${meta.seat}號 ${meta.name} 已擲出 [${bd.dice.join('・')}]・無對子 (+0 兵符)`;
913
- [0, 1, 2].forEach(idx => {
914
- const dieEl = $(`#wonderDie${idx}`);
915
- if (!dieEl || !Array.isArray(bd.dice)) return;
916
- dieEl.classList.remove('rolling', 'matched', 'unmatched');
917
- dieEl.classList.add('locked');
918
- dieEl.innerHTML = renderWonderDieFaceHtml(bd.dice[idx]);
919
- });
 
 
 
 
 
 
 
920
  }
921
  };
922
 
923
- const syncWonderDiceTargets = (preferredUid = null) => {
924
  const sel = $('#selWonderDiceTarget');
925
- if (!sel) return null;
926
- const list = getDrawnWinnerEntries();
927
- sel.innerHTML = list.map(w => {
928
- const b = extraBonuses[w.uid] || 0;
929
- const statusTxt = w.bonusRecord?.rolled ? ` [${w.bonusRecord.dice?.join('・')} ➔ +${w.bonusRecord.bonusBp}]` : (b > 0 ? ` (+${b})` : '');
930
- return `<option value="${esc(w.uid)}">${esc(w.tierLabel)}・${esc(w.seat)}號 ${esc(w.name)}${statusTxt}</option>`;
931
- }).join('');
932
- const chosen = (preferredUid && list.some(w => w.uid === preferredUid))
933
- ? preferredUid
934
- : (lastWinnerUid && list.some(w => w.uid === lastWinnerUid))
935
- ? lastWinnerUid
936
- : list[0]?.uid || '';
937
- if (chosen) sel.value = chosen;
938
- syncRollUiForTarget(chosen);
 
 
939
  return chosen;
940
  };
941
 
@@ -950,22 +943,26 @@ async function initLotteryDrawPage() {
950
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
951
  if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled') return;
952
  const sel = $('#selWonderDiceTarget');
953
- const targetUid = sel?.value || lastWinnerUid;
954
- const winnerMeta = getDrawnWinnerEntries().find(w => w.uid === targetUid);
955
- if (!targetUid || !winnerMeta) return;
956
- if (winnerMeta.bonusRecord?.rolled) {
957
- syncRollUiForTarget(targetUid);
958
  return;
959
  }
 
 
960
 
961
  clearDiceTimers();
962
  isDiceRolling = true;
963
- const rollAgainBtn = $('#btnRollWonderDiceAgain');
964
- const nextPersonBtn = $('#btnDrawNextWonderPerson');
 
 
965
  const finishBtn = $('#btnFinishWonderDice');
966
  const bannerEl = $('#wonderDiceResult');
967
- if (rollAgainBtn) rollAgainBtn.disabled = true;
968
- if (nextPersonBtn) nextPersonBtn.disabled = true;
969
  if (sel) sel.disabled = true;
970
  if (finishBtn) finishBtn.disabled = true;
971
 
@@ -980,10 +977,12 @@ async function initLotteryDrawPage() {
980
 
981
  if (bannerEl) {
982
  bannerEl.className = 'wonder-dice-result-banner';
983
- bannerEl.textContent = `🎲 正在為加碼幸運兒【${winnerMeta.seat}號 ${winnerMeta.name}】擲出三顆奇蹟金骰…`;
 
 
984
  }
985
 
986
- const curBonus = extraBonuses[targetUid] || 0;
987
  const res = evaluateWonderDiceRoll(null, { currentBonus: curBonus, maxBonus: 3 });
988
 
989
  playMachineSound('diceRoll');
@@ -1010,7 +1009,7 @@ async function initLotteryDrawPage() {
1010
  diceTimeouts.push(setTimeout(() => {
1011
  lockDie(1);
1012
  if (bannerEl && res.dice[0] === res.dice[1]) {
1013
- bannerEl.textContent = `👀 前兩顆同為【${res.dice[0]} 點】!已穩拿 +1 兵符,第三顆拚全同豹子 (+2)!`;
1014
  }
1015
  }, 960));
1016
 
@@ -1028,59 +1027,63 @@ async function initLotteryDrawPage() {
1028
  else el.classList.add('unmatched');
1029
  });
1030
 
1031
- if (winnerMeta.bonusRecord) {
1032
- winnerMeta.bonusRecord.rolled = true;
1033
- winnerMeta.bonusRecord.dice = [...res.dice];
1034
- winnerMeta.bonusRecord.outcome = res.outcome;
1035
- winnerMeta.bonusRecord.bonusBp = res.appliedDelta;
1036
- }
1037
- if (res.appliedDelta > 0) {
1038
- extraBonuses[targetUid] = res.nextBonus;
1039
- }
1040
- saveTempSession();
1041
- renderAll();
1042
-
1043
- if (res.appliedDelta > 0) {
1044
- playMachineSound('fanfare');
1045
- spawnWonderDiceConfetti($('#wonderDiceCard'));
1046
- if (bannerEl) {
1047
- bannerEl.className = 'wonder-dice-result-banner hit';
1048
- bannerEl.innerHTML = `${esc(res.label)}<div style="font-size:1.02rem; margin-top:4px; color:#78350f;">🎁 ${esc(winnerMeta.seat)}號 ${esc(winnerMeta.name)} 獲得奇蹟骰加碼 +${res.appliedDelta} 兵符!</div>`;
1049
- }
1050
- const chute = $('#lotteryChuteReveal');
1051
- if (chute) {
1052
- chute.innerHTML = `<div style="font-size:1.18rem; color:#991b1b; font-weight:900; text-align:center;">🎲 加碼結果 [${res.dice.join('・')}] ➔ ${esc(winnerMeta.seat)}號 ${esc(winnerMeta.name)} ${esc(res.label)}!</div>`;
1053
- }
1054
- } else if (res.capped) {
1055
- playMachineSound('diceMiss');
1056
- if (bannerEl) {
1057
- bannerEl.className = 'wonder-dice-result-banner miss';
1058
- bannerEl.textContent = `🎲 擲出 [${res.dice.join('・')}]!但 ${winnerMeta.seat}號已達個人 +3 兵符上限!`;
1059
  }
1060
  } else {
1061
- playMachineSound('diceMiss');
1062
- if (bannerEl) {
1063
- bannerEl.className = 'wonder-dice-result-banner miss';
1064
- bannerEl.textContent = `💨 擲出 [${res.dice.join('・')}]・三顆都不同點(本次加碼 +0 兵符)`;
1065
- }
1066
- const chute = $('#lotteryChuteReveal');
1067
- if (chute) {
1068
- chute.innerHTML = `<div style="font-size:1.12rem; color:#685247; font-weight:800; text-align:center;">💨 加碼抽 ${esc(winnerMeta.seat)}號 ${esc(winnerMeta.name)} 擲出 [${res.dice.join('・')}](未出現同點,+0 兵符)</div>`;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1069
  }
1070
  }
1071
 
1072
  isDiceRolling = false;
1073
- syncWonderDiceTargets(targetUid);
1074
- if (nextPersonBtn) nextPersonBtn.disabled = false;
1075
  if (sel) sel.disabled = false;
1076
  if (finishBtn) finishBtn.disabled = false;
1077
  }, 1460));
1078
  };
1079
 
1080
- /** 老師點「➕ 奇蹟加碼抽 +1 人」:物理轉球抽人 ➔ 立即跳出奇蹟骰定賞賜 */
1081
- const triggerBonusDrawWithDice = async () => {
1082
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1083
- if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled') return;
1084
 
1085
  closeWonderDiceModal();
1086
  if (!Array.isArray(drawState.bonusDraws)) drawState.bonusDraws = [];
@@ -1099,77 +1102,75 @@ async function initLotteryDrawPage() {
1099
  isAnimating = true;
1100
  renderAll();
1101
  const chute = $('#lotteryChuteReveal');
1102
- chute.innerHTML = `<div style="font-size:1.28rem; font-weight:900; color:#991b1b;">🌀 啟動「班導奇蹟加碼抽」!正在抽出幸運同學…</div>`;
1103
 
1104
  await machine.playDrawSequence(winner, nearMisses, (nmList) => {
1105
  const names = nmList.map(x => `${x.seat}號 ${x.name}`).join(' / ');
1106
- chute.innerHTML = `<div style="font-size:1.2rem; font-weight:800; color:#b45309;">💨 差一點抽出加碼:<b>${esc(names)}</b> …</div>`;
1107
  });
1108
 
1109
  drawState.bonusDraws.push({
1110
  uid: winner.uid,
1111
  seat: String(winner.seat || '?'),
1112
  name: winner.name || winner.uid,
1113
- rolled: false,
1114
- dice: null,
1115
- outcome: null,
1116
- bonusBp: 0,
1117
  });
 
 
 
1118
  lastWinnerUid = winner.uid;
 
1119
  isAnimating = false;
1120
  saveTempSession();
1121
  renderAll();
1122
 
1123
  chute.innerHTML = `
1124
  <div class="draw-winner-pop" style="text-align:center;">
1125
- <div style="font-size:1.08rem; font-weight:800; color:#92400e;">🎁 班導奇蹟加碼幸運兒登場!</div>
1126
- <div style="font-size:2.1rem; font-weight:900; color:#991b1b; margin:4px 0;">🎉 ${esc(winner.seat)}號 ${esc(winner.name)}</div>
1127
- <div style="font-size:1.02rem; font-weight:700; color:#685247;">正在跳出三顆奇蹟金骰決定兵符獎勵…</div>
 
 
1128
  </div>
1129
  `;
1130
-
1131
- const overlay = $('#wonderDiceOverlay');
1132
- if (overlay) {
1133
- syncWonderDiceTargets(winner.uid);
1134
- overlay.classList.remove('hidden');
1135
- runWonderDiceRoll();
1136
- }
1137
  };
1138
 
1139
- $('#btnExtraTeacherDraw')?.addEventListener('click', () => triggerBonusDrawWithDice());
1140
- $('#btnDrawNextWonderPerson')?.addEventListener('click', () => triggerBonusDrawWithDice());
1141
-
1142
- $('#btnWonderDiceBonus')?.addEventListener('click', () => {
1143
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1144
  if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled') return;
1145
- const winners = getDrawnWinnerEntries();
1146
- if (winners.length === 0) {
1147
- if (confirm('尚未抽出任何得主,要立即進行「➕ 奇蹟加碼抽 +1 人」並擲奇蹟骰嗎?')) {
1148
- triggerBonusDrawWithDice();
1149
- }
1150
  return;
1151
  }
1152
  const overlay = $('#wonderDiceOverlay');
1153
  if (!overlay) return;
1154
- const chosenUid = syncWonderDiceTargets(lastWinnerUid);
 
1155
  overlay.classList.remove('hidden');
1156
- const chosenMeta = winners.find(w => w.uid === chosenUid);
1157
- if (!chosenMeta?.bonusRecord?.rolled && (extraBonuses[chosenUid] || 0) < 3 && !chosenMeta?.isBonusDraw) {
1158
- // 主獎得主手動開啟時等候教師按下或直接檢視狀態,避免意外重複加碼
1159
- const bannerEl = $('#wonderDiceResult');
1160
- if (bannerEl) {
1161
- bannerEl.className = 'wonder-dice-result-banner';
1162
- bannerEl.textContent = `準備就緒!點擊「🎲 擲出奇蹟骰!」為 ${chosenMeta.seat}號 ${chosenMeta.name} 挑戰加碼`;
1163
- }
1164
- }
1165
- });
1166
 
1167
  $('#selWonderDiceTarget')?.addEventListener('change', (e) => {
1168
  if (isDiceRolling) return;
1169
- syncRollUiForTarget(e.target.value);
1170
  });
1171
 
1172
  $('#btnRollWonderDiceAgain')?.addEventListener('click', () => runWonderDiceRoll());
 
 
 
 
 
 
 
 
1173
  $('#btnCloseWonderDice')?.addEventListener('click', () => closeWonderDiceModal());
1174
  $('#btnFinishWonderDice')?.addEventListener('click', () => closeWonderDiceModal());
1175
  $('#wonderDiceOverlay')?.addEventListener('click', (e) => {
@@ -1179,6 +1180,7 @@ async function initLotteryDrawPage() {
1179
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1180
  if (isAnimating || isDiceRolling || cycle?.status === 'settled') return;
1181
  if (!confirm('確定清除本機尚未發信的抽籤暫存並重新載入名單?(不影響學生已投球數)')) return;
 
1182
  closeWonderDiceModal();
1183
  try { sessionStorage.removeItem(ssKey()); } catch (e) {}
1184
  drawState = null;
 
707
  <b style="color:#991b1b;">🎲 班導奇蹟加碼席(已抽 ${bonusDrawsList.length} 名)</b>
708
  <span style="color:#92400e; font-size:0.98rem; font-weight:800;">2顆同點 +1|3顆全同 +2 兵符</span>
709
  </div>
710
+ <div>${bonusTags || '<span style="color:#685247; font-size:0.98rem;">按左側「🎲 奇蹟骰加碼抽」先擲骰決定兵符,再抽出幸運同學!</span>'}</div>
711
  </div>
712
  `;
713
  $('#drawPrizeBoard').innerHTML = tierRows + bonusRowHtml;
 
829
  document.querySelectorAll('[data-draw-tier]').forEach(btn => {
830
  btn.addEventListener('click', () => triggerSingleDraw(btn.dataset.drawTier, false));
831
  });
832
+ // 🎲 奇蹟加碼抽(先擲骰子、老師控制無限重骰 ➔ 再依最後結果物理轉球抽人贈獎)
833
+ const PRE_ROLL_MODE = '__NEW_DRAW__';
834
  let isDiceRolling = false;
835
  let diceIntervalId = null;
836
+ let lastPreRollResult = null;
837
  const diceTimeouts = [];
838
 
839
  const clearDiceTimers = () => {
 
846
  }
847
  };
848
 
849
+ const getMainWinnerEntries = () => {
850
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
851
  const rankMap = { head: 4, t1: 3, t2: 2, t3: 1 };
852
  const tierLabelMap = Object.fromEntries((drawState?.prizeTiers || []).map(t => [t.tierKey, t.label]));
853
+ return Object.entries(drawState?.uidToTier || {})
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
854
  .map(([uid, tierKey]) => {
855
  const entry = cycle?.entries?.[uid] || {};
856
  return {
857
  uid,
 
 
858
  tierKey,
859
  tierLabel: tierLabelMap[tierKey] || tierKey,
860
  rank: rankMap[tierKey] || 0,
 
862
  name: entry.name || uid,
863
  };
864
  })
865
+ .sort((a, b) => b.rank - a.rank);
866
+ };
867
 
868
+ const getRemainingBonusPool = () => {
869
+ if (!drawState) return [];
870
+ const bonusUids = new Set((Array.isArray(drawState.bonusDraws) ? drawState.bonusDraws : []).map(b => b.uid));
871
+ return (drawState.eligiblePool || []).filter(e =>
872
+ e && e.uid && e.weight > 0 && !drawState.uidToTier?.[e.uid] && !bonusUids.has(e.uid)
873
+ );
874
  };
875
 
876
+ const syncRollUiForMode = (selectedVal) => {
877
+ const isPreRoll = !selectedVal || selectedVal === PRE_ROLL_MODE;
 
 
878
  const capEl = $('#lblWonderDiceCap');
879
  const rollBtn = $('#btnRollWonderDiceAgain');
880
+ const drawBtn = $('#btnDrawNextWonderPerson');
881
+
882
+ if (isPreRoll) {
883
+ const pendingBp = lastPreRollResult ? lastPreRollResult.rawDelta : null;
884
+ if (capEl) capEl.textContent = pendingBp === null ? '準備擲骰定獎額' : `本輪抽獎額:+${pendingBp} 兵符`;
885
+ if (rollBtn) {
886
+ rollBtn.disabled = isDiceRolling;
887
+ rollBtn.textContent = lastPreRollResult
888
+ ? (pendingBp > 0 ? '🎲 不滿意?再重骰一次' : '🎲 未同點!再骰一次!')
889
+ : '🎲 擲出奇蹟骰!';
890
+ rollBtn.classList.toggle('gold', Boolean(lastPreRollResult && pendingBp === 0));
891
+ }
892
+ if (drawBtn) {
893
+ drawBtn.style.display = '';
894
+ drawBtn.disabled = isDiceRolling || !lastPreRollResult;
895
+ drawBtn.classList.toggle('gold', Boolean(lastPreRollResult && pendingBp > 0));
896
+ drawBtn.textContent = lastPreRollResult
897
+ ? `🎯 依最後結果 (+${pendingBp} 兵符) 立即抽人!`
898
+ : '🎯 依最後結果立即抽人!';
899
+ }
900
+ } else {
901
+ const cur = extraBonuses[selectedVal] || 0;
902
+ if (capEl) capEl.textContent = `已加碼 +${cur} / 3 兵符`;
903
+ if (rollBtn) {
904
+ rollBtn.disabled = isDiceRolling || cur >= 3;
905
+ rollBtn.classList.add('gold');
906
+ rollBtn.textContent = cur >= 3 ? '✅ 已達個人上限 (+3)' : '🎲 為該得主擲奇蹟骰!';
907
+ }
908
+ if (drawBtn) {
909
+ drawBtn.style.display = 'none';
910
+ }
911
  }
912
  };
913
 
914
+ const syncWonderDiceTargets = (preferredVal = PRE_ROLL_MODE) => {
915
  const sel = $('#selWonderDiceTarget');
916
+ if (!sel) return PRE_ROLL_MODE;
917
+ const mains = getMainWinnerEntries();
918
+ const remainCnt = getRemainingBonusPool().length;
919
+ const optionsHtml = [
920
+ `<option value="${PRE_ROLL_MODE}">🎯 【先骰後抽】依最後骰子結果抽出加碼得主(剩 ${remainCnt} 人可抽)</option>`,
921
+ ...mains.map(w => {
922
+ const b = extraBonuses[w.uid] || 0;
923
+ return `<option value="${esc(w.uid)}">(指定補擲)${esc(w.tierLabel)}・${esc(w.seat)}號 ${esc(w.name)}${b > 0 ? ` (+${b})` : ''}</option>`;
924
+ }),
925
+ ];
926
+ sel.innerHTML = optionsHtml.join('');
927
+ const chosen = preferredVal && (preferredVal === PRE_ROLL_MODE || mains.some(m => m.uid === preferredVal))
928
+ ? preferredVal
929
+ : PRE_ROLL_MODE;
930
+ sel.value = chosen;
931
+ syncRollUiForMode(chosen);
932
  return chosen;
933
  };
934
 
 
943
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
944
  if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled') return;
945
  const sel = $('#selWonderDiceTarget');
946
+ const selectedVal = sel?.value || PRE_ROLL_MODE;
947
+ const isPreRoll = selectedVal === PRE_ROLL_MODE;
948
+
949
+ if (isPreRoll && getRemainingBonusPool().length === 0) {
950
+ alert('所有有投球的同學均已獲得主要獎項或參加過奇蹟加碼抽囉!');
951
  return;
952
  }
953
+ const targetWinner = !isPreRoll ? getMainWinnerEntries().find(w => w.uid === selectedVal) : null;
954
+ if (!isPreRoll && !targetWinner) return;
955
 
956
  clearDiceTimers();
957
  isDiceRolling = true;
958
+ if (isPreRoll) lastPreRollResult = null;
959
+
960
+ const rollBtn = $('#btnRollWonderDiceAgain');
961
+ const drawBtn = $('#btnDrawNextWonderPerson');
962
  const finishBtn = $('#btnFinishWonderDice');
963
  const bannerEl = $('#wonderDiceResult');
964
+ if (rollBtn) rollBtn.disabled = true;
965
+ if (drawBtn) drawBtn.disabled = true;
966
  if (sel) sel.disabled = true;
967
  if (finishBtn) finishBtn.disabled = true;
968
 
 
977
 
978
  if (bannerEl) {
979
  bannerEl.className = 'wonder-dice-result-banner';
980
+ bannerEl.textContent = isPreRoll
981
+ ? '🎲 三顆奇蹟金骰滾動中…先骰出本輪加碼兵符數!'
982
+ : `🎲 正在為【${targetWinner.seat}號 ${targetWinner.name}】擲出三顆奇蹟金骰…`;
983
  }
984
 
985
+ const curBonus = isPreRoll ? 0 : (extraBonuses[selectedVal] || 0);
986
  const res = evaluateWonderDiceRoll(null, { currentBonus: curBonus, maxBonus: 3 });
987
 
988
  playMachineSound('diceRoll');
 
1009
  diceTimeouts.push(setTimeout(() => {
1010
  lockDie(1);
1011
  if (bannerEl && res.dice[0] === res.dice[1]) {
1012
+ bannerEl.textContent = `👀 前兩顆同為【${res.dice[0]} 點】!已確定 +1 兵符,第三顆衝刺豹子 (+2)!`;
1013
  }
1014
  }, 960));
1015
 
 
1027
  else el.classList.add('unmatched');
1028
  });
1029
 
1030
+ if (isPreRoll) {
1031
+ lastPreRollResult = res;
1032
+ if (res.rawDelta > 0) {
1033
+ playMachineSound('fanfare');
1034
+ spawnWonderDiceConfetti($('#wonderDiceCard'));
1035
+ if (bannerEl) {
1036
+ bannerEl.className = 'wonder-dice-result-banner hit';
1037
+ bannerEl.innerHTML = `${esc(res.label)}<div style="font-size:1.02rem; margin-top:4px; color:#78350f;">滿意的話可按「🎯 立即抽人!」或點「再重骰一次」繼續骰!</div>`;
1038
+ }
1039
+ } else {
1040
+ playMachineSound('diceMiss');
1041
+ if (bannerEl) {
1042
+ bannerEl.className = 'wonder-dice-result-banner miss';
1043
+ bannerEl.textContent = `💨 擲出 [${res.dice.join('・')}]・三顆都不同點(+0 兵符),可按「再骰一次」重擲!`;
1044
+ }
 
 
 
 
 
 
 
 
 
 
 
 
 
1045
  }
1046
  } else {
1047
+ if (res.appliedDelta > 0) {
1048
+ extraBonuses[selectedVal] = res.nextBonus;
1049
+ saveTempSession();
1050
+ renderAll();
1051
+ playMachineSound('fanfare');
1052
+ spawnWonderDiceConfetti($('#wonderDiceCard'));
1053
+ if (bannerEl) {
1054
+ bannerEl.className = 'wonder-dice-result-banner hit';
1055
+ bannerEl.innerHTML = `${esc(res.label)}<div style="font-size:1.02rem; margin-top:4px; color:#78350f;">🎁 ${esc(targetWinner.seat)}號 ${esc(targetWinner.name)} 累計 +${res.nextBonus} / 3 兵符!</div>`;
1056
+ }
1057
+ const chute = $('#lotteryChuteReveal');
1058
+ if (chute) {
1059
+ chute.innerHTML = `<div style="font-size:1.18rem; color:#991b1b; font-weight:900; text-align:center;">🎲 奇蹟骰開出 [${res.dice.join('・')}] ➔ ${esc(targetWinner.seat)}號 ${esc(targetWinner.name)} 累計 +${res.nextBonus} 兵符!</div>`;
1060
+ }
1061
+ } else if (res.capped) {
1062
+ playMachineSound('diceMiss');
1063
+ if (bannerEl) {
1064
+ bannerEl.className = 'wonder-dice-result-banner miss';
1065
+ bannerEl.textContent = `🎲 擲出 [${res.dice.join('・')}]!但 ${targetWinner.seat}號已達個人 +3 兵符上限!`;
1066
+ }
1067
+ } else {
1068
+ playMachineSound('diceMiss');
1069
+ if (bannerEl) {
1070
+ bannerEl.className = 'wonder-dice-result-banner miss';
1071
+ bannerEl.textContent = `💨 擲出 [${res.dice.join('・')}]・未出現對子(+0 兵符),可再骰一次!`;
1072
+ }
1073
  }
1074
  }
1075
 
1076
  isDiceRolling = false;
1077
+ syncWonderDiceTargets(selectedVal);
 
1078
  if (sel) sel.disabled = false;
1079
  if (finishBtn) finishBtn.disabled = false;
1080
  }, 1460));
1081
  };
1082
 
1083
+ /** 第 2 步:依老師最終確定的最後一次骰子結果,從剩餘投球名單滾球抽出得主並贈獎 */
1084
+ const executeDrawForLastDiceResult = async (frozenRoll) => {
1085
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1086
+ if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled' || !frozenRoll) return;
1087
 
1088
  closeWonderDiceModal();
1089
  if (!Array.isArray(drawState.bonusDraws)) drawState.bonusDraws = [];
 
1102
  isAnimating = true;
1103
  renderAll();
1104
  const chute = $('#lotteryChuteReveal');
1105
+ chute.innerHTML = `<div style="font-size:1.28rem; font-weight:900; color:#991b1b;">🌀 鎖定奇蹟骰 [${frozenRoll.dice.join('・')}] (+${frozenRoll.rawDelta} 兵符)!彩球攪拌抽人中…</div>`;
1106
 
1107
  await machine.playDrawSequence(winner, nearMisses, (nmList) => {
1108
  const names = nmList.map(x => `${x.seat}號 ${x.name}`).join(' / ');
1109
+ chute.innerHTML = `<div style="font-size:1.2rem; font-weight:800; color:#b45309;">💨 差一點抽出:<b>${esc(names)}</b> …</div>`;
1110
  });
1111
 
1112
  drawState.bonusDraws.push({
1113
  uid: winner.uid,
1114
  seat: String(winner.seat || '?'),
1115
  name: winner.name || winner.uid,
1116
+ rolled: true,
1117
+ dice: [...frozenRoll.dice],
1118
+ outcome: frozenRoll.outcome,
1119
+ bonusBp: frozenRoll.rawDelta,
1120
  });
1121
+ if (frozenRoll.rawDelta > 0) {
1122
+ extraBonuses[winner.uid] = Math.min(3, (extraBonuses[winner.uid] || 0) + frozenRoll.rawDelta);
1123
+ }
1124
  lastWinnerUid = winner.uid;
1125
+ lastPreRollResult = null;
1126
  isAnimating = false;
1127
  saveTempSession();
1128
  renderAll();
1129
 
1130
  chute.innerHTML = `
1131
  <div class="draw-winner-pop" style="text-align:center;">
1132
+ <div style="font-size:1.08rem; font-weight:800; color:#92400e;">🎲 依最後奇蹟骰 [${frozenRoll.dice.join('・')}] 抽出加碼得主!</div>
1133
+ <div style="font-size:2.15rem; font-weight:900; color:#991b1b; margin:6px 0;">🎉 ${esc(winner.seat)}號 ${esc(winner.name)}</div>
1134
+ <div style="font-size:1.12rem; font-weight:900; color:${frozenRoll.rawDelta > 0 ? '#b45309' : '#685247'};">
1135
+ ${frozenRoll.rawDelta > 0 ? `🏆 獲得奇蹟骰加碼 +${frozenRoll.rawDelta} 兵符!` : '💫 本次未擲出同點(+0 兵符)'}
1136
+ </div>
1137
  </div>
1138
  `;
 
 
 
 
 
 
 
1139
  };
1140
 
1141
+ /** 老師點「🎲 奇蹟骰加碼抽(先擲骰 ➔ 再抽人)」:檢查剩餘名單後跳出骰台並自動首擲 */
1142
+ const openPreRollWonderDiceModal = () => {
 
 
1143
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1144
  if (!drawState || isAnimating || isDiceRolling || cycle?.status === 'settled') return;
1145
+ if (getRemainingBonusPool().length === 0) {
1146
+ alert('所有有投球的同學均已獲得主要獎項或參加過奇蹟加碼抽囉!');
 
 
 
1147
  return;
1148
  }
1149
  const overlay = $('#wonderDiceOverlay');
1150
  if (!overlay) return;
1151
+ lastPreRollResult = null;
1152
+ syncWonderDiceTargets(PRE_ROLL_MODE);
1153
  overlay.classList.remove('hidden');
1154
+ runWonderDiceRoll();
1155
+ };
1156
+
1157
+ $('#btnExtraTeacherDraw')?.addEventListener('click', () => openPreRollWonderDiceModal());
1158
+ $('#btnWonderDiceBonus')?.addEventListener('click', () => openPreRollWonderDiceModal());
 
 
 
 
 
1159
 
1160
  $('#selWonderDiceTarget')?.addEventListener('change', (e) => {
1161
  if (isDiceRolling) return;
1162
+ syncRollUiForMode(e.target.value);
1163
  });
1164
 
1165
  $('#btnRollWonderDiceAgain')?.addEventListener('click', () => runWonderDiceRoll());
1166
+ $('#btnDrawNextWonderPerson')?.addEventListener('click', () => {
1167
+ if (isDiceRolling) return;
1168
+ if (!lastPreRollResult) {
1169
+ runWonderDiceRoll();
1170
+ return;
1171
+ }
1172
+ executeDrawForLastDiceResult({ ...lastPreRollResult });
1173
+ });
1174
  $('#btnCloseWonderDice')?.addEventListener('click', () => closeWonderDiceModal());
1175
  $('#btnFinishWonderDice')?.addEventListener('click', () => closeWonderDiceModal());
1176
  $('#wonderDiceOverlay')?.addEventListener('click', (e) => {
 
1180
  const cycle = currentCycleId ? currentClass?.lotteryCycles?.[currentCycleId] : null;
1181
  if (isAnimating || isDiceRolling || cycle?.status === 'settled') return;
1182
  if (!confirm('確定清除本機尚未發信的抽籤暫存並重新載入名單?(不影響學生已投球數)')) return;
1183
+ lastPreRollResult = null;
1184
  closeWonderDiceModal();
1185
  try { sessionStorage.removeItem(ssKey()); } catch (e) {}
1186
  drawState = null;
lottery-draw.html CHANGED
@@ -64,7 +64,7 @@
64
  </div>
65
 
66
  <div style="margin-top:10px; display:flex; gap:10px; flex-wrap:wrap;">
67
- <button id="btnExtraTeacherDraw" class="draw-btn gold" type="button" style="flex:1;">➕ 奇蹟加碼抽 +1 人(抽球 ➔ 擲骰)</button>
68
  <button id="btnWonderDiceBonus" class="draw-btn" type="button" style="flex:1;">🎲 開啟奇蹟骰台</button>
69
  <button id="btnResetLocalDraw" class="draw-btn" type="button" title="僅重設尚未結算發信的現場模擬抽籤">🧹 重抽暫存</button>
70
  </div>
@@ -86,22 +86,22 @@
86
  </section>
87
  </main>
88
 
89
- <!-- 🎲 奇蹟骰跳出對決舞台 -->
90
  <div id="wonderDiceOverlay" class="wonder-dice-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="wonderDiceTitle">
91
  <div id="wonderDiceCard" class="wonder-dice-card">
92
  <div class="wonder-dice-header">
93
- <h2 id="wonderDiceTitle" style="margin:0; font-size:1.45rem; color:#991b1b;">🎲 奇蹟骰・加碼對決台</h2>
94
  <button id="btnCloseWonderDice" class="draw-btn" type="button" aria-label="關閉奇蹟骰視窗">✕</button>
95
  </div>
96
 
97
  <div class="wonder-dice-target-row">
98
- <label for="selWonderDiceTarget" style="font-weight:800; color:#2c201b; font-size:1.05rem;">🎯 加碼對象:</label>
99
  <select id="selWonderDiceTarget" class="draw-select" style="flex:1; min-width:180px;"></select>
100
- <span id="lblWonderDiceCap" class="lottery-pill-tag">+0 / 3 兵符</span>
101
  </div>
102
 
103
  <div class="wonder-dice-rules">
104
- ✨ 三骰同步擲出:<b>任兩顆同點 ➔ 加碼 +1 兵符</b>|<b>三顆全同(豹子)➔ 加碼 +2 兵符</b>(單人上限 3 兵符)
105
  </div>
106
 
107
  <div id="wonderDiceStage" class="wonder-dice-stage">
@@ -115,9 +115,9 @@
115
  </div>
116
 
117
  <div class="wonder-dice-actions">
118
- <button id="btnDrawNextWonderPerson" class="draw-btn gold" type="button" style="flex:1; font-size:1.12rem;">➕ 再加碼抽 +1 人</button>
119
- <button id="btnRollWonderDiceAgain" class="draw-btn" type="button" style="font-size:1.05rem;">🎲 擲出奇蹟骰</button>
120
- <button id="btnFinishWonderDice" class="draw-btn" type="button" style="font-size:1.05rem;">✅ 返回開獎台</button>
121
  </div>
122
  </div>
123
  </div>
 
64
  </div>
65
 
66
  <div style="margin-top:10px; display:flex; gap:10px; flex-wrap:wrap;">
67
+ <button id="btnExtraTeacherDraw" class="draw-btn gold" type="button" style="flex:1;">🎲 奇蹟骰加碼抽(先擲骰 ➔ 再抽人)</button>
68
  <button id="btnWonderDiceBonus" class="draw-btn" type="button" style="flex:1;">🎲 開啟奇蹟骰台</button>
69
  <button id="btnResetLocalDraw" class="draw-btn" type="button" title="僅重設尚未結算發信的現場模擬抽籤">🧹 重抽暫存</button>
70
  </div>
 
86
  </section>
87
  </main>
88
 
89
+ <!-- 🎲 奇蹟骰跳出對決舞台(先骰骰子、可不限次重骰,再依最後結果抽籤) -->
90
  <div id="wonderDiceOverlay" class="wonder-dice-overlay hidden" role="dialog" aria-modal="true" aria-labelledby="wonderDiceTitle">
91
  <div id="wonderDiceCard" class="wonder-dice-card">
92
  <div class="wonder-dice-header">
93
+ <h2 id="wonderDiceTitle" style="margin:0; font-size:1.45rem; color:#991b1b;">🎲 奇蹟骰・先擲骰後抽人對決台</h2>
94
  <button id="btnCloseWonderDice" class="draw-btn" type="button" aria-label="關閉奇蹟骰視窗">✕</button>
95
  </div>
96
 
97
  <div class="wonder-dice-target-row">
98
+ <label for="selWonderDiceTarget" style="font-weight:800; color:#2c201b; font-size:1.05rem;">🎯 抽獎模式:</label>
99
  <select id="selWonderDiceTarget" class="draw-select" style="flex:1; min-width:180px;"></select>
100
+ <span id="lblWonderDiceCap" class="lottery-pill-tag">待擲骰定獎</span>
101
  </div>
102
 
103
  <div class="wonder-dice-rules">
104
+ ✨ 老師可不限次數重骰至滿意再按抽人!<b>任 2 顆同點 ➔ +1 兵符</b>|<b>3 顆全同(豹子)➔ +2 兵符</b>(依最後一次結果抽籤)
105
  </div>
106
 
107
  <div id="wonderDiceStage" class="wonder-dice-stage">
 
115
  </div>
116
 
117
  <div class="wonder-dice-actions">
118
+ <button id="btnRollWonderDiceAgain" class="draw-btn" type="button" style="flex:1; font-size:1.08rem;">🎲 再骰一次!</button>
119
+ <button id="btnDrawNextWonderPerson" class="draw-btn gold" type="button" style="flex:1.25; font-size:1.12rem;">🎯 依最後結果立即抽人!</button>
120
+ <button id="btnFinishWonderDice" class="draw-btn" type="button" style="font-size:1.02rem;">取消返回</button>
121
  </div>
122
  </div>
123
  </div>