剪刀石头布。似乎无法使按钮正常工作。 (初学者)

时间:2019-01-10 22:11:19

标签: javascript

我正在做一个石头剪刀布游戏。一切都在控制台中正常工作,所以现在我正在致力于使按钮正常工作。我已经选择了每个按钮并添加了一个事件侦听器,但是我为实现它而大吃一惊。

当我单击“开始”时,游戏开始,但是当我单击(例如)“摇滚”按钮时,它立即以“摇滚”作为唯一的玩家选择运行了5次游戏。我尝试将其分解:循环运行了5次,并没有停止并等待第二次单击。

这可能与我不同功能的定位有关。

在此先感谢任何阅读此书的人!

var scorePlayer = 0;
    var scoreComputer = 0;
    let displayPlayerScore = document.getElementById("playerScore");
    let displayComputerScore = document.getElementById("computerScore");
    let rockButton = document.getElementById("rock");
    let paperButton = document.getElementById("paper");
    let scissorsButton = document.getElementById("scissors");
    let startButton = document.getElementById("startGame");
    let playerPick = "";
    
    let computerPlay = () => {
      const pick = ["rock", "paper", "scissors"];
      computerPick = pick[Math.floor(Math.random() * pick.length)];
    };
    
    let playerPlay = () => {
      rockButton.addEventListener("click", function(){
        return playerPick = "rock";
      });
      
      paperButton.addEventListener("click", function(){
       return playerPick = "paper";
      });
      
      scissorsButton.addEventListener("click", function(){
        return playerPick = "scissors";
      });
      // playerPick = prompt("what's your pick?").toLowerCase();
    };
    
    // game is played for 5 rounds max
    let game = () => {
      for (var i = 0; i < 5; i++) {
        playerPlay();
        computerPlay();
        let playRound = (p, c) => {
          if (p === c) {
            console.log("=================")
            console.log("Draw. PLAY AGAIN!");
            console.log("=================")
          } else if (c === "rock" && p === "paper") {
            scorePlayer += 1;
            displayPlayerScore.textContent = scorePlayer;
            console.log("=================")
            console.log(`${playerPick} beats ${computerPick}. \n Player score: ${scorePlayer}`);
            console.log("=================")
          } else if (c === "paper" && p === "scissors") {
            scorePlayer += 1;
            displayPlayerScore.textContent = scorePlayer;
            console.log("=================")
            console.log("Player wins. Player score: " + scorePlayer);
            console.log("=================")
          } else if (c === "scissors" && p === "rock") {
            scorePlayer += 1;
            displayPlayerScore.textContent = scorePlayer;
            console.log("=================")
            console.log("Player wins. Player score: " + scorePlayer);
            console.log("=================")
          } else if (c === "rock" && p === "scissors") {
            scoreComputer += 1;
            displayComputerScore.textContent = scoreComputer;
            console.log("=================")
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================")
          } else if (c === "paper" && p === "rock") {
            scoreComputer += 1;
            displayComputerScore.textContent = scoreComputer;
            console.log("=================")
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================")
          } else if (c === "scissors" && p === "paper") {
            scoreComputer += 1;
            displayComputerScore.textContent = scoreComputer;
            console.log("=================")
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================")
          }
        };
        playRound(playerPick, computerPick);
      }
    };
    
    startButton.addEventListener("click", function(){
      game();
    });
    
    console.log("Score player: " + scorePlayer);
    console.log("Score computer: " + scoreComputer);
<!DOCTYPE html>
    <!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
    <!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
    <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title></title>
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="">
        </head>
        <body>
            <div>
                <p>Player Score: <span id="playerScore">0</span></p>
                <p>Computer Score: <span id="computerScore">0</span></p>
            </div>
            <div>
                <button id="rock" value="rock">ROCK</button>
                <button id="paper" value="paper">PAPER</button>
                <button id="scissors" value="scissors">SCISSORS</button>
            </div>
            <div>
                <button id="startGame">START</button>
            </div>
            <script src="script.js" async defer></script>
        </body>
    </html>

2 个答案:

答案 0 :(得分:0)

您的一般问题是,在您的按钮侦听器中返回值对游戏按预期工作绝对没有任何作用。

