如何在一个函数中嵌套其他函数以跟踪游戏的分数?

huangapple go评论104阅读模式
英文:

How to insert some functions inside other function to track score for a game?

问题

我是新手学习JavaScript,正在尝试实现"石头,剪刀,布"游戏,参考了The Odin Project的教程链接:https://www.theodinproject.com/lessons/foundations-rock-paper-scissors。从用户获取输入和从计算机获取随机选择的函数都可以正常工作,以及我可以玩5轮游戏,但没有记分。当我想为每个玩家添加记分时,我只能收到来自playRound()函数的最后一个答案,甚至游戏结束也没有显示。我认为问题可能出在如何以及何处声明具有函数值的变量(playerSelection = getPlayerChoice(); computerSelection = getComputerChoice())。以下是我的代码:

// 从玩家获取输入
function getPlayerChoice() {
   let playerInput = prompt("选择石头、剪刀或布。");
   let playerChoice = playerInput.toLowerCase();
   if (playerChoice === "rock") {
       playerChoice = "Rock";
   } else if (playerChoice === "paper") {
       playerChoice = "Paper";
   } else if (playerChoice === "scissors") {
       playerChoice = "Scissors";
   } else {
     alert("请选择这些选项之一");
     getPlayerChoice();
  }
   return playerChoice;
}

// 从计算机获取随机输入
function getComputerChoice() {
  const comChoice = ["Rock", "Paper", "Scissors"];
  const comResult = Math.floor(Math.random() * comChoice.length);
    return comChoice[comResult];
}

// 进行一轮游戏并将它们分配给两个变量,并检查赢家
function playRound() {
  const playerSelection = getPlayerChoice();
  const computerSelection = getComputerChoice();
  let response = "";
    if (playerSelection === computerSelection) {
        response += "平局";
  } else if ((playerSelection === "Rock" && computerSelection === "Scissors") ||
             (playerSelection === "Paper" && computerSelection === "Rock") ||
             (playerSelection === "Scissors" && computerSelection === "Paper")) {
        response += `你赢了。${playerSelection}${computerSelection}`;
  } else if ((playerSelection === "Rock" && computerSelection === "Paper") ||
             (playerSelection === "Paper" && computerSelection === "Scissors") ||
             (playerSelection === "Scissors" && computerSelection === "Rock")) {
        response += `你输了。${playerSelection}${computerSelection}`;
      }
      return response;
}

// 进行5轮游戏并获取分数
function game() {
  let playerScore = 0;
  let computerScore = 0;
  for (let i = 0; i < 5; i++) {
    let playerSelection = getPlayerChoice();
    let computerSelection = getComputerChoice();
    let roundResult = playRound(); // 存储 playRound() 的结果
    console.log(roundResult);
    if (roundResult.includes("你赢了")) { // 使用 includes() 检查结果
        playerScore++;
        console.log(`玩家分数: ${playerScore}`)
      } else if (roundResult.includes("你输了")) {
        computerScore++;
        console.log(`计算机分数: ${computerScore}`)
    }
      console.log("---------");
   }

    if (playerScore > computerScore) {
       console.log("你赢了。")
    } else if (playerScore < computerScore) {
       console.log("你输了。")
    } else if (playerScore === computerScore) {
       console.log("平局")
    }
     console.log("游戏结束")
   }

    game();

对于你的问题,我对代码进行了一些修改,主要是将playRound()的结果存储在一个变量中,然后使用includes()方法来检查结果以确定分数。这样,你应该能够正确地跟踪分数并在游戏结束时显示结果。

至于getPlayerChoice()在按取消时可能导致"无法读取 null 的属性 toLowerCase()"的错误,你可以在函数内部添加一个条件来检查用户是否点击了取消,如果是,可以选择不再递归调用函数,而是返回一个默认值,例如"Cancelled"。这样,你就可以在后续代码中检查这个值并采取相应的措施。

希望这些修改有助于你解决问题并改进你的游戏!

英文:

I am new to javascript and I'm trying to do the rock-paper-scrissors game from the odin project: https://www.theodinproject.com/lessons/foundations-rock-paper-scissors. The functions that get an input from user and a random answear from the computer work and also the game when I want to play 5 rounds, but without score. When I want to add score for each player, I only receive the last answear from function playround(), not even game over in the end. I think it is about how and where to declare variables that have functions values (playerSelection = getPlayerChoice(); computerSelection = getComputerChoice()). Here is my code:

