尝试在 JS Rock、Paper、Scissors 游戏中设置一个 span 元素等于一个变量值 [英] Trying to set a span element equal to a variable value in a JS Rock, Paper, Scissors Game

查看:15
本文介绍了尝试在 JS Rock、Paper、Scissors 游戏中设置一个 span 元素等于一个变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个程序来玩石头、纸和剪刀.在我编写代码时,一切都很顺利,直到我添加了:

userScore_span.InnerHTML = userScore;

线.在测试 win 功能时,我添加了一个 console.log('you win');它工作正常,但是一旦我从上面添加了这一行,当我按下三个按钮中的任何一个时,就会出错.

我正在尝试将结果从 userScore 传递到 userScore_span,因为 userScore 在赢得游戏后会增加

userScore++;userScore_span.innerHTML = userScore;

然而,当我按下任何按钮时,我得到一个错误:

未捕获的类型错误:无法设置 null 的属性innerHTML"输了(app.js:34)在游戏中 (app.js:58)

我不确定 chrome Dev 工具是什么意思.如何解决这个问题?

让 userScore = 0;让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");constrock_div = document.getElementById('r');const paper_div = document.getElementById('p');const scissors_div = document.getElementById('s');函数 getComputerChoice() {const 选择 = ['r', 'p', 's'];const randomNumber = (Math.floor(Math.random() * 3));返回选择[随机数];}函数 convertToWord(字母){如果(字母 ===r")返回摇滚";if (let === "p") return "Paper";返回 "剪刀";}功能赢(用户选择,计算机选择){用户评分++;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} 胜过 ${convertToWord(computerChoice)}${smallCompWord}.你赢了!`;}功能丢失(用户选择,计算机选择){计算机分数++;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} 输给 ${convertToWord(computerChoice)}${smallCompWord}.你输了!`;}函数绘制(用户选择,计算机选择){const smallUserWord = "user".fontsize(3).sub();const smallCompWord = "comp".fontsize(3).sub();result_p.innerHTML = `${convertToWord(userChoice)}${smallUserWord} 等于 ${convertToWord(computerChoice)}${smallCompWord}.这是平局`;}功能游戏(用户选择){const computerChoice = getComputerChoice();开关(用户选择 + 计算机选择){案例rs":案例公关":案例sp":赢(用户选择,计算机选择);休息;案例'rp':案例ps":案例'sr':失去(用户选择,计算机选择);休息;案例'rr':案例'pp':案例's':绘制(用户选择,计算机选择);休息;}}函数主(){Rock_div.addEventListener('点击', function() {游戏('r');})paper_div.addEventListener('点击', function() {游戏('p');})scissors_div.addEventListener('click', function() {游戏('s');})};main();

