我如何使我的分数在剪刀,纸石游戏中起作用?

发布于 2025-01-22 10:56:36 字数 2906 浏览 0 评论 0原文

我是JavaScript和HTML的新手。我正在尝试制作玩家对付电脑的剪刀,纸石游戏。但是,我无法使得分数播放或在HTML中显示得分。我也尝试添加渲染功能,但行不通。我的ScoreWindow代码有什么问题?为什么显示为错误和空? 请帮忙。

let choises = ['rock', 'paper', 'scissors'];

choises.rock = document.querySelector('.rock');
choises.paper = document.querySelector('.paper');
choises.scissors = document.querySelector('.scissors');

/*let userScore = document.querySelector('.scores .scorePlayer');
let computerScore = document.querySelector('.scores .scoreComp');*/
let scoreWindow = document.querySelector('.scores');
let playerSelection;
let computerSelection;

let computerScore = 0;
let userScore = 0;

scoreWindow.innerHTML = userScore + ' : ' + computerScore;

function computerPlay() {
  let computerAction = Math.floor(Math.random() * choises.length);
  computerSelection = choises[computerAction];
  return computerSelection;
}


function playRound(playerSelection, computerSelection) {
  if (playerSelection === computerSelection) {
    userScore = userScore + 1;
    computerScore = computerScore + 1;
  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
    (playerSelection === choises.rock && computerSelection === choises.rock) ||
    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
    userScore = userScore++;
  } else {
    computerScore = computerScore++;
  }

  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
  return (computerScore, userScore);
}

function doChoises() {
  choises.rock.addEventListener('click', () => {
    playerSelection = choises[0];
    console.log(computerPlay());
    console.log(playerSelection);
    console.log(playRound(playerSelection, computerSelection));
  });
  choises.paper.addEventListener('click', () => {
    playerSelection = choises[1];
    console.log(computerPlay());
    playRound();
  });
  choises.scissors.addEventListener('click', () => {
    playerSelection = choises[2];
    console.log(computerPlay());
    playRound();
  });
}

function renderScore(computerScore, userScore) {
  scoreWindow.innerText = `${computerScore} : ${userScore}`;
}
renderScore();
doChoises();
<div class="battlefield">
  <div class="battlefield__back">
    <div class="scores">
      <span>:</span>
    </div>

    <div class="battlefield__weapon">
      <button class="rock">
                <img src="./rock.png"/>
            </button>
      <button class="paper">
                <img src="./paper.png"/>
            </button>
      <button class="scissors">
                <img src="./scissors.png"/>
            </button>
    </div>
  </div>
</div>

I am new to javascript and html. I am trying to make a scissors, paper stone game that the player plays against the computer. However I am not able to get the score to play or get the score to display in html. I have tried adding a rendering function too but doesn't work. What is wrong with my scoreWindow code? Why does it show as error and null?
Please help.

let choises = ['rock', 'paper', 'scissors'];

choises.rock = document.querySelector('.rock');
choises.paper = document.querySelector('.paper');
choises.scissors = document.querySelector('.scissors');

/*let userScore = document.querySelector('.scores .scorePlayer');
let computerScore = document.querySelector('.scores .scoreComp');*/
let scoreWindow = document.querySelector('.scores');
let playerSelection;
let computerSelection;

let computerScore = 0;
let userScore = 0;

scoreWindow.innerHTML = userScore + ' : ' + computerScore;

function computerPlay() {
  let computerAction = Math.floor(Math.random() * choises.length);
  computerSelection = choises[computerAction];
  return computerSelection;
}


function playRound(playerSelection, computerSelection) {
  if (playerSelection === computerSelection) {
    userScore = userScore + 1;
    computerScore = computerScore + 1;
  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
    (playerSelection === choises.rock && computerSelection === choises.rock) ||
    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
    userScore = userScore++;
  } else {
    computerScore = computerScore++;
  }

  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
  return (computerScore, userScore);
}

function doChoises() {
  choises.rock.addEventListener('click', () => {
    playerSelection = choises[0];
    console.log(computerPlay());
    console.log(playerSelection);
    console.log(playRound(playerSelection, computerSelection));
  });
  choises.paper.addEventListener('click', () => {
    playerSelection = choises[1];
    console.log(computerPlay());
    playRound();
  });
  choises.scissors.addEventListener('click', () => {
    playerSelection = choises[2];
    console.log(computerPlay());
    playRound();
  });
}

function renderScore(computerScore, userScore) {
  scoreWindow.innerText = `${computerScore} : ${userScore}`;
}
renderScore();
doChoises();
<div class="battlefield">
  <div class="battlefield__back">
    <div class="scores">
      <span>:</span>
    </div>

    <div class="battlefield__weapon">
      <button class="rock">
                <img src="./rock.png"/>
            </button>
      <button class="paper">
                <img src="./paper.png"/>
            </button>
      <button class="scissors">
                <img src="./scissors.png"/>
            </button>
    </div>
  </div>
