Rock, Paper, Scissors 使用 onclick 函数来填充玩家结果

Rock, Paper, Scissors using onclick function to populate player results

我目前正在完成训练营的准备课程,最后一项任务是将一些基本的 JavaScript 函数放入剪刀石头布游戏中。我无法完成此 onclick 函数。

当用户单击按钮时填充用户选择的最佳方式是什么?

我目前已经在数组中定义和设置了我的选择。所以,我想我正在尝试让定义的选择等于按下的按钮。如果我的想法是正确的,我希望 ex: choices[1] 也成为我的“Papyrus”按钮。我已经尝试使用 const () =,但我没有收到“初始化程序”警告。

更新了点击功能。在我的所有地方和我的课程中,它都具有 e.target.id 的功能(e),我将 querySelector 更改为 querySelectorAll 以获取所有按钮。但仍然没有看到 console.log 输出,也没有看到屏幕上的 compareChoice 结果。

const firstChoice = "Lapis";
const secondChoice = "Papyrus";
const thirdChoice = "Scalpellus";
const choices = ['Lapis', 'Payrus', 'Scalpellus'];

player.currentChoice = document.querySelectorAll('button').onclick = function(e) {
    console.log(e.target.id); 
}
 //Example of on of the choice outcomes
else if(computer.currentChoice === choices[0]){
    if(player.currentChoice === choices[1]){
      displayResults("The player wins! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);
    }else{
      displayResults("The computer loses! The computer chose " + computer.currentChoice + " and the player chose " + player.currentChoice);

我从您的代码中看到的第一件事是您没有正确定义 onclick 回调。

您应该改用 addEventListener 函数,第一个参数是您要收听的事件(在您的例子中是 "click" ),第二个参数是您的回调。

注意回调可以带一个参数,也就是事件。

document.querySelectorAll('button').addEventListener("click", function(event) {
    // do something once the button is clicked. 
});

回调只是一个将在某个时刻执行的函数。并且由于您在其余代码中接缝使用回调的“Return 值”,因此它不会被正确执行。举个例子。

const myButton = document.querySelector('#button');

let myVariable;
// proper way to define an event listener.
myButton.addEventListener('click', function(event) {
    myVariable = "Some string";
});

console.log(myVariable); // will always be undefined.
<button id="button">Click me !</button>

请注意当您 运行 代码时控制台总是输出 undefined ?

这是因为,回调和其余代码没有同时执行。尽管 console.log 部分出现在回调之后,但它是 运行 与其余代码一起出现的,而不是在触发回调时。只有回调中的代码才会在我们监听的事件触发时运行

也就是说,您可以在回调外部定义变量并在内部使用它。这可能有助于跟踪每个玩家的选择。

考虑到这一点,您需要在回调中移动检查玩家是否获胜的逻辑。

document.querySelectorAll('button').addEventListener("click", function(event) {
    if(player.currentChoice === choices[1]){
    // player wins
    } else {
     // computer wins.
    }
});

至于填充用户选择部分,您实际上并不需要外部变量。您可以像以前一样简单地听点击并使用 event.target.id 获得玩家的选择。然后将其与预定义的 computer move.

进行比较

这是一个有点工作的例子。

const choices = ['Lapis', 'Payrus', 'Scalpellus'];

const allButtons = document.querySelectorAll('button');

// we register the listener on the `click` event, for each buttons.
for(let i = 0; i < allButtons.length; i ++) {

  allButtons[i].addEventListener('click', function(event){
    // we retrieve the player's choice from the id of the clicked button.
    const playerChoice = event.target.id;

    // we get a random id for the computer's move.
    const randomChoiceId = Math.floor(Math.random() * choices.length);

    const computerChoice = choices[randomChoiceId];
    
    // we check if the player wins. 
    // I don't know the logic and comparing each element might
    // not be the more efficient way to acheive this. But it works for now.
    if(playerChoice === "Lapis" && computerChoice === "Payrus") {
      console.log('Player Wins ! ');
    } else {
      console.log('Computer wins... ');
    }
  });
}
<button id="Lapis">Lapis</button>
<button id="Payrus">Payrus</button>
<button id="Scalpellus">Scalpellus</button>

希望这个回调的简要概述足够清楚,可以帮助您继续进行您的项目。祝你好运!

我假设您有 player 个 Obj 和多个用户可以从中选择的按钮

let player = {
        currentChoice: ''
    },
    computer = {
        computerSelection: ['Lapis', 'Payrus', 'Scalpellus'],
        currentChoice: ''
    };

const allButtons = document.querySelectorAll('button')

for (var i = 0; i < allButtons.length; i++) {
    allButtons[i].addEventListener('click', getUserSelection);
}


function compare() {
    let playerChoice = player.currentChoice,
        computerChoice = computer.currentChoice,
        outcome = '';

    if (playerChoice === computerChoice) {
        outcome = 'draw';
    } else if (playerChoice === 'Lapis' && computerChoice === 'Scalpellus' || (playerChoice === 'Papyrus' && computerChoice === 'Lapis') || (playerChoice === 'Scalpellus' && computerChoice === 'Papyrus')) {
        outcome = 'You win';
    } else {
        outcome = 'You lose'
    }
    displayResults(outcome)
    displayResults(`You picked ${playerChoice}`)
    displayResults(`Computer picked ${computerChoice}`)
}

function getUserSelection(e) {
    player.currentChoice = this.id;
    // From here trigger a function that compares
    // User slection against computers random selection
    startTheFight();

}

function setComputerChoice() {
    let random = Math.floor(Math.random() * (computer.computerSelection.length - 1)) + 1;
    computer.currentChoice = computer.computerSelection[random];
}

function startTheFight() {
    // Get a random selection
    setComputerChoice();
    compare();


}

function displayResults(result) {
    const resultText = document.createElement('p');
    resultText.innerText = result;
    document.body.appendChild(resultText);
}
<button id="Lapis">
    Lapis
</button>
<button id="Papyrus">
    Papyrus
</button>
<button id="Scalpellus">
    Scalpellus
</button>

编辑:在您的情况下,可以像示例中那样显示最后通牒的结果