* {边距:0;填充:0;box-sizing: 边框框;}身体 {背景颜色:#24272E;字体系列:avenir;}标题{背景:白色;填充:20px;}/*每个标题*/标题> h1 {颜色:#24272E;文本对齐:居中;}.计分板{边框:3px纯白色;边框半径:4px;宽度:200px;边距:20px 自动;/*20px(顶部/底部)&中心(左/右)*/白颜色;填充:15px 20px;文本对齐:居中;字体大小:46px;位置:相对;}.徽章 {背景:#E2584D;字体大小:14px;填充:2px 10px;}#用户标签{位置:绝对;顶部:30px;左:-25px;}#计算机标签{位置:绝对;顶部:30px;右:-30px;}.结果 {字体大小:40px;白颜色;}.结果> p {文本对齐:居中;字体粗细:粗体;}.选择{文本对齐:居中;边距顶部:50px;}.选择 {显示:内联块;边框:4px纯白色;边界半径:50%;填充:10px;边距:0 20px;过渡:全0.3s缓和;}.选择:悬停{光标:指针;背景:深蓝色;}图片{高度:100px;宽度:100px;}#action-message {文本对齐:居中;白颜色;字体粗细:粗体;字体大小:20px;边距顶部:20px}

<html lang="zh-cn"><头><meta charset="UTF-8"><title>石头剪刀布</title><meta name="description" content="DESCRIPTION"><link rel="stylesheet" href="styles.css"><身体><标题><h1>石头剪刀布</h1></标题><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 class="result"><p>纸盖岩.你赢了!</p>

<div class="选择"><div class="choice" id="r"><img src="images/rock.png" alt="rock">

<div class="choice" id="p"><img src="images/paper.png" alt="paper">

<div class="choice" id="s"><img src="images/scissors.png" alt="scissors">

<p id="action-message">开始行动</p><script src="app.js"></script></html>

解决方案

除了你的错别字 idea=/id= ...
您可以通过使用索引整数来大幅缩小您的游戏逻辑和代码.

整数游戏

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

石头剪刀布逻辑

游戏有三种可能的回合分辨率PL 获胜,AI 获胜,平局.让我们以相同的顺序将那些 "human" 值转换为整数:

以下是计算这些的方法:

画图

计算平局是最简单的.当 AIPL 整数相等时.让我们返回2

result = PL === AI ?2

玩家获胜

要计算玩家获胜,只需将 AI 选择增加 1 并取模 3.如果这个操作的结果等于玩家的选择,那么玩家一定赢了!让我们返回0

人工智能获胜

另外,由于我们的游戏只有 3 种可能的状态,所以它不是平局,也不是​​玩家获胜,而是 AI 获胜!让我们返回1

const 结果 = PL===AI ?2 : (AI+1)%3 === PL?0 : 1;//可能的结果:0, 1, 2

基于游戏结果索引的一个很酷的事情是,现在您还可以使用一系列消息,例如 messages = ["You won!", "AI won", "it's a draw!",]通过结果索引得到想要的消息!.还有奖金!您还可以增加 score 数组值,0 是玩家的索引,1 是 AI!<​​/p>

const move = ["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");功能游戏(){const PL = +this.dataset.playermove;//以整数形式获取数据集值const AI = ~~(Math.random() * 3);//所有你需要的:0, 1, 2const 结果 = PL === AI ?2 : (AI + 1) % 3 === PL ?0 : 1;//0=PLwins 1=AIwins 2=平局得分[结果]++;//增加 PL 或 AI 的分数(也增加抽奖次数;))EL_result.innerHTML = `你:${moves[PL]}<br>AI:${moves[AI]}<br>${messages[result]}`;EL_PLScore.textContent = score[0];EL_AIScore.textContent = score[1];}//事件:document.querySelectorAll("[data-playermove]").forEach(el => el.addEventListener("click", game));

I'm writing a program to play rock, paper, scissors. As I was coding, everything was going fine until I added the:

userScore_span.InnerHTML = userScore;

line. When testing out the win function, I added a console.log('you win'); and it worked fine, but as soon as I added the line from above I got an error when I pressed any one of the three buttons.

I'm trying to relay the result from userScore to userScore_span given that userScore increases after a game is won

userScore++;
userScore_span.innerHTML = userScore;

However, when I press any of the buttons I get an error of:

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

I am not sure what the chrome Dev tools means by this. How can this be fixed?

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>

解决方案

Beside your typo idea= / id= ...
you could drastically minify your game logic and code by using indexes integers.

Game of integers

Now that you know AI and Player both use integers (instead of strange letters combinations), you can store the Move names into an array const moves = ["Rock", "Paper", "Scissors"]; (where 0 is Rock... etc)

Rock Paper Scissors Logic

The game has three possible round resolutions, PL wins, AI wins, Draw. Let's convert those "human" values to integers, in the same order:

Here's how to calculate those:

Draw

To calculate a Draw is the simplest. It's when both AI and PL integers are equal. Let's return 2

result = PL === AI ? 2

Player wins

To calculate Player win, simply increment AI choice by 1 and do a modulo 3. If the result of this operation is equal to player's choice, than Player must have won! Let's return 0

AI wins

Else, since our game has only 3 possible states, it's not a draw, and it's not a player win, than must be AI win! And let's return 1

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

The cool thing in having a game result index based too is that now you can use also an array of messages like messages = ["You won!", "AI won", "it's a draw!", ] and get the desired message by the result index!. And bonus! You can also increment the score array values, 0 being the player's index and 1 being AIs!

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));

<button data-playermove="0">ROCK</button>
<button data-playermove="1">PAPER</button>
<button data-playermove="2">SCISSORS</button>

<br>

YOU | <span id="PLScore">0</span>:<span id="AIScore">0</span> | AI

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

这篇关于尝试在 JS Rock、Paper、Scissors 游戏中设置一个 span 元素等于一个变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
前端开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