</div>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

成熟的代价 2025-01-29 10:56:36

您需要进行以下3个更改,以使得分数正常工作。我只是尝试了一下,一旦您进行了更改,您的其余游戏代码都可以正常工作。正如一些答案所暗示的那样,这不是脚本加载问题。

(1)从功能游戏中删除参数,因为您希望该函数使用全局变量。这可能并不明显。但是,这些参数以相同名称覆盖全局值。而且它们始终既无效,因此确定分数的逻辑无法正常工作。

    // function playRound(playerSelection, computerSelection) {
    function playRound() {

(2&amp; 3)正确递增用户和计算机分数。

    //userScore = userScore++;
    userScore++;


    //computerScore = computerScore++;
    computerScore++;

let choises = ['rock', 'paper', 'scissors'];

choises.rock = document.querySelector('.rock');
choises.paper = document.querySelector('.paper');
choises.scissors = document.querySelector('.scissors');

/*let userScore = document.querySelector('.scores .scorePlayer');
let computerScore = document.querySelector('.scores .scoreComp');*/
let scoreWindow = document.querySelector('.scores');
let playerSelection;
let computerSelection;

let computerScore = 0;
let userScore = 0;

scoreWindow.innerHTML = userScore + ' : ' + computerScore;

function computerPlay() {
  let computerAction = Math.floor(Math.random() * choises.length);
  computerSelection = choises[computerAction];
  return computerSelection;
}


function playRound() {
  if (playerSelection === computerSelection) {
    userScore++;
    computerScore++;
  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
    (playerSelection === choises.rock && computerSelection === choises.rock) ||
    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
    userScore++;
  } else {
    computerScore++;
  }

  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
  return (computerScore, userScore);
}

function doChoises() {
  choises.rock.addEventListener('click', () => {
    playerSelection = choises[0];
    console.log(computerPlay());
    console.log(playerSelection);
    console.log(playRound(playerSelection, computerSelection));
  });
  choises.paper.addEventListener('click', () => {
    playerSelection = choises[1];
    console.log(computerPlay());
    playRound();
  });
  choises.scissors.addEventListener('click', () => {
    playerSelection = choises[2];
    console.log(computerPlay());
    playRound();
  });
}

function renderScore(computerScore, userScore) {
  scoreWindow.innerText = `${computerScore} : ${userScore}`;
}
renderScore();
doChoises();
<div class="battlefield">
  <div class="battlefield__back">
    <div class="scores">
      <span>:</span>
    </div>

    <div class="battlefield__weapon">
      <button class="rock">
                <img alt="rock" src="./rock.png"/>
            </button>
      <button class="paper">
                <img alt="paper" src="./paper.png"/>
            </button>
      <button class="scissors">
                <img alt="scissors" src="./scissors.png"/>
            </button>
    </div>
  </div>
</div>

You need to make the following 3 changes to make the score work correctly. I just tried it and the rest of your game code works fine once you make the changes. It is not a script loading problem as some answers suggest.

(1) Remove the parameters from function playRound because you want the function to use the global variables. The problem with this might not be obvious. Yet, these parameters are overriding the global values with the same name. And they are always both null and so the logic for determining the score doesn't work correctly.

    // function playRound(playerSelection, computerSelection) {
    function playRound() {

(2 & 3) Increment the user and computer scores correctly.

    //userScore = userScore++;
    userScore++;


    //computerScore = computerScore++;
    computerScore++;

let choises = ['rock', 'paper', 'scissors'];

choises.rock = document.querySelector('.rock');
choises.paper = document.querySelector('.paper');
choises.scissors = document.querySelector('.scissors');

/*let userScore = document.querySelector('.scores .scorePlayer');
let computerScore = document.querySelector('.scores .scoreComp');*/
let scoreWindow = document.querySelector('.scores');
let playerSelection;
let computerSelection;

let computerScore = 0;
let userScore = 0;

scoreWindow.innerHTML = userScore + ' : ' + computerScore;

function computerPlay() {
  let computerAction = Math.floor(Math.random() * choises.length);
  computerSelection = choises[computerAction];
  return computerSelection;
}


function playRound() {
  if (playerSelection === computerSelection) {
    userScore++;
    computerScore++;
  } else if ((playerSelection === choises.rock && computerSelection === choises.scissors) ||
    (playerSelection === choises.rock && computerSelection === choises.rock) ||
    (playerSelection === choises.scissors && computerSelection === choises.paper)) {
    userScore++;
  } else {
    computerScore++;
  }

  scoreWindow.innerHTML = userScore + ' : ' + computerScore;
  return (computerScore, userScore);
}

function doChoises() {
  choises.rock.addEventListener('click', () => {
    playerSelection = choises[0];
    console.log(computerPlay());
    console.log(playerSelection);
    console.log(playRound(playerSelection, computerSelection));
  });
  choises.paper.addEventListener('click', () => {
    playerSelection = choises[1];
    console.log(computerPlay());
    playRound();
  });
  choises.scissors.addEventListener('click', () => {
    playerSelection = choises[2];
    console.log(computerPlay());
    playRound();
  });
}

function renderScore(computerScore, userScore) {
  scoreWindow.innerText = `${computerScore} : ${userScore}`;
}
renderScore();
doChoises();
<div class="battlefield">
  <div class="battlefield__back">
    <div class="scores">
      <span>:</span>
    </div>

    <div class="battlefield__weapon">
      <button class="rock">
                <img alt="rock" src="./rock.png"/>
            </button>
      <button class="paper">
                <img alt="paper" src="./paper.png"/>
            </button>
      <button class="scissors">
                <img alt="scissors" src="./scissors.png"/>
            </button>
    </div>
  </div>
</div>

爱的那么颓废 2025-01-29 10:56:36

在对DOM进行任何操作之前,您必须等待它渲染。使用当前代码,您正在尝试在潜在的空页面中查找元素。

使用docund.onload带有包装所有代码的功能。

function main() {
  /* the eternity of the code */
}
document.onload = main;

Before doing any operations on the DOM, you must wait for it to render. With the current code, you are trying to look for elements in a potentially empty page.

Use document.onload with a function wrapping all of your code.

function main() {
  /* the eternity of the code */
}
document.onload = main;
心的憧憬 2025-01-29 10:56:36

如果QuerySelector正常工作,请在脚本标签中添加defer属性,

例如,

<script src='script.js' defer ></script>

这应该解决您的问题

For queryselectors to work properly add a defer attribute to your script tag

For example

<script src='script.js' defer ></script>

This should fix your problem

岁月静好 2025-01-29 10:56:36

这是处理游戏的一种凝结方式:

const choices="rock,paper,scissors".split(","),
 btns=document.querySelectorAll("#user button");
var cmp,usr;

btns.forEach(b=>b.onclick=()=>{
 usr=choices.findIndex(c=>b.classList.contains(c));
 btns.forEach(c=>c.classList.toggle("active",b==c));
 computer.className=choices[cmp=Math.floor(Math.random()*3)];
 switch((3+cmp-usr)%3){ // possible results: 0,1,2
  case 1: cs.textContent++; break;
  case 2: us.textContent++;
 }
})
button {background:url(https://previews.123rf.com/images/sudowoodo/sudowoodo1710/sudowoodo171000028/88077066-hand-gestures-for-rock-paper-scissors-game-simple-hand-icons-.jpg); width:32px; height:36px; background-size:96px; display:inline-block}
.rock  {background-position:-4px -32px}
.paper {background-position:-34px -32px}
.scissors {background-position:-64px -32px}
.active {border-color:#f00;}
<div class="battlefield">
Computer: <span id="cs">0</span><br>
 <button id="computer"></button>
 <div id="user">
 User: <span id="us">0</span><br>
   <button class="rock"></button>
   <button class="paper"></button>
   <button class="scissors"></button>
 </div>
</div>

由于简短和避免冗余是我的主要重点,因此,我使用了直接解决DOM元素作为全局范围中的变量的形式(Computercsus )。更传统的方法是通过以下内容:const Computs = document.getElementById(“ Computer”)

Here is a condensed way of handling the game:

const choices="rock,paper,scissors".split(","),
 btns=document.querySelectorAll("#user button");
var cmp,usr;

btns.forEach(b=>b.onclick=()=>{
 usr=choices.findIndex(c=>b.classList.contains(c));
 btns.forEach(c=>c.classList.toggle("active",b==c));
 computer.className=choices[cmp=Math.floor(Math.random()*3)];
 switch((3+cmp-usr)%3){ // possible results: 0,1,2
  case 1: cs.textContent++; break;
  case 2: us.textContent++;
 }
})
button {background:url(https://previews.123rf.com/images/sudowoodo/sudowoodo1710/sudowoodo171000028/88077066-hand-gestures-for-rock-paper-scissors-game-simple-hand-icons-.jpg); width:32px; height:36px; background-size:96px; display:inline-block}
.rock  {background-position:-4px -32px}
.paper {background-position:-34px -32px}
.scissors {background-position:-64px -32px}
.active {border-color:#f00;}
<div class="battlefield">
Computer: <span id="cs">0</span><br>
 <button id="computer"></button>
 <div id="user">
 User: <span id="us">0</span><br>
   <button class="rock"></button>
   <button class="paper"></button>
   <button class="scissors"></button>
 </div>
</div>

As brevity and avoiding redundancies was my main focus here I used the form of addressing DOM elements directly as variables in the global scope (computer, cs and us). The more conventional way would have been to "get" them through something like: const computer=document.getElementById("computer").

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文