massive noob here.
I'm making a rock paper scissor game in which one of the functions called 'game', counts the score between the player and the computer over 5 rounds.
The problem I am having is that no matter whether the player wins loses or draws, +1 is added to the score every time, instead of -1 for a loss and maintaining the score on a draw.
function game() {
var roundCount = 0;
var score = 0;
while (roundCount < 5) {
playRound(prompt("Rock, Paper or Scissors?"), computerPlay());
if (resultMessage == "You Win. Rock beats Scissors" || "You Win. Paper beats Rock" || "You Win. Scissor beats Paper") {
score++;
} else if (resultMessage == "Draw") {
score = score;
} else {
score--;
}
console.log(score)
roundCount = roundCount + 1;
}
return score;
}
console.log(game());
答案 0 :(得分:1)
This will always return true:
resultMessage == "You Win. Rock beats Scissors" || "You Win. Paper beats Rock" || "You Win. Scissor beats Paper"
Because the second and third dysjuncts are strings, which are always true.
答案 1 :(得分:1)
This does not work:
if(resultMessage == "You Win. Rock beats Scissors" || "You Win. Paper beats Rock" || "You Win. Scissor beats Paper") {
score++;
}
You have to compare each value:
if(resultMessage === "You Win. Rock beats Scissors" || resultMessage === "You Win. Paper beats Rock" || resultMessage === "You Win. Scissor beats Paper") {
score++;
}
答案 2 :(得分:0)
您可以通过返回值playRound()
(-1 =&gt; lost,0 =&gt; draw,1 =&gt; win)来实现-1,0,1
函数。然后,您可以直接将其添加到乐谱中,这将节省您比较字符串值。我已经包含了一个演示此代码的代码示例,但是您需要使用自己的逻辑替换playRound(choice)
函数来生成计算机选项,测试win / draw / lose,并返回正确的响应。古德勒克:)
function playRound(choice) {
//replace this random win/draw/lose function with play logic
let randomResult = Math.floor((Math.random() * 3) - 1);
return randomResult;
}
function game() {
//init round and score variables
let roundCount = 0;
let score = 0;
//play 5 rounds
while (roundCount < 5) {
//get users choice
let userChoice = prompt("Rock, Paper, or Scissors?");
//play round and get result (-1 => loss, 0 => draw, 1=> win)
score += playRound(userChoice);
//print current score and increment round count
console.log("Current Score: " + score);
roundCount++;
}
//print final result (no need to check for draw as we have an odd number of rounds)
console.log("Final Score: " + score);
if (score < 0) {
console.log("You lost the game :(");
} else {
console.log("You won the game :)");
}
}
//start game
game();