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

石头剪刀布(Rock Paper Scissors)游戏:得分达20分时停止并显示遮罩提示

石头剪刀布游戏功能升级:20分胜负终止与遮罩层实现

现有石头剪刀布游戏运行正常,需新增以下功能:

  • 当玩家或电脑的得分达到20分时,立即终止游戏交互
  • 在游戏界面上方显示带文本提示的遮罩层,防止玩家继续点击操作

现有HTML代码

<div class="game">
    <div class="choices">
        <div id="rock" class="choice">
            <img src="/rock.png" title="Select option rock">
        </div>

        <div id="paper" class="choice">
            <img src="/paper.png" title="Select option paper">
        </div>

        <div id="scissors" class="choice">
            <img src="/scissors.png" title="Select option scissors">
        </div>
    </div>
    
    <div class="score">
        <div id="user-label" class="badge">Client - YOU</div>
        <div id="computer-label" class="badge">Competition</div>
        <span id="user-score">0</span><span class="separator">-</span><span id="computer-score">0</span>
    </div>
    
    <div class="result">
        It's your turn
    </div>
</div>

现有JavaScript代码

// cache the dom (storing for future use)
// & reset everything to 0 value
let userScore = 0;
let computerScore = 0;
const userScore_span = document.getElementById('user-score');
const computerScore_span = document.getElementById('computer-score');
const scoreBoard_div = document.querySelector('.score-board');
const result_div = document.querySelector('.result');
const rock_div = document.getElementById('rock');
const paper_div = document.getElementById('paper');
const scissors_div = document.getElementById('scissors');


// set up the core function for the computer that will use math.random to loop through an array and return that value
function getComputerChoice() {
  const choices = ['rock', 'paper', 'scissors'];
  const randomNumber = Math.floor(Math.random() * 3);
  return choices[randomNumber];
}

// similar to convertcase but just takes lowercase and replaces with titlecase
function convertCase(anythingIwant) {
  if (anythingIwant === 'paper') return 'Paper';
  if (anythingIwant === 'scissors') return 'Scissors';
  return 'Rock';
}

// Winning Condition - this handles what happens when the user clicks one of the choices where the value is them passed through as a parameter
function win(user, computer) {
  userScore++;
  userScore_span.innerHTML = userScore;
  //const userName = ' (user)'.fontsize(3).sup();
  //const compName = ' (comp)'.fontsize(3).sup();
  result_div.innerHTML = 'YOU WIN';
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('winningStyles');
  setTimeout(() => roundStatus.classList.remove('winningStyles'), 300);
}

// Losing Condition - this handles what happens when the user clicks one of the choices where the value is them passed through as a parameter
function loses(user, computer) {
  computerScore++;
  computerScore_span.innerHTML = computerScore;
  //const userName = ' (user)'.fontsize(3).sup();
  //const compName = ' (comp)'.fontsize(3).sup();
  result_div.innerHTML = 'YOU LOSE';
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('losingStyles');
  setTimeout(() => roundStatus.classList.remove('losingStyles'), 300);
}

// Draw Condition - this handles what happens when the user clicks one of the choices where the value is them passed through as a parameter
function draw(user, computer) {
  //const userName = ' (user)'.fontsize(3).sup();
  //const compName = ' (comp)'.fontsize(3).sup();
  result_div.innerHTML = 'IT\'S A TIE';
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('drawStyles');
  setTimeout(() => roundStatus.classList.remove('drawStyles'), 300);
}

// The core game functions that set up and determine the games actual logic aka paper beats rock etc
function game(userChoice) {
  const computerChoice = getComputerChoice();

  switch (userChoice + computerChoice) {
    case 'paperrock':
    case 'rockscissors':
    case 'scissorspaper':
      win(userChoice, computerChoice);
      break;
    case 'rockpaper':
    case 'scissorsrock':
    case 'paperscissors':
      loses(userChoice, computerChoice);
      break;
    case 'rockrock':
    case 'scissorsscissors':
    case 'paperpaper':
      draw(userChoice, computerChoice);
      break;
  }
}

// This function creates and adds an eventlistener to the rock, paper scissors html element and the passes the value of that element to the game function
function main() {
  rock_div.addEventListener('click', () => game('rock'));
  paper_div.addEventListener('click', () => game('paper'));
  scissors_div.addEventListener('click', () => game('scissors'));
}

main();

升级后的完整实现

1. 修改后的HTML(添加遮罩层元素)

