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

如何让JavaScript猜拳游戏的函数等待按钮点击?

解决石头剪刀布游戏等待用户点击选择的问题

核心思路是用Promise封装用户点击事件,配合async/await语法让游戏流程等待用户输入,具体实现如下:

1. 改造获取用户选择的函数

把getPlayerChoice改成返回Promise,监听三个按钮的点击动作,直到用户做出选择才resolve:

function getPlayerChoice() {
  return new Promise((resolve) => {
    // 替换成你实际的按钮选择器(比如按类名或id)
    const choiceButtons = document.querySelectorAll('.choice-btn');

    function handleButtonClick(e) {
      // 从按钮的data属性获取选择值(推荐写法)
      const playerPick = e.target.dataset.choice;
      // 移除所有按钮的点击监听,避免重复触发
      choiceButtons.forEach(btn => btn.removeEventListener('click', handleButtonClick));
      // 返回用户选择,结束等待
      resolve(playerPick);
    }

    // 给每个按钮绑定点击事件
    choiceButtons.forEach(btn => btn.addEventListener('click', handleButtonClick));
  });
}

注:如果你的按钮用id区分(比如#rock、#paper、#scissors),可以把选择器改成document.querySelectorAll('#rock, #paper, #scissors'),然后通过e.target.id获取选择值。

2. 改造游戏主函数

将game函数声明为async函数,用await等待getPlayerChoice()的结果,实现每轮等待用户操作后再继续:

async function game() {
  for (let round = 1; round <= 5; round++) {
    console.log(`=== 第${round}轮 ===`);
    
    // 等待用户点击选择
    const playerChoice = await getPlayerChoice();
    // 生成电脑的选择(假设你已有这个函数)
    const computerChoice = getComputerChoice();

    // 执行胜负判断逻辑(假设你已有这个函数)
    const roundResult = determineWinner(playerChoice, computerChoice);
    console.log(`你选了${playerChoice},电脑选了${computerChoice} → ${roundResult}`);
  }
  console.log('=== 5轮游戏全部结束 ===');
}

关键注意点

  • 每次获取用户选择后,必须移除按钮的点击监听,否则后续轮次会重复绑定事件,导致一次点击触发多次逻辑
  • await只能在async函数内部使用,所以游戏主函数必须标记为async
  • 可以给按钮添加data-choice属性(比如<button class="choice-btn" data-choice="rock">石头</button>),更优雅地获取用户选择

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 06:05:20