You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让网格游戏的功能逻辑仅在点击开始按钮时才触发执行?

你当前代码的核心问题是:网格方块的点击事件没有判断游戏是否已启动,所以未点击开始按钮时也能触发游戏逻辑。根据你的需求可以选择以下两种修改方案:


方案1:页面加载完成就显示游戏面板,仅禁止未启动时的点击响应

修改click函数,在函数入口处新增游戏状态判断即可:

function click(square) {
  // 新增:游戏未启动/暂停时不响应网格点击
  if (paused) return
  let currentId = square.id
  if (isGameOver) return
  // 剩余原有逻辑保持不变
  if (square.classList.contains('checked')) return score++
  if (square.classList.contains('buzzy')) {
      gameOver(square)
    } else {
      let total = square.getAttribute('data')
      if (total !=0) {
        square.classList.add('checked')
        if (total == 1) square.classList.add('one')
        if (total == 2) square.classList.add('two')
        if (total == 3) square.classList.add('three')
        if (total == 4) square.classList.add('four')
        square.innerHTML = total
        return
      }
      checkSquare(square, currentId)
    }
    square.classList.add('checked')
  }

方案2:点击开始按钮后才生成游戏面板+响应点击

  1. 先删掉代码里单独调用的createBoard()那行代码
  2. 修改开始按钮的点击事件,新增面板创建逻辑:
startBtn.addEventListener('click', () => {
  if (paused === false) {
    score++
    return
  }
  // 新增:仅首次点击开始时创建游戏面板,避免重复生成
  if (squares.length === 0) {
    createBoard()
  }
  scoreDisplay.innerHTML = 'Score' + ': ' + score++
  paused = false
  timerId = setInterval(countDown, 1000)
})

如果需要支持多次重启游戏,你可以在开始按钮逻辑中补充重置分数、重置isGameOver状态、清空原有grid容器内容的逻辑,避免多次点击出现重复面板。


内容的提问来源于stack exchange,提问作者sunflowers14

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 06:06:03