rockButton.addEventListener("click", function(){
     //does nothing
     return playerPick = "rock";
});

它应该是这样的(我使用的功能尚未实现。它们只是出于逻辑解释的目的):

rockButton.addEventListener("click", function(){
     playerPick = "rock";
     //get the computer's next move
     computerMove();
     //determine the winner
     calculateRoundWinner();
     //is the game finished?
     determineIfDone();
     //update the HTML to reflect the current points
     updateUI();
});

我了解您是一个初学者,但是这里是“我的”石头,纸,剪刀的版本。不要犹豫地指出任何需要详细解释的内容。

/** order of choices are super important
* Scissors wins against paper, paper aginst rock, and rock against scissors
* Suppose: i (index of player choice) and c (index of computer choice)
* (i+1) % choices.length === c determines if player won
* (i.e: i = 0 (scissors), c = 1 (paper), ((0+1) % 3) === 1, player win
* (i.e: i = 2 (rock), c = 0 (scissors), ((2+1) % 3) === 0, player win
*/
const choices = ["scissors", "paper", "rock"];
const ps = document.getElementById("playerScore"),
      cs = document.getElementById("computerScore"),
      ds = document.getElementById("draws"),
      r  = document.getElementById("round"),
      s  = document.getElementById("startGame");

/**
* Store all relevant data in an object
*/
const data = {
  playerScore: 0,
  computerScore: 0,
  draws: 0,
  round: 0,
  running: false
}

/**
* Fancy way of adding event listeners to each of your buttons
*/
choices
.map(a=>document.getElementById(a))
.forEach((ele,i)=>ele.addEventListener("click", ()=>choiceHandler(i)));

function getComputerMove(){
  return Math.floor(Math.random() * choices.length);
}

function choiceHandler(i){
   if(!data.running) return;
   const c = getComputerMove();
   switch(true){
      //player wins round
      case (i+1) % choices.length === c:
        data.playerScore++;
        break;
      //draw
      case i === c:
        data.draws++;
        break;
      //compuer wins round
      default:
        data.computerScore++;
  }
  //increment round everytime player makes a choice
  data.round++;
  if(data.round > 5){
    //stop the game
    data.running = false;
    //update final message of the winner
    data.round = data.playerScore > data.computerScore ? "You win" : "You lose";
  }
  updateUI();
}

function updateUI(){
  ps.innerText = data.playerScore;
  cs.innerText = data.computerScore;
  ds.innerText = data.draws;
  r.innerText  = data.round;
}

s.addEventListener("click", function(){
  //on start, set round to 1
  data.round = 1;
  //set all values to 0 (in case a previous round was played, exactly like a reset)
  data.computerScore = data.playerScore = data.draws = 0;
  data.running = true;
  updateUI();
})
div {
  display: flex;
  margin-top: 10px;
}

div:first-child {
  justify-content: space-between;
}

div > p {
  background-color: grey;
  padding: 5px 10px;
  border: 1px solid black;
  color: white;
}

div > button {
  flex-grow: 1;
  padding: 5px 10px;
}

div > button:hover {
  background-color: green;
  color: white;
}
<div>
  <p>Round: <span id="round">0</span></p>
  <p>Player Score: <span id="playerScore">0</span></p>
  <p>Computer Score: <span id="computerScore">0</span></p>
  <p>Draws: <span id="draws">0</span></p>
</div>
<div>
  <button id="rock" value="rock">ROCK</button>
  <button id="paper" value="paper">PAPER</button>
  <button id="scissors" value="scissors">SCISSORS</button>
</div>
<div>
  <button id="startGame">START</button>
</div>

答案 1 :(得分:0)

问题

每次单击按钮,您的for循环都会迭代5次。因此,一旦您点击START,就会“玩了5场游戏”。

想法

我假设每次单击START时都要进行一次迭代,所以要进行一轮游戏。您不需要为此需要循环,因为您的按钮已经触发了game()函数。当然,这并不意味着您可以使用for循环(您可以自由地做自己想做的事!)

我的解决方案

fiddled有点,这就是我想您要做的,在这里我尝试尽可能少地更改您的代码(@kemicofa提供了更专业的方法)

