iT邦幫忙

2025 iThome 鐵人賽

0

Day 22
主題:計分系統 — 翻牌次數、分數顯示

🎯今日目標
今天要讓遊戲能記錄玩家的表現!
在有了計時功能之後,我們可以進一步增加「計分系統」,讓玩家能看到自己的成績。」
主要的設計方向有兩種:

  1. 翻牌次數統計 — 每翻一次就 +1,用來評估效率。
  2. 分數制度 — 根據配對成功與失誤次數計算分數,增加挑戰性。
    有了這些機制,玩家會更有動力去追求「更少步數」或「更高分數」。

📘學習與操作重點

  1. 統計翻牌次數
    每當玩家點擊一張卡片,就讓 flipCount++
    在畫面上顯示目前的翻牌次數。

  2. 建立分數規則
    可以簡單設定為:
    成功配對:+10 分
    失敗翻錯:-2 分(最低不低於 0)
    分數可用 score 變數紀錄。

  3. 畫面即時更新
    使用 document.getElementById("score").textContent 即時更新分數。
    搭配 CSS 美化計分板,讓畫面更清楚。

💻 程式範例

<div id="scoreboard">
  <p>翻牌次數:<span id="flipCount">0</span></p>
  <p>分數:<span id="score">0</span></p>
</div>

<script>
  let flipCount = 0;
  let score = 0;

  function updateScoreboard() {
    document.getElementById("flipCount").textContent = flipCount;
    document.getElementById("score").textContent = score;
  }

  function flipCard(card) {
    // 每次翻牌都記錄次數
    flipCount++;
    updateScoreboard();

    flippedCards.push(card);
    if (flippedCards.length === 2) checkMatch();
  }

  function checkMatch() {
    const [card1, card2] = flippedCards;
    const isMatch =
      card1.querySelector(".back").textContent ===
      card2.querySelector(".back").textContent;

    if (isMatch) {
      score += 10;
    } else {
      score = Math.max(0, score - 2);
    }

    updateScoreboard();
    flippedCards = [];
  }
</script>

今日成果
✅ 成功加入翻牌次數與分數統計功能。
✅ 學會在程式中即時更新數據與畫面。
✅ 遊戲不再只是運氣,而是能衡量技巧與效率的挑戰!


上一篇
Day 21 | 計時器
下一篇
Day 23 | 狀態管理
系列文
30天打造純前端互動小遊戲網站30
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言