Камень, ножницы, бумага в JavaScript
Я работаю над созданием своей первой игры (Rock Paper Sissors), и я столкнулся с проблемой, когда userChoice является ножницами и computerChoice является rock, программа не может вернуть победителя в качестве rock. Я могу заставить программу выдать мне победителя для любой другой комбинации.
У меня есть мой код здесь:
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
if (computerChoice < 0.34) {
computerChoice = "rock";
} else if(computerChoice <= 0.67) {
computerChoice = "paper";
} else {
computerChoice = "scissors";
}
var compare = function(choice1, choice2) {
if(choice1 === choice2) {
return "The result is a tie!";
}
if(choice1 === "rock") {
if(choice2 === "scissors") {
return "rock wins";
} else {
return "paper wins";
}
}
if(choice1 === "paper") {
if(choice2 === "rock") {
return "paper wins";
} else {
if(choice2 === "scissors") {
return "scissors wins";
}
}
if(choice1 === "scissors") {
if(choice2 === "rock") {
return "rock wins";
} else {
if(choice2 === "paper") {
return "scissors wins";
}
}
}
}
};
console.log("User Choice: " + userChoice);
console.log("Computer Choice: " + computerChoice);
compare(userChoice, computerChoice);
12 ответов:
Вы не смогли увидеть проблему, скорее всего, из-за плохого отступа вашего кода. Правильно выделенный вопрос ясен:
if (choice1 === "paper") { if (choice2 === "rock") { return "paper wins"; } else { if (choice2 === "scissors") { return "scissors wins"; } } if (choice1 === "scissors") { if (choice2 === "rock") { return "rock wins"; } else { if (choice2 === "paper") { return "scissors wins"; } } } }Ваш
if (choice1 === "scissors") {находится внутриif (choice1 === "paper") {. Код внутри никогда не будет достигнут.
Что-то для изучения:
var choices = ["rock", "paper", "scissors"]; var map = {}; choices.forEach(function(choice, i) { map[choice] = {}; map[choice][choice] = "Was a tie" map[choice][choices[(i+1)%3]] = choices[(i+1)%3] + " wins" map[choice][choices[(i+2)%3]] = choice + " wins" }) function compare(choice1, choice2) { return (map[choice1] || {})[choice2] || "Invalid choice"; }
Вот альтернативный вариант, который будет работать для расширенных наборов. Предположение состоит в том, что существует нечетное число возможностей, и из любой данной точки, из общего числа оппозиций, читая вперед от нашей данной точки (и оборачиваясь, когда мы достигнем конца) Первая половина выиграет над данной точкой, а вторая половина проиграет.
Или другим способом описать это было бы то, что половина оставшихся противников, которые предшествующая нам данная точка проиграет, а следующая половина выиграет.
Поэтому правильный порядок в массивеchoicesимеет решающее значение.var choices = ["rock", "spock", "paper", "lizard", "scissors"]; var map = {}; choices.forEach(function(choice, i) { map[choice] = {}; for (var j = 0, half = (choices.length-1)/2; j < choices.length; j++) { var opposition = (i+j)%choices.length if (!j) map[choice][choice] = "Was a tie" else if (j <= half) map[choice][choices[opposition]] = choices[opposition] + " wins" else map[choice][choices[opposition]] = choice + " wins" } }) function compare(choice1, choice2) { return (map[choice1] || {})[choice2] || "Invalid choice"; }
Так много утверждений if. Они сбивают с толку.
Кроме того, все эти утверждения if блокируют игру и затрудняют ее чтобы использовать логику для другой игры.
function referee(){ var training = {}; function learn(winner,loser){ if (!training[winner]) training[winner] = {}; training[winner][loser]=1; } function judge(play1,play2){ if (play1 === play2){ return 'tie'; } return ( (training[play1][play2] === 1)? play1: play2 )+' wins!'; } function validate(choice) { return choice in training; } function choices() { return Object.keys(training); } return { 'learn': learn, 'judge': judge, 'validAction': validate, 'getChoices': choices }; } var ref = referee(); ref.learn('rock','scissors'); ref.learn('paper','rock'); ref.learn('scissors','paper'); do { var userChoice = prompt("Do you choose rock, paper or scissors?"); } while(!ref.validAction(userChoice)) var choices = ref.getChoices(), computerChoice = choices[Math.floor(Math.random()*choices.length)]; console.log("User Choice: " + userChoice); console.log("Computer Choice: " + computerChoice); console.log(ref.judge(userChoice, computerChoice));
Я придумал альтернативу, которая должна быть легкой для понимания и избегать некоторых проблем в вашем коде, таких как чрезмерное повторение и фиксированный выбор. Таким образом, он гораздо более гибкий и простой в обслуживании.
function compare(choice1, choice2) { choice1 = choices.indexOf(choice1); choice2 = choices.indexOf(choice2); if (choice1 == choice2) { return "Tie"; } if (choice1 == choices.length - 1 && choice2 == 0) { return "Right wins"; } if (choice2 == choices.length - 1 && choice1 == 0) { return "Left wins"; } if (choice1 > choice2) { return "Left wins"; } else { return "Right wins"; } }Выбор есть
var choices = ["rock", "paper", "scissors"];. Вы можете ознакомиться с демонстрация.
Чтобы обобщить решение на большие списки, этот метод по модулю может быть полезен:
function mod(a, b) { c = a % b return (c < 0) ? c + b : c }Тогда гораздо проще написать код сравнения:
function compare(choice1, choice2) { x = choices.indexOf(choice1); y = choices.indexOf(choice2); if (x == y) { return "Tie"; } if (mod((x - y), choices.length) < choices.length / 2) { return choice1 + " wins"; } else { return choice2 + " wins"; } }
У вас есть несоответствующая скобка:
if(choice1 === "paper") { if(choice2 === "rock") { return "paper wins"; } else { if(choice2 === "scissors") { return "scissors wins"; } }Я бы на самом деле удалил последнюю
ifв этом блоке, вам это не нужно. Последний блок (choice1 === "scissors") верен, но опять же последний, если не требуется.Чтобы показать вам почему он не работает именно таким образом, я изменил отступ в соответствующей части вашего кода, чтобы проиллюстрировать, как он интерпретируется:
if(choice1 === "paper") { if(choice2 === "rock") { return "paper wins"; } else { if(choice2 === "scissors") { return "scissors wins"; } } if(choice1 === "scissors") { if(choice2 === "rock") { return "rock wins"; } else { if(choice2 === "paper") { return "scissors wins"; } } } }
Решение, к которому я пришел как товарищ-новичок, кажется относительно простым..
var userChoice = prompt ("Do you choose rock, paper or scissors?"); var computerChoice = Math.random(); console.log(computerChoice); if (computerChoice <=0.33) { "rock"; } else if (computerChoice <=0.66) { "paper"; } else { "scissors"; }
У меня получилось:
function playFunction() { var userChoice = prompt("Do you choose rock, paper or scissors?"); var computerChoice = Math.random(); if (computerChoice < 0.34) { computerChoice = "rock"; } else if(computerChoice <= 0.67) { computerChoice = "paper"; } else { computerChoice = "scissors"; } var compare = function(choice1, choice2) { if(choice1 === choice2) { alert("The result is a tie!"); } if(choice1 === "rock") { if(choice2 === "scissors") { alert("rock wins"); } else { alert("paper wins"); } } if(choice1 === "paper") { if(choice2 === "rock") { alert("paper wins"); } else { if(choice2 === "scissors") { alert("scissors wins"); } } if(choice1 === "scissors") { if(choice2 === "rock") { alert("rock wins"); } else { if(choice2 === "paper") { alert("scissors wins"); } } } } }; console.log("User Choice: " + userChoice); console.log("Computer Choice: " + computerChoice); compare(userChoice, computerChoice) }Все, что я изменил, это вместо того, чтобы возвращать сообщение, оно высвечивает предупреждение с ответом. Я также поместил его в одну функцию, которая может быть вызвана при нажатии кнопки HTML.
Пример без всех {} и else if
Всегда используйте else, если это возможно.. поскольку ваши утверждения if-это разные случаи и применяется только один, вы должны использовать else if..
С операторами if, если у вас есть только 1 оператор после условия, которое вам не нужно {} (условие 1 ниже).. даже если у тебя есть "если".. еще если...блок высказывания ее считается одним высказыванием..(условие 2 ниже).. но если это поможет, вы можете использовать их вокруг "если".. еще если...блок заявление, чтобы помочь вашему поймите это лучше ..(условие 3 ниже).. ..
Также не используйте ===, если вы действительно не знаете, что он делает.. это может привести к тому, что вы будете новичком.. используйте == по умолчанию..
if(choice1 == choice2) //condition 1 return "The result is a tie!"; else if(choice1 == "rock") //condition 2 if(choice2 == "scissors") return "rock wins"; else return "paper wins"; else if(choice1 == "paper"){ //condition 3 if(choice2 == "rock") return "paper wins"; else return "scissors wins"; } else if(choice1 == "scissors") if(choice2 == "rock") return "rock wins"; else return "scissors wins";
var userChoice = prompt("Do you choose rock, paper or scissors? "); var computerChoice=Math.random(); { if(computerChoice <= ".33") { computerChoice === 'rock'; } else if(computerChoice<='.66' & '>=.34') { computerChoice === 'paper'; } else { computerChoice ===' scissors'; } } console.log( computerChoice);
var compare = function (choice1, choice2) { if (choice1 === choice2) { return "The result is a tie!"; } else { if(choice1 === "rock") { if(choice2 === "paper") { return "Paper beats rock. Computer Wins."; } else { return "Rock beats scissors. You win."; } } else { if(choice1 === "paper") { if(choice2 === "rock") { return "Paper beats rock. You Win."; } else { return "Scissors beat paper. Computer Wins."; } } if(choice1 === "scissors") { if(choice2 === "rock") { return "Rock beats scissors. Computer Wins."; } else { return "Scissors beat paper. You Win."; } } } } }; var r = function(user) { while(user < 0 | user >3) {user = prompt("Please don't act oversmart. Press '1' for rock, '2' for paper, and '3' for scissors."); } if(user === "1") user = "rock"; else { if(user === "2") {user = "paper";} else {user = "scissors";} }; console.log("You chose: " + user); computerChoice = Math.random() if(computerChoice <= 0.33) { computerChoice = "rock"; } else { if(computerChoice > 0.33 && computerChoice <=0.66) {computerChoice = "paper";} else {computerChoice = "scissors";} } console.log("The computer chose: "+computerChoice) console.log(compare(user, computerChoice)); if(user===computerChoice) { userChoice = user; return "1";} }; var userChoice = prompt("Press '1' for rock, '2' for paper, and '3' for scissors") var computerChoice; var a = r(userChoice); if(a === "1") {//console.log("1"); while(userChoice === computerChoice) { var a = prompt("Since there was a tie, please choose again. Press 1 for rock, 2 for paper and 3 for scissors.") var b = r(a); if(b !== "1") {break;} } }
Этот человек создаст идеальную, самоподражающуюся игру, пока кто-то не выиграет. Он также показывает, сколько игр вы сыграли. Все без использования петель!
count = 1; var Decisions = function() { if (count === 1) { userChoice = prompt("Do you choose rock, paper or scissors?"); } else { userChoice = prompt("It's a tie. Please make your choice again!"); } computerChoice = Math.random(); if (computerChoice < 0.4) { computerChoice = "rock"; } else if(computerChoice <= 0.8) { computerChoice = "paper"; } else { computerChoice = "scissors"; } console.log("User: " + userChoice); console.log("Computer: " + computerChoice); } Decisions(); var compare = function(choice1, choice2) { if (choice1 === choice2) { count = count + 1 console.log("The result is a tie!"); Decisions(); return compare(userChoice, computerChoice); } else if (choice1 === "rock") { if (choice2 === "scissors") { return "rock wins"; } else { return "paper wins"; } } else if (choice1 === "paper") { if (choice2 === "rock") { return "paper wins"; } else { return "scissors wins"; } } else if (choice1 === "scissors") { if (choice2 === "paper") { return "scissors win"; } else { return "rock wins"; } } } console.log(compare(userChoice,computerChoice)); console.log("Wow, you played " + count + " times!");
Это код, который я сделал в этом упражнении, и он сработал как заклинание... Я использовал логические операторы в своих утверждениях "если", и это было принято(очевидно).
Попробуйте :D
var userChoice = prompt("Do you choose rock, paper or scissor?"); var computerChoice = Math.random(); if (computerChoice > 0 && computerChoice < 0.33) { computerChoice = "Rock"; } else if (computerChoice > 0.34 && computerChoice < 0.67) { computerChoice = "Paper"; } else { computerChoice = "Scissor"; } console.log(computerChoice);
Comments