var scorePlayer = parseInt(document.getElementById("playerScore").innerHTML);
var scoreComputer = parseInt(document.getElementById("computerScore").innerHTML);
let count = 0;

let rockButton = document.getElementById("rock");
let paperButton = document.getElementById("paper");
let scissorsButton = document.getElementById("scissors");
let startButton = document.getElementById("startGame");
let resetButton = document.getElementById("resetGame");
let playerPick = "";
    
let computerPlay = () => {
  const pick = ["rock", "paper", "scissors"];

  computerPick = pick[Math.floor(Math.random() * 	  pick.length)];
};

let playerPlay = () => {

  rockButton.addEventListener("click", function(){
   playerPick = 'rock';
 });
      
  paperButton.addEventListener("click", function(){
    playerPick = 'paper';
  });

  scissorsButton.addEventListener("click", function(){
    playerPick = 'rock';
  });

}

// playerPick = prompt("what's your pick?").toLowerCase();

// game is played for 5 rounds max

let game = () => {
    
    if (count >= 5) {
     alert('Maximum rounds played.')
    } else {
    	alert(`Round ${count}`);
      
      playerPlay();
    computerPlay();
    
    let playRound = (p, c) => {
          if (p === c) {
            console.log("=================")
            console.log("Draw. PLAY AGAIN!");
            console.log("=================")
          } else if (c === "rock" && p === "paper") {
            scorePlayer++;
            document.getElementById('playerScore').innerHTML = scorePlayer;
            console.log("=================")
            console.log(`${playerPick} beats ${computerPick}. \n Player score: ${scorePlayer}`);
            console.log("=================")
          } else if (c === "paper" && p === "scissors") {
            scorePlayer += 1;
            document.getElementById('playerScore').innerHTML = scorePlayer;
            console.log("=================");
            console.log("Player wins. Player score: " + scorePlayer);
            console.log("=================");
          } else if (c === "scissors" && p === "rock") {
            scorePlayer += 1;
            document.getElementById('playerScore').innerHTML = scorePlayer;
            console.log("=================");
            console.log("Player wins. Player score: " + scorePlayer);
            console.log("=================");
          } else if (c === "rock" && p === "scissors") {
            scoreComputer += 1;
            document.getElementById('computerScore').innerHTML = scoreComputer;
            console.log("=================");
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================");
          } else if (c === "paper" && p === "rock") {
            scoreComputer += 1;
            document.getElementById('computerScore').innerHTML = scoreComputer;
            console.log("=================");
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================");
          } else if (c === "scissors" && p === "paper") {
            scoreComputer += 1;
            document.getElementById('computerScore').innerHTML = scoreComputer;
            console.log("=================");
            console.log("Computer wins. Score of computer: " + scoreComputer);
            console.log("=================");
          }
        };
        playRound(playerPick, computerPick);
    }
        count++;
    };
    
    startButton.addEventListener("click", function(){
      game();
    });
    
    resetButton.addEventListener("click", function(){
      count = 0;
      document.getElementById('playerScore').innerHTML = 0;
      document.getElementById('computerScore').innerHTML = 0;
    });
    
console.log("Score player: " + scorePlayer);
console.log("Score computer: " + scoreComputer);
<!DOCTYPE html>
    <!--[if lt IE 7]>      <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
    <!--[if IE 7]>         <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
    <!--[if IE 8]>         <html class="no-js lt-ie9"> <![endif]-->
    <!--[if gt IE 8]><!--> <html class="no-js"> <!--<![endif]-->
        <head>
            <meta charset="utf-8">
            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <title></title>
            <meta name="description" content="">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <link rel="stylesheet" href="">
        </head>
        <body>
            <div>
                <p>Player Score: <span id="playerScore">0</span></p>
                <p>Computer Score: <span id="computerScore">0</span></p>
            </div>
            <div>
                <button id="rock" value="rock">ROCK</button>
                <button id="paper" value="paper">PAPER</button>
                <button id="scissors" value="scissors">SCISSORS</button>
            </div>
            <div>
                <button id="startGame">START</button>
                <button id="resetGame">RESET</button>
            </div>
            <script src="script.js" async defer></script>
        </body>
    </html>