在JS Rock,Paper,剪刀游戏中,尝试将span元素设置为等于变量值

时间:2018-12-31 02:10:53

标签: javascript html dom

我正在编写一个程序来播放石头,纸,剪刀。在编写代码时,一切正常,直到我添加了:

userScore_span.InnerHTML = userScore;

行。在测试win功能时,我添加了console.log('you win');并且效果很好,但是当我从上方添加该行时,按下三个按钮中的任何一个按钮时我都会出错。

鉴于赢得比赛后userScore增加,我正在尝试将结果从userScore中继到userScore_span

userScore++;
userScore_span.innerHTML = userScore;

但是,当我按下任何按钮时,都会出现以下错误:

Uncaught TypeError: Cannot set property 'innerHTML' of null
at lose (app.js:34)
at game (app.js:58)

我不确定chrome开发工具的含义。如何解决?

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_p = document.querySelector(".result > p");
const rock_div = document.getElementById('r');
const paper_div = document.getElementById('p');
const scissors_div = document.getElementById('s');

function getComputerChoice() {
  const choices = ['r', 'p', 's'];
  const randomNumber = (Math.floor(Math.random() * 3));
  return choices[randomNumber];
}

function convertToWord(letter) {
  if (letter === "r") return "Rock";
  if (letter === "p") return "Paper";
  return "Scissors";
}

function win(userChoice, computerChoice) {
  userScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} beats ${convertToWord(computerChoice)}${smallCompWord}. You win!`;
}

function lose(userChoice, computerChoice) {
  computerScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} loses to ${convertToWord(computerChoice)}${smallCompWord}. You lost!`;
}

function draw(userChoice, computerChoice) {
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} equals ${convertToWord(computerChoice)}${smallCompWord}. It's a draw`;
}

function game(userChoice) {
  const computerChoice = getComputerChoice();
  switch (userChoice + computerChoice) {
    case "rs":
    case "pr":
    case "sp":
      win(userChoice, computerChoice);
      break;
    case 'rp':
    case 'ps':
    case 'sr':
      lose(userChoice, computerChoice);
      break;
    case 'rr':
    case 'pp':
    case 'ss':
      draw(userChoice, computerChoice);
      break;
  }
}

function main() {
  rock_div.addEventListener('click', function() {
    game('r');
  })
  paper_div.addEventListener('click', function() {
    game('p');
  })
  scissors_div.addEventListener('click', function() {
    game('s');
  })
};

main();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #24272E;
  font-family: avenir;
}

header {
  background: white;
  padding: 20px;
}


/*header each one*/

header>h1 {
  color: #24272E;
  text-align: center;
}

.score-board {
  border: 3px solid white;
  border-radius: 4px;
  width: 200px;
  margin: 20px auto;
  /*20px (top/bottom) & center (left/right) */
  color: white;
  padding: 15px 20px;
  text-align: center;
  font-size: 46px;
  position: relative;
}

.badge {
  background: #E2584D;
  font-size: 14px;
  padding: 2px 10px;
}

#user-label {
  position: absolute;
  top: 30px;
  left: -25px;
}

#computer-label {
  position: absolute;
  top: 30px;
  right: -30px;
}

.result {
  font-size: 40px;
  color: white;
}

.result>p {
  text-align: center;
  font-weight: bold;
}

.choices {
  text-align: center;
  margin-top: 50px;
}

.choice {
  display: inline-block;
  border: 4px solid white;
  border-radius: 50%;
  padding: 10px;
  margin: 0 20px;
  transition: all 0.3s ease;
}

.choice:hover {
  cursor: pointer;
  background: darkblue;
}

img {
  height: 100px;
  width: 100px;
}

#action-message {
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 20px;
  margin-top: 20px
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Rock Paper Scissors</title>
  <meta name="description" content="DESCRIPTION">
  <link rel="stylesheet" href="styles.css">

</head>

<body>
  <header>
    <h1>Rock Paper Scissors</h1>
  </header>
  <div class="score-board">
    <div id="user-label" class="badge">user</div>
    <div id="computer-label" class="badge">comp</div>
    <span idea="user-score">0</span>:<span idea="computer-score">0</span>
  </div>

  <div class="result">
    <p>Paper cover rock. You win!</p>
  </div>

  <div class="choices">
    <div class="choice" id="r">
      <img src="images/rock.png" alt="rock">
    </div>
    <div class="choice" id="p">
      <img src="images/paper.png" alt="paper">
    </div>
    <div class="choice" id="s">
      <img src="images/scissors.png" alt="scissors">
    </div>
  </div>

  <p id="action-message">Make your move</p>






