Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

Rock Paper Scissors game is not working JavaScript

So I've been trying to figure out what is going on with my JavaScript that is not working. I'm a beginner and just started learning JavaScript a week ago. I've went through every question here regarding this but I'm still stuck and can't figure this out. This is my and HTML JavaScript code. My buttons aren't functioning, and this code just doesn't do anything.

const buttons = document.querySelectorAll(".button");
const container = document.querySelector("#results-container");
const playerScore = document.querySelector("#user-score");
const computerScore = document.querySelector("#computer-score");
const scoreLabel = document.querySelector("#score-label");

buttons.forEach((button) => {
  button.addEventListener("click", () => {

    playRound(playerSelection, computerSelection);

    if (playerScore === 5 || computerScore === 5) {
      declareWinner();
    }
  });
});
const myArray = ["Rock", "Paper", "Scissors"];

function computerPlay() {
  return myArray[~~(Math.random() * myArray.length)];
}

function playRound(playerSelection, computerSelection) {
  computerSelection = computerPlay().toLowerCase();;
  playerSelection = playerSelection.toLowerCase()

  if (playerSelection === 'rock') {
    if (computerSelection === 'raper') {
      displayResult('You Lose! Paper beats Rock');
    } else if (computerSelection === 'scissors') {
      displayResult('You Win! Rock beats Scissors');
    } else {
      displayResult("It's a tie");
    }
<div class="button">
  <div id="rockbutton" class="button">
    <img src="rocks.jpg" alt="rock" height="30px">
  </div>
  <div id="paperbutton" class="button">
    <img src="papers.jpg" alt="paper" height="30px">
  </div>
  <div id="scissorsbutton" class="button">
    <img src="scissors.jpg" alt="scissor" height="30px">
  </div>
  <div id="score-label">

    <p class="label1">you</p>
    <p class="label2">computer</p>
    <div id="score-container">
      <div id="player-score" class="score">0</div>
      <div class="player-selection"></div>
      <div id="computer-score" class="score">0</div>
      <div class="computer-selection"></div>
      <div id="results-container"></div>
    </div>
    </main>
    <script src="script.js"></script>
    </body>

    </html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I got kind of obsessed fiddling with this while watching tv. There's probably some really clever way to determine a winner with bitwise flags or something, but this is nice and simple. Someone else can replace the computer move with Machine Learning.

window.addEventListener("DOMContentLoaded", () => {
  const ctx = document.getElementById("scores");
  const output = document.querySelector("#output");
  const buttons = document.querySelectorAll("button");
  buttons.forEach((button) => button.addEventListener("click", clicked));
  const history = [];
  const scores = {
    p: 1,
    c: 1
  };

  const scoreChart = displayScores(scores, ctx);

  function clicked(event) {
    const pthrow = event.target.id;
    const cthrow = chooseThrow(history);
    const winner = determineWinner(pthrow, cthrow);
    const timestamp = Date.now();
    const round = {
      pthrow,
      cthrow,
      winner,
      timestamp
    };
    history.push(round);
    displayResult(scores, scoreChart, output, round);
  }
});

function determineWinner(pthrow, cthrow) {
  if (pthrow === cthrow) return "t";
  else if (pthrow == "r") return cthrow == "p" ? "c" : "p";
  else if (pthrow == "p") return cthrow == "s" ? "c" : "p";
  else if (pthrow == "s") return cthrow == "r" ? "c" : "p";
}

function getThrowLabel(code) {
  return {
    r: "Rock",
    p: "Paper",
    s: "Scissors"
  }[code];
}

function getResultLabel(code) {
  return {
    t: "tie.",
    p: "win!",
    c: "lose."
  }[code];
}

function displayResult(scores, scoreChart, output, round) {
  if (round.winner === "c") scores.c++;
  if (round.winner === "p") scores.p++;

  updateScores(scores, scoreChart);
  displayText(output, round);
}

function displayScores(scores, ctx) {
  return new Chart(ctx, {
    type: "doughnut",
    data: {
      labels: ["Player", "Computer"],
      datasets: [{
        data: [scores.p, scores.c],
        backgroundColor: ["rgb(255, 205, 86)", "rgb(255, 99, 132)"],
      }, ],
    },
    options: {
      rotation: 0.5 * Math.PI,
    },
  });
}

function updateScores(scores, chart) {
  chart.data.datasets[0].data = [scores.p, scores.c];
  chart.update();
}

function displayText(output, round) {
  // TODO: yack about player history to make them think

  output.append(`You threw ${getThrowLabel(round.pthrow)}
`);
  output.append(`Computer threw ${getThrowLabel(round.cthrow)}
`);
  output.append(`You ${getResultLabel(round.winner)}
`);
  output.scrollTop = output.scrollHeight;
}

function chooseThrow(_history) {
  // TODO: use history to choose a better throw?

  // pick one at random
  return ["r", "p", "s"][~~(Math.random() * 3)];
}
#scoresContainer {
  position: relative;
  height: 300px;
}

#output {
  white-space: pre;
  height: 72px;
  overflow: hidden;
  overflow-y: scroll;
  scroll-behavior: smooth;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.4/Chart.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />

<div class="container">
  <div class="row">
    <h1>Roshambo</h1>
  </div>
  <div class="row">
    <div class="eight columns">
      <button id="r">Rock</button>
      <button id="p">Paper</button>
      <button id="s">Scissors</button>
      <div class="row" id="output"></div>
    </div>
    <div class="four columns">
      <h5>Scores</h5>
      <div id="scoresContainer">
        <canvas id="scores" width="100%" height="100%"></canvas>
      </div>
    </div>
  </div>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...