剪刀石头布游戏事件监听器

Rock Paper Scissors Game event listener

我目前正在制作剪刀石头布游戏。我被困在我的事件侦听器功能上。我能够让这个显示我的图像来显示玩家选择的内容,我也想将我的 playRound 函数添加到这个事件中,以便它在单击按钮时运行游戏。尝试在这个函数中嵌套一个函数是不是一个坏主意?

//Button Click Event Listener to Display Choice//
rock.addEventListener('click', function() {
  playerSign.getElementsByClassName('?')[0]
  playerSign.innerHTML = '<img src="./images/Rock.png" alt="Rock"/>'
});

paper.addEventListener('click', function() {
  playerSign.getElementsByClassName('?')[0]
  playerSign.innerHTML = '<img src="./images/Paper.png" alt="Paper"/>'
});

scissors.addEventListener('click', function() {
  playerSign.getElementsByClassName('?')[0]
  playerSign.innerHTML = '<img src="./images/Scissors.png" alt="Scissors"/>'
});


//Play Round//
function playRound(playerSelection, computerSelection) {
  if (playerSelection === computerSelection) {
    roundWinner = 'tie'
  }
  if (
    (playerSelection === 'rock' && computerSelection === 'scissors') ||
    (playerSelection === 'scissors' && computerSelection === 'paper') ||
    (playerSelection === 'paper' && computerSelection === 'rock')
  ) {
    playerScore++
    roundWinner = 'player'
  }
  if (
    (computerSelection === 'rock' && playerSelection === 'scissors') ||
    (computerSelection === 'scissors' && playerSelection === 'paper') ||
    (computerSelection === 'paper' && playerSelection === 'rock')
  ) {
    computerScore++
    roundWinner = 'computer'
  }
  updateScoreMessage(roundWinner, playerSelection, computerSelection)
}

function updateScore() {
  if (roundWinner === 'tie') {
    scoreMessage.textContent = "It's a tie!"
  } else if (roundWinner === 'player') {
    scoreMessage.textContent = 'You won!'
  } else if (roundWinner === 'computer') {
    scoreMessage.textContent = 'You lost!'
  }

  //Display choices for computer selection//

  computerSign.getElementsByClassName('?')[0]
  computerSign.innerHTML = '<img src="./images/Paper.png" alt="Paper"/>'

  //Random choice for Computer selection//
  function getRandomChoice() {
    let randomNumber = Math.floor(Math.random() * 3)
    switch (randomNumber) {
      case 0:
        return 'rock'
      case 1:
        return 'paper'
      case 2:
        return 'scissors'
    }
  }
  //Computer selection function//
  const computerSelection = getRandomChoice()
  playRound(playerSelection, computerSelection)
  updateChoices(playerSelection, computerSelection)
  updateScore()

  if (isGameOver()) {
    openEndgameModal()
    setFinalMessage()
  }
}

function updateChoices(playerSelection, computerSelection) {
  switch (playerSelection) {
    case 'rock':
      playerSign.textContent = ''
      break
    case 'paper':
      playerSign.textContent = ''
      break
    case 'scissors':
      playerSign.textContent = ''
      break
  }

  switch (computerSelection) {
    case 'rock':
      computerSign.getElementsByClassName('?')[0]
      computerSign.innerHTML = '<img src="./images/Rock.png" alt="Rock"/>'
      break
    case 'paper':
      computerSign.getElementsByClassName('?')[0]
      computerSign.innerHTML = '<img src="./images/Paper.png" alt="Paper"/>'
      break
    case 'scissors':
      computerSign.getElementsByClassName('?')[0]
      computerSign.innerHTML = '<img src="./images/Scissors.png" alt="Scissors"/>'
      break
  }
}

//Update Score Message//