</body>
<script src="app.js"></script>

</html>

2 个答案:

答案 0 :(得分:1)

在您的错字idea= / id=旁边...
您可以使用索引整数来极大地最小化游戏逻辑和编码。

整数游戏

  • 对用户按钮使用data-*属性。这些属性应包含数值0, 1, 2。点击后,该值将代表玩家的选择。
  • AI也应该播放数字:const AI = ~~(Math.random() * 3) // 0, 1, 2

现在您知道AI和Player都使用整数(而不是奇怪的字母组合),您可以将移动名称存储到数组const moves = ["Rock", "Paper", "Scissors"];中(其中0 Rock ...等)

岩石纸剪刀逻辑

游戏具有 3 个可能的全面解决方案 PL胜利,AI胜利,平局。 让我们以相同的顺序将这些“ human” 值转换为整数:

  • 0 = PL胜利
  • 1 = AI胜利
  • 2 =抽奖

这里是计算这些的方法:

绘画

计算抽奖是最简单的。这是AIPL整数相等的时候。 让我们退回2

result = PL === AI ? 2

玩家获胜

要计算玩家获胜,只需将AI选择加1,然后取模3 。如果此操作的结果等于玩家的选择,那么玩家一定赢了! 让我们退回0

人工智能获胜

否则,由于我们的游戏只有3种可能的状态,因此这不是平局,也不是​​玩家获胜,而AI获胜也必须如此! 让我们返回1

const result = PL===AI ? 2 : (AI+1)%3 === PL? 0 : 1; // Possible results: 0, 1, 2

拥有基于游戏结果索引的很酷的事情是,现在您还可以使用messages = ["You won!", "AI won", "it's a draw!", ]之类的消息数组,并通过结果索引获取所需的消息!。和奖金!您还可以增加score数组值,其中0是玩家的索引,1是AI!

const moves = ["Rock", "Paper", "Scissors"],
  messages  = ["You won!", "AI won", "It's a draw!"], // [PL, AI, draw]
  score     = [0, 0, 0],                              // [PL, AI, draw]
  EL = sel => document.querySelector(sel),
  EL_result  = EL("#result"),
  EL_PLScore = EL("#PLScore"),
  EL_AIScore = EL("#AIScore");

function game() {
  const PL = +this.dataset.playermove;  // Get dataset value as integer
  const AI = ~~(Math.random() * 3);     // All you need: 0, 1, 2
  const result = PL === AI ? 2 : (AI + 1) % 3 === PL ? 0 : 1; // 0=PLwins 1=AIwins 2=draw 

  score[result]++; // Increment PL or AI's score (Increments number of draws too ;) )
  EL_result.innerHTML = `You: ${moves[PL]}<br>AI: ${moves[AI]}<br>${messages[result]}`;
  EL_PLScore.textContent = score[0];
  EL_AIScore.textContent = score[1];
}

