我正在努力确保用户插入正确的字符串,但到目前为止似乎解决方案只是喜欢逃避我。它是一个迷你纸,剪刀,摇滚游戏。如果用户输入除allowedString之外的其他字符串,则应该要求他继续,然后会出现提示对话框。这是代码。
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";
}
console.log("Computer: " + computerChoice);
var compare = function(choice1,choice2)
{
ch(choice1);
if (choice1 === choice2){
return"The result is a tie!";
}
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 ==="rock"){
return"rock wins";
}
else{
return"scissors wins";
}
}
}
var ch = function(user)
{
allowedString = ["paper", "scissors", "rock"];
if (!Boolean(user in allowedString)){
if (confirm("Your choice is invalid, Do you want to try again?")) {
userChoice = prompt("Choose rock, paper or scissors?");
compare(userChoice, computerChoice);
}
else{
console.log("Thanks for playing");
}
}
else return;
}
compare(userChoice, computerChoice);
答案 0 :(得分:1)
ch
验证功能有点不精确。它总是返回错误。
if (allowedString.indexOf(user) > -1)
{
console.log('ok');
return;
}
我认为现在它按预期工作了。如果没问题,请告诉我。
答案 1 :(得分:-1)
只是为了好玩,我写了我的版本:
var rules = {
rock: {beat: ['scissors'], loses: ['paper']},
scissors: {beat: ['paper'], loses: ['rock']},
paper: {beat: ['rock'], loses: ['scissors']}
}
var getUserChoice = function(text){
var userChoice = prompt(text);
if(userChoice in rules)
return userChoice;
return getUserChoice("Wrong choice, try again! Choose rock, paper or scissors");
};
var getComputerChoice = function(){
return Object.keys(rules)[Math.floor(Math.random() * 3)];
}
var getWinner = function(userChoice, computerChoice){
if(rules[userChoice].beat.indexOf(computerChoice) !== -1)
return 'user';
else if(rules[userChoice].loses.indexOf(computerChoice) !== -1)
return 'computer';
return 'dead heat';
}
var userChoice = getUserChoice("Do you choose rock, paper or scissors?");
var computerChoice = getComputerChoice();
var winner = getWinner(userChoice, computerChoice);
console.log('userChoice=', userChoice, ', computerChoice=', computerChoice, ', winner=', winner);