首页 > 解决方案 > 谁能告诉我为什么我的代码不能正常工作?游戏石头、纸、剪刀。Java 脚本

问题描述

谁能告诉我为什么我的代码不能正常工作?我正在尝试在纯 Java 脚本上制作游戏 ROCK、PAPER、SCISSORS。由于某种原因,它不像我预期的那样工作。

const computerAanswer = ["rock", "paper", "scissors"];

function computerPlay() {
    let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
    return answer;
}

console.log('computer choice is: ' + computerPlay().toUpperCase());



function playRound (playerSelection, computerSelection) {
    playerSelection  = playerSelection.toLowerCase()
    
    if (playerSelection == "rock" && computerSelection == "scissors") {
        return "Congrats,you are winner!";
    }   else if (playerSelection == "paper" && computerSelection == "rock") {
        return "Congrats,you are winner!";
    }   else if (playerSelection == "scissors" && computerSelection == "paper") {
        return "Congrats,you are winner!";
    }   else if (playerSelection == "rock" && computerSelection == "rock") {
        return "Draw!";
    }   else if (playerSelection == "paper" && computerSelection == "paper") {
        return "Draw!";
    }   else if (playerSelection == "scissors" && computerSelection == "scissors") {
        return "Draw!";
    }   else {
        return "You lose. Maybe next time...";
    }
}

let playerSelection = prompt("Make your choose: Rock, Paper or Scissors?");
let computerSelection = computerPlay();
console.log(playRound(playerSelection, computerSelection));

console.log('player choice is: ' + playerSelection.toUpperCase());

标签: javascript

解决方案


我想这只是你的第一个 console.log :

console.log('computer choice is: ' + computerPlay().toUpperCase());

它为计算机播放一轮,然后您与提示用户播放另一轮。

改为这样做:

function computerPlay() {
    let answer = computerAanswer[Math.floor(Math.random() * computerAanswer.length)];
    console.log('computer choice is: ' + answer.toUpperCase()); 
    return answer;
}

推荐阅读