function updateScoreMessage(winner, playerSelection, computerSelection) {
  if (winner === 'player') {
    scoreMessage.textContent = `${capitalizeFirstLetter(
      playerSelection
    )} beats ${computerSelection.toLowerCase()}`
    return
  }
  if (winner === 'computer') {
    scoreMessage.textContent = `${capitalizeFirstLetter(
      playerSelection
    )} is beaten by ${computerSelection.toLowerCase()}`
    return
  }

  scoreMessage.textContent = `${capitalizeFirstLetter(
    playerSelection
  )} ties with ${computerSelection.toLowerCase()}`
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://use.typekit.net/rcz1ikf.css">

  <link rel="shortcut icon" href="favicon.ico" />
  <script src="https://kit.fontawesome.com/4c536a6bd5.js" crossorigin="anonymous">
  </script>
  <title>Rock Paper Scissors</title>
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <header class="heading">
    <h1>ROCK PAPER SCISSORS</h1>
  </header>

  <div class="rps">
    <h2>CHOOSE YOUR WEAPON</h2>
    <h3 class="score-message" id="scoreMessage">
      FIRST TO SCORE 5 POINTS WINS THE GAME</h3>
    </h3>
  </div>

  <div class="score-container">
    <div class="score-box">
      <div class="sign" id="playerSign">❔</div>
      <h2 class="score" id="playerScore">PLAYER:0</h2>
    </div>
    <div class="score-box">
      <div class="sign" id="computerSign">❔</div>
      <h2 class="computerScore">COMPUTER:0</h2>
    </div>
  </div>

  <div class="button-box">
    <input type="image" src="./images/Rock.png" id="rockBtn">
    <input type="image" src="./images/Paper.png" id="paperBtn">
    <input type="image" src="./images/Scissors.png" id="scissorsBtn">
  </div>

</body>

<footer>
  COPYRIGHT &copy
  <script>
    new Date().getFullYear() > 2010 && document.write(+new Date().getFullYear());
  </script> NAME
  <! -- github icon --!>
  <a href="https://github.com/USERNAME" target="_blank">
    <i class="fab fa-github">
      </i>
  </a>
</footer>

</html>

  • 为了避免“blah blah is undefined”控制台错误,您需要为剪刀石头布元素创建引用。
  • 由于这些按钮中的 none 个具有 类,因此您需要使用 getElementById() 通过其 ID 引用它们。
  • 在每个按钮的事件侦听器中,我添加了一行调用您的 playRound() 函数,并将选项发送给它进行比较。请注意,在此调用中,我还可以通过为发送到 playRound().
  • 的第二个变量调用 getRandomChoice() 来提取计算机选项
  • 虽然您可以选择忽略尾随的分号,但它通常被认为是懒惰的并且会降低可读性。建议总是用尾随分号指定语句的结尾。

由于 roundWinner 不是全局定义的变量,因此需要将其传递到 updateScore() 函数中。因为从逻辑上讲,每次你玩一轮,在 playRound() 函数中使用 updateScore(roundWinner);

这样做是有意义的
  • playRound() 函数中添加了 updateScore(roundWinner);
  • 我还将 scoreMessage 添加到上面定义元素的列表中。
  • 为调试添加了一些日志记录

为了保持分数,我向 computerScoreplayerScore 元素添加了 data-score 属性。显然,您很容易以这种方式欺骗游戏,但您可以进行一些验证或将这些分数保留为全局分数。无论哪种方式,您都需要一种方法来保留游戏之间的进度。

  • 添加了首字母大写函数,因为我无法访问您正在做的任何 {}。
  • 删除了 updateScore() 并在 playRound() 中添加了一点点工作 updateScore()updateScoreMessage() 似乎都试图在屏幕上操作相同的字符串, 可能会互相覆盖。

const rock = document.getElementById("rockBtn");
const paper = document.getElementById("paperBtn");
const scissors = document.getElementById("scissorsBtn");
const playerSign = document.getElementById("playerSign");
const scoreMessage = document.getElementById("scoreMessage");
const pScore = document.getElementById("playerScore");
const cScore = document.getElementById("computerScore");

rock.addEventListener('click', function() {
  playerSign.innerHTML = '<img src="./images/Rock.png" alt="Rock"/>';
  playRound('rock', getRandomChoice());
});

paper.addEventListener('click', function() {
  playerSign.innerHTML = '<img src="./images/Paper.png" alt="Paper"/>';
  playRound('paper', getRandomChoice());
});

scissors.addEventListener('click', function() {
  playerSign.innerHTML = '<img src="./images/Scissors.png" alt="Scissors"/>';
  playRound('scissors', getRandomChoice());
});

function playRound(playerSelection, computerSelection) {

  if (playerSelection === computerSelection) {
    roundWinner = 'tie';
  }

  if (
    (playerSelection === 'rock' && computerSelection === 'scissors') ||
    (playerSelection === 'scissors' && computerSelection === 'paper') ||
    (playerSelection === 'paper' && computerSelection === 'rock')
  ) {
    pScore.dataset.score = parseInt(pScore.dataset.score) + 1;
    pScore.textContent = "PLAYER:" + pScore.dataset.score;
    roundWinner = 'player';
  }
  if (
    (computerSelection === 'rock' && playerSelection === 'scissors') ||
    (computerSelection === 'scissors' && playerSelection === 'paper') ||
    (computerSelection === 'paper' && playerSelection === 'rock')
  ) {
    cScore.dataset.score = parseInt(cScore.dataset.score) + 1;
    cScore.textContent = "COMPUTER:" + cScore.dataset.score;
    roundWinner = 'computer';
  }
  console.log("Computer: " + computerSelection + ", Player: " + playerSelection + ", Winner: " + roundWinner + ".");
  updateScoreMessage(roundWinner, playerSelection, computerSelection);
}

function getRandomChoice() {
  let computerSign = document.getElementById("computerSign");
  let rndChoice = Math.floor(Math.random() * 3);
  var txtChoice;
  switch (rndChoice) {
    case 0:
      computerSign.innerHTML = '<img src="./images/Rock.png" alt="Rock"/>';
      txtChoice = 'rock';
      break;
    case 1:
      computerSign.innerHTML = '<img src="./images/Paper.png" alt="Paper"/>';
      txtChoice = 'paper';
      break;
    case 2:
      computerSign.innerHTML = '<img src="./images/Scissors.png" alt="Scissors"/>';
      txtChoice = 'scissors';
      break;
  }
  return txtChoice;
}

function updateScoreMessage(winner, playerSelection, computerSelection) {
  var txtMessage = '';
  if (winner === 'player') {
    scoreMessage.textContent = 'You win! Selection: ' + flCapital(playerSelection) + ' beats ' + flCapital(computerSelection) + '!';
    return;
  }
  if (winner === 'computer') {
    scoreMessage.textContent = 'You lose! Selection: ' + flCapital(computerSelection) + ' beats ' + flCapital(playerSelection) + '!';
    return;
  }
  scoreMessage.textContent = 'Your selection: ' + flCapital(playerSelection) + ' ties with ' + flCapital(computerSelection) + '!';
}

function flCapital(str) {
  if (!str) return;
  return str.match("^[a-z]") ? str.charAt(0).toUpperCase() + str.substring(1) : str;
}
<!DOCTYPE html>
<html lang="en">

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="https://use.typekit.net/rcz1ikf.css">

    <link rel="shortcut icon" href="favicon.ico" />
    <script src="https://kit.fontawesome.com/4c536a6bd5.js" crossorigin="anonymous">
    </script>
    <title>Rock Paper Scissors</title>
    <link rel="stylesheet" href="styles.css">
  </head>

  <body>

    <header class="heading">
      <h1>ROCK PAPER SCISSORS</h1>
    </header>

    <div class="rps">
      <h2>CHOOSE YOUR WEAPON</h2>
      <h3 class="score-message" id="scoreMessage">
        FIRST TO SCORE 5 POINTS WINS THE GAME
      </h3>
    </div>

    <div class="score-container">
      <div class="score-box">
        <div class="sign" id="playerSign">❔</div>
        <!-- added data-score attribute -->
        <h2 class="score" id="playerScore" data-score="0">PLAYER:0</h2>
      </div>
      <div class="score-box">
        <div class="sign" id="computerSign">❔</div>
        <!-- added data-score attribute -->
        <h2 class="score" id="computerScore" data-score="0">COMPUTER:0</h2>
      </div>
    </div>

    <div class="button-box">
      <input type="image" src="./images/Rock.png" id="rockBtn">
      <input type="image" src="./images/Paper.png" id="paperBtn">
      <input type="image" src="./images/Scissors.png" id="scissorsBtn">
    </div>

  </body>

  <footer>
    COPYRIGHT &copy; <script>
      new Date().getFullYear() > 2010 && document.write(+new Date().getFullYear());

    </script> NAME
    <! -- github icon --!>
      <a href="https://github.com/USERNAME" target="_blank">
        <i class="fab fa-github">
        </i>
      </a>
  </footer>

</html>

https://jsfiddle.net/wqmzyk67/4/

问题是你写的:

rock.addEventListener('click', function() {

但你从未定义过 'rock' 是什么。你错过了添加剪刀石头布的 const/variable 定义。

const rock = getElementById('rockBtn')

等等