// EVENTS:
[...document.querySelectorAll("[data-playermove]")]
.forEach(el => el.addEventListener("click", game));
*{margin:0;padding:0;box-sizing:border-box;}body{background-color:#24272E;font-family:avenir;}header {background:white;padding:20px;}header>h1{color:#24272E;text-align:center;}.score-board{border:3px solid white;border-radius:4px;width:200px;margin:20px auto;color:white;padding:15px 20px;text-align:center;font-size:46px;position:relative;}.badge{background:#E2584D;font-size:14px;padding:2px 10px;}#user-label{position:absolute;top:30px;left:-25px;}#computer-label{position:absolute;top:30px;right:-30px;}#result{font-size:1.4em;color:white;text-align:center;font-weight: bold;}.choices{text-align:center;margin-top:50px;}[data-playermove]{display:inline-block;border:4px solid white;border-radius:50%;padding:10px;margin:0 20px;transition:all 0.3s ease;}[data-playermove]:hover{cursor:pointer;background:darkblue;}img{height:100px;width:100px;}
<div class="score-board">
  <div id="user-label" class="badge">user</div>
  <div id="computer-label" class="badge">comp</div>
  <span id="PLScore">0</span>:<span id="AIScore">0</span>
</div>

<div id="result"></div>

<div class="choices">
  <div data-playermove="0">ROCK</div>
  <div data-playermove="1">PAPER</div>
  <div data-playermove="2">SCISSORS</div>
</div>

答案 1 :(得分:0)

错别字:print(list_obj) # will work # Frequencies # tobacco$gender # Type: Factor # # Freq % Valid % Valid Cum. % Total % Total Cum. # ----------- ------ --------- -------------- --------- -------------- # F 489 50.00 50.00 48.90 48.90 # M 489 50.00 100.00 48.90 97.80 # <NA> 22 2.20 100.00 # Total 1000 100.00 100.00 100.00 100.00 # # tobacco$age.gr # Type: Factor # # Freq % Valid % Valid Cum. % Total % Total Cum. # ----------- ------ --------- -------------- --------- -------------- # 18-34 258 26.46 26.46 25.80 25.80 # 35-50 241 24.72 51.18 24.10 49.90 # 51-70 317 32.51 83.69 31.70 81.60 # 71 + 159 16.31 100.00 15.90 97.50 # <NA> 25 2.50 100.00 # Total 1000 100.00 100.00 100.00 100.00 <> idea

更改此:

id

<span idea="user-score">0</span>:<span idea="computer-score">0</span>

<span id="user-score">0</span>:<span id="computer-score">0</span>
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_p = document.querySelector(".result > p");
const rock_div = document.getElementById('r');
const paper_div = document.getElementById('p');
const scissors_div = document.getElementById('s');

function getComputerChoice() {
  const choices = ['r', 'p', 's'];
  const randomNumber = (Math.floor(Math.random() * 3));
  return choices[randomNumber];
}

function convertToWord(letter) {
  if (letter === "r") return "Rock";
  if (letter === "p") return "Paper";
  return "Scissors";
}

function win(userChoice, computerChoice) {
  userScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} beats ${convertToWord(computerChoice)}${smallCompWord}. You win!`;
}

function lose(userChoice, computerChoice) {
  computerScore++;
  userScore_span.innerHTML = userScore;
  computerScore_span.innerHTML = computerScore;
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} loses to ${convertToWord(computerChoice)}${smallCompWord}. You lost!`;
}

function draw(userChoice, computerChoice) {
  const smallUserWord = "user".fontsize(3).sub();
  const smallCompWord = "comp".fontsize(3).sub();
  result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} equals ${convertToWord(computerChoice)}${smallCompWord}. It's a draw`;
}

function game(userChoice) {
  const computerChoice = getComputerChoice();
  switch (userChoice + computerChoice) {
    case "rs":
    case "pr":
    case "sp":
      win(userChoice, computerChoice);
      break;
    case 'rp':
    case 'ps':
    case 'sr':
      lose(userChoice, computerChoice);
      break;
    case 'rr':
    case 'pp':
    case 'ss':
      draw(userChoice, computerChoice);
      break;
  }
}

function main() {
  rock_div.addEventListener('click', function() {
    game('r');
  })
  paper_div.addEventListener('click', function() {
    game('p');
  })
  scissors_div.addEventListener('click', function() {
    game('s');
  })
};

main();
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #24272E;
  font-family: avenir;
}

header {
  background: white;
  padding: 20px;
}


/*header each one*/

header>h1 {
  color: #24272E;
  text-align: center;
}

.score-board {
  border: 3px solid white;
  border-radius: 4px;
  width: 200px;
  margin: 20px auto;
  /*20px (top/bottom) & center (left/right) */
  color: white;
  padding: 15px 20px;
  text-align: center;
  font-size: 46px;
  position: relative;
}

.badge {
  background: #E2584D;
  font-size: 14px;
  padding: 2px 10px;
}

#user-label {
  position: absolute;
  top: 30px;
  left: -25px;
}

#computer-label {
  position: absolute;
  top: 30px;
  right: -30px;
}

.result {
  font-size: 40px;
  color: white;
}

.result>p {
  text-align: center;
  font-weight: bold;
}

.choices {
  text-align: center;
  margin-top: 50px;
}

.choice {
  display: inline-block;
  border: 4px solid white;
  border-radius: 50%;
  padding: 10px;
  margin: 0 20px;
  transition: all 0.3s ease;
}

.choice:hover {
  cursor: pointer;
  background: darkblue;
}

img {
  height: 100px;
  width: 100px;
}

#action-message {
  text-align: center;
  color: white;
  font-weight: bold;
  font-size: 20px;
  margin-top: 20px
}