<div class="game">
    <!-- 新增遮罩层 -->
    <div class="game-overlay" id="gameOverlay">
        <div class="overlay-text" id="overlayText"></div>
    </div>

    <div class="choices">
        <div id="rock" class="choice">
            <img src="/rock.png" title="选择石头">
        </div>

        <div id="paper" class="choice">
            <img src="/paper.png" title="选择布">
        </div>

        <div id="scissors" class="choice">
            <img src="/scissors.png" title="选择剪刀">
        </div>
    </div>
    
    <div class="score">
        <div id="user-label" class="badge">玩家 - 你</div>
        <div id="computer-label" class="badge">电脑</div>
        <span id="user-score">0</span><span class="separator">-</span><span id="computer-score">0</span>
    </div>
    
    <div class="result">
        轮到你了
    </div>
</div>

2. 新增CSS(控制遮罩层样式)

/* 遮罩层样式 */
.game-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.8);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.overlay-text {
    color: white;
    font-size: 3rem;
    font-weight: bold;
    text-align: center;
}

/* 游戏结束后禁用选择项交互 */
.game-ended .choice {
    pointer-events: none;
    opacity: 0.5;
}

3. 修改后的JavaScript(实现胜负判断与遮罩逻辑)

// 缓存DOM元素并初始化分数
let userScore = 0;
let computerScore = 0;
const userScore_span = document.getElementById('user-score');
const computerScore_span = document.getElementById('computer-score');
const result_div = document.querySelector('.result');
const rock_div = document.getElementById('rock');
const paper_div = document.getElementById('paper');
const scissors_div = document.getElementById('scissors');
const gameOverlay = document.getElementById('gameOverlay');
const overlayText = document.getElementById('overlayText');
const gameContainer = document.querySelector('.game');

// 电脑选择逻辑
function getComputerChoice() {
  const choices = ['rock', 'paper', 'scissors'];
  const randomNumber = Math.floor(Math.random() * 3);
  return choices[randomNumber];
}

// 格式转换为中文标题式
function convertCase(anythingIwant) {
  if (anythingIwant === 'paper') return '布';
  if (anythingIwant === 'scissors') return '剪刀';
  return '石头';
}

// 胜利处理
function win(user, computer) {
  userScore++;
  userScore_span.innerHTML = userScore;
  result_div.innerHTML = `你赢了!${convertCase(user)} 击败 ${convertCase(computer)}`;
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('winningStyles');
  setTimeout(() => roundStatus.classList.remove('winningStyles'), 300);
  checkGameEnd();
}

// 失败处理
function loses(user, computer) {
  computerScore++;
  computerScore_span.innerHTML = computerScore;
  result_div.innerHTML = `你输了!${convertCase(computer)} 击败 ${convertCase(user)}`;
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('losingStyles');
  setTimeout(() => roundStatus.classList.remove('losingStyles'), 300);
  checkGameEnd();
}

// 平局处理
function draw(user, computer) {
  result_div.innerHTML = `平局!双方都选了 ${convertCase(user)}`;
  const roundStatus = document.getElementById(user);
  roundStatus.classList.add('drawStyles');
  setTimeout(() => roundStatus.classList.remove('drawStyles'), 300);
}

// 检查游戏是否结束
function checkGameEnd() {
  let endMessage = '';
  if (userScore >= 20) {
    endMessage = '恭喜你获胜!总分达到20分';
    endGame(endMessage);
  } else if (computerScore >= 20) {
    endMessage = '电脑获胜!总分达到20分';
    endGame(endMessage);
  }
}

// 终止游戏并显示遮罩
function endGame(message) {
  // 显示遮罩层
  gameOverlay.style.display = 'flex';
  overlayText.textContent = message;
  // 移除选择项的点击事件
  rock_div.removeEventListener('click', () => game('rock'));
  paper_div.removeEventListener('click', () => game('paper'));
  scissors_div.removeEventListener('click', () => game('scissors'));
  // 添加样式标记游戏结束
  gameContainer.classList.add('game-ended');
}

// 核心游戏逻辑
function game(userChoice) {
  const computerChoice = getComputerChoice();

  switch (userChoice + computerChoice) {
    case 'paperrock':
    case 'rockscissors':
    case 'scissorspaper':
      win(userChoice, computerChoice);
      break;
    case 'rockpaper':
    case 'scissorsrock':
    case 'paperscissors':
      loses(userChoice, computerChoice);
      break;
    case 'rockrock':
    case 'scissorsscissors':
    case 'paperpaper':
      draw(userChoice, computerChoice);
      break;
  }
}

// 初始化事件监听
function main() {
  rock_div.addEventListener('click', () => game('rock'));
  paper_div.addEventListener('click', () => game('paper'));
  scissors_div.addEventListener('click', () => game('scissors'));
}

main();

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 00:47:02