//get input from the player
function getPlayerChoice() {
let playerInput = prompt(&quot;Choose rock, paper or scrissors.&quot;);
let playerChoice = playerInput.toLowerCase();
if (playerChoice === &quot;rock&quot;) {
playerChoice = &quot;Rock&quot;;
} else if (playerChoice === &quot;paper&quot;) {
playerChoice = &quot;Paper&quot;;
} else if (playerChoice === &quot;scrissors&quot;) {
playerChoice = &quot;Scrissors&quot;;
} else {
alert(&quot;Choose one of these objects&quot;);
getPlayerChoice();
}
return playerChoice;
}
//get random input from the computer
function getComputerChoice() {
const comChoice = [&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scrissors&quot;];
const comResult = Math.floor(Math.random() * comChoice.length);
return comChoice[comResult];
}
//play one round using the functions and assign them to two variables 
and checks the winner
function playRound() {
const playerSelection = getPlayerChoice();
const computerSelection = getComputerChoice();
let response = &quot;&quot;;
if (playerSelection === computerSelection) {
response += &quot;It&#39;s a tie&quot;;
} else if ((playerSelection === &quot;Rock&quot; &amp;&amp; computerSelection === &quot;Scrissors&quot;) ||
(playerSelection === &quot;Paper&quot; &amp;&amp; computerSelection === &quot;Rock&quot;) ||
(playerSelection === &quot;Scrissors&quot; &amp;&amp; computerSelection === &quot;Paper&quot;)) {
response += `You win. ${playerSelection} beats ${computerSelection}`;
} else if ((playerSelection === &quot;Rock&quot; &amp;&amp; computerSelection === &quot;Paper&quot;) ||
(playerSelection === &quot;Paper&quot; &amp;&amp; computerSelection === &quot;Scrissors&quot;) ||
(playerSelection === &quot;Scrissors&quot; &amp;&amp; computerSelection === &quot;Rock&quot;)) {
response += `You lose. ${playerSelection} beats ${computerSelection}`;
}
return response;
}
//playing a game of 5 rounds and get score
function game() {
let playerScore = 0;
let computerScore = 0;
for (let i = 0; i &lt; 5; i++) {
let playerSelection = getPlayerChoice();
let computerSelection = getComputerChoice();
console.log(playRound());
if (playRound() === `You win. ${playerSelection} beats ${computerSelection}`) {
playerScore++;
console.log(`Player score: ${playerScore}`)
} else if (playRound() === `You lose. ${playerSelection} beats ${computerSelection}`) {
computerScore++;
console.log(`Computer score: ${computerScore}`)
}
console.log(&quot;---------&quot;);
}
if (playerScore &gt; computerScore) {
console.log(&quot;You win.&quot;)
} else if (playerScore &lt; computerScore) {
console.log(&quot;You lose.&quot;)
} else if (playerScore === computerScore) {
console.log(&quot;Drawn&quot;)
}
console.log(&quot;Game Over&quot;)
}
game();

I saw some solutions on youtube, but they use more functions and I want to keep mine and to understand the concepts from JS. I think the problem is playRound() where I already use two functions as variables and the return response involves the values of the parameters. I try to use playRound() inside game() and I don't know how to use that response from my playRound() to add a score: if the user win, he gets 1 point, if the computer wins, it gets 1 point at each round and then add a message score that says who is the winner of the game in the end. Do you have any suggestions for my code? It works if I don't use score for the game, but I want to add this.
P.s. there is also an error about getPlayerChoice() where it can't read the properties of null reading toLowerCase(), but only if I press cancel on the prompt. I want to make the game also in html, so I find a little difficult the solution for this error, even if I found it, but I don't feel safe just to copy, maybe you have an easier solution or an explanation for the solution.

答案1

得分: 1

我建议你将playerscore和computer score以及player和computer selection作为一个全局数组(player and computer selection)在全局范围内定义,然后在playRound函数中进行得分计算。另外,不要多次调用playRound函数,因为这会严重影响性能。你的代码中另一个问题是在playRound和game函数中都获取了player和computer的选择。

修改后的代码如下:

var computerSelections = []; // 电脑选择的数组
var playerSelections = []; // 玩家选择的数组
var playerScore = 0; // 玩家和电脑的分数应该在全局范围内定义
var computerScore = 0;

// 从玩家获取输入
function getPlayerChoice() {
    let playerInput = prompt("选择石头、剪刀或布。");
    let playerChoice = playerInput.toLowerCase();
    if (playerChoice === "rock") {
        playerChoice = "Rock";
    } else if (playerChoice === "paper") {
        playerChoice = "Paper";
    } else if (playerChoice === "scissors") {
        playerChoice = "Scissors";
    } else {
        alert("请选择其中一个选项");
        getPlayerChoice();
    }
    return playerChoice;
}

// 从电脑随机获取输入
function getComputerChoice() {
    const comChoice = ["Rock", "Paper", "Scissors"];
    const comResult = Math.floor(Math.random() * comChoice.length);
    return comChoice[comResult];
}

function playRound(playerSelection, computerSelection) {
    let response = "";
    if (playerSelection === computerSelection) {
        response += "平局";
    } else if (
        (playerSelection === "Rock" && computerSelection === "Scissors") ||
        (playerSelection === "Paper" && computerSelection === "Rock") ||
        (playerSelection === "Scissors" && computerSelection === "Paper")
    ) {
        response += `你赢了。${playerSelection} 战胜了 ${computerSelection}`;
    } else {
        response += `你输了。${playerSelection}${computerSelection} 战胜了`;
    }
    return response;
}

// 进行5轮游戏并计分
function game() {
    for (let i = 0; i < 5; i++) {
        let thisplayerSelection = getPlayerChoice();
        let thiscomputerSelection = getComputerChoice();
        var response = playRound(thisplayerSelection, thiscomputerSelection);
        if (response.includes("赢了")) {
            playerScore++;
            console.log(`玩家得分: ${playerScore}`);
        } else if (response.includes("输了")) {
            computerScore++;
            console.log(`电脑得分: ${computerScore}`);
        }
        console.log("---------");
        playerSelections.push(thisplayerSelection);
        computerSelections.push(thiscomputerSelection);
    }

    if (playerScore > computerScore) {
        console.log("你赢了。");
    } else if (playerScore < computerScore) {
        console.log("你输了。");
    } else {
        console.log("平局。");
    }
    console.log("游戏结束");
}

game();

我还进行了其他一些修改,请查看注释。如果这个答案对你有帮助,请接受并点赞。这对我很有帮助。希望对你有所帮助。

英文:

I suggest you that use playerscore and computer score and player and computer selection as an array(player and computer selection) in global scope and then do the score counting in playRound function and second is that dont call playRound multiple times cause it decreases the performance very much. And another in your code is that you get the player and computer selection both in playRound and game functions.
So the code will be like this :

var computerSelections = []; // an array of computer selections
var playerSelections = []; // **   **    ** player    **
var playerScore = 0; // player and computer score should be in global scope
var computerScore = 0;
//get input from the player
function getPlayerChoice() {
let playerInput = prompt(&quot;Choose rock, paper or scrissors.&quot;);
let playerChoice = playerInput.toLowerCase();
if (playerChoice === &quot;rock&quot;) {
playerChoice = &quot;Rock&quot;;
} else if (playerChoice === &quot;paper&quot;) {
playerChoice = &quot;Paper&quot;;
} else if (playerChoice === &quot;scrissors&quot;) {
playerChoice = &quot;Scrissors&quot;;
} else {
alert(&quot;Choose one of these objects&quot;);
getPlayerChoice();
}
return playerChoice;
}
//get random input from the computer
function getComputerChoice() {
const comChoice = [&quot;Rock&quot;, &quot;Paper&quot;, &quot;Scrissors&quot;];
const comResult = Math.floor(Math.random() * comChoice.length);
return comChoice[comResult];
}
function playRound(playerSelection,computerSelection) {
let response = &quot;&quot;;
if (playerSelection === computerSelection) {
response += &quot;It&#39;s a tie&quot;;
} else if ((playerSelection === &quot;Rock&quot; &amp;&amp; computerSelection === &quot;Scrissors&quot;) ||
(playerSelection === &quot;Paper&quot; &amp;&amp; computerSelection === &quot;Rock&quot;) ||
(playerSelection === &quot;Scrissors&quot; &amp;&amp; computerSelection === &quot;Paper&quot;)) {
response += `You win. ${playerSelection} beats ${computerSelection}`;
} else if ((playerSelection === &quot;Rock&quot; &amp;&amp; computerSelection === &quot;Paper&quot;) ||
(playerSelection === &quot;Paper&quot; &amp;&amp; computerSelection === &quot;Scrissors&quot;) ||
(playerSelection === &quot;Scrissors&quot; &amp;&amp; computerSelection === &quot;Rock&quot;)) {
response += `You lose. ${playerSelection} beats ${computerSelection}`;
}
return response;
}
//playing a game of 5 rounds and get score
function game() {
for (let i = 0; i &lt; 5; i++) {
let thisplayerSelection = getPlayerChoice();
let thiscomputerSelection = getComputerChoice();
var response = playRound(thisplayerSelection,thiscomputerSelection); // added 2 parameters to defined playRound, playerSelection and computerSelection
// response variable is defined only in game function scope and is diffrent from playRound&#39;s response
if (response === `You win. ${thisplayerSelection} beats ${thiscomputerSelection}`) {
playerScore++;
console.log(`Player score: ${playerScore}`)
} else if (response === `You lose. ${thisplayerSelection} beats ${thiscomputerSelection}`) {
computerScore++;
console.log(`Computer score: ${computerScore}`)
}
console.log(&quot;---------&quot;);
playerSelections.push(thisplayerSelection);
computerSelections.push(thiscomputerSelection);
}
if (playerScore &gt; computerScore) {
console.log(&quot;You win.&quot;)
} else if (playerScore &lt; computerScore) {
console.log(&quot;You lose.&quot;)
} else if (playerScore === computerScore) {
console.log(&quot;Drawn&quot;)
}
console.log(&quot;Game Over&quot;)
}
game();

And i did some other changes please read the comments.
And if it worked please accept it and upvote it, It helps me a lot.
Hope it had been helpful for you.

huangapple
  • 本文由 发表于 2023年8月4日 02:35:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/76830800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定