javascript - 如何在控制台中显示 ROCK、PAPER、SCISSOR GAME Javascript 的结果
问题描述
我目前被javascript中的石头、纸、剪刀游戏困住了。我需要在控制台中显示如下内容: 计算机选择:“Rock” 用户选择:“Paper” 用户获胜!
如何在下面的代码中实现这一点。
let userSelection = userPlay();
function userPlay() {
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
let computerSelection = computerPlay();
function computerPlay() { //computer generates a random answer.
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
function playRound(playerSelection, computerSelection) { //plays a round of the game.
if (playerSelection === "rock") {
if (computerSelection === "rock") {
return "Draw!";
} else if (computerSelection === "paper") {
return "Computer wins!";
} else {
return "User wins!";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "User wins!";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "Computer wins!";
}
} else {
if (computerSelection === "rock") {
return "Computer wins!";
} else if (computerSelection === "paper") {
return "User wins!";
} else {
return "Draw!";
}
}
}
console.log(playRound(userPlay, computerSelection));
解决方案
我已经交换了函数调用的位置以获得更好的可读性。想法是将每个函数调用的结果存储到一个变量中并打印出来。
function userPlay() {
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
function computerPlay() { //computer generates a random answer.
let random = ["rock", "paper", "scissors"];
return random[Math.floor(Math.random() * 3)];
}
function playRound(playerSelection, computerSelection) { //plays a round of the game.
if (playerSelection === "rock") {
if (computerSelection === "rock") {
return "Draw!";
} else if (computerSelection === "paper") {
return "Computer wins!";
} else {
return "User wins!";
}
} else if (playerSelection === "paper") {
if (computerSelection === "rock") {
return "User wins!";
} else if (computerSelection === "paper") {
return "Draw!";
} else {
return "Computer wins!";
}
} else {
if (computerSelection === "rock") {
return "Computer wins!";
} else if (computerSelection === "paper") {
return "User wins!";
} else {
return "Draw!";
}
}
}
var userChoice = userPlay();
var computerSelection = computerPlay();
var result = playRound(userChoice, computerSelection)
console.log("user's choice", userChoice);
console.log("computer's choice", computerSelection);
console.log("Result is", result);
推荐阅读
- java - Java:静态变量声明最佳实践
- git - git init --separate-git-dir 覆盖现有的 .git 文件夹
- css - 通过 .css 文件更改 JavaFX 中的字体颜色
- arrays - SAPUI5 XML 视图中嵌套 JSON 数组的聚合绑定
- javascript - 如何在 react-native-maps 中取消以前的 onRegionChangeComplete 处理程序?
- r - 使用 gsub 删除 R 中的子字符串
- css - 在同一级别元素之后选择 div
- javascript - 使用 pdfkit 创建 .pdf 没有保存选项
- javascript - btn-danger 效果不适用于 jQuery
- reporting-services - 如何与不同域中的服务器建立 Power bi 实时连接?