我是JS的新手,当用户在确认中单击OK后,试图将用户带回程序的开始时,我被卡住了



我被告知要使用javascript制作剪刀布或石头游戏。在用户到达脚本结束后,我需要知道如何创建一个函数或者我认为这是当用户点击"ok"时所需要的;在confirm中,true值将把用户带到开始,直到用户单击cancel。但即使我建立了一个函数,我该把它代入哪里呢?非常感谢大家!

这是我到目前为止所做的…

alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
prompt("Type in P for Paper, R for Rock, Or S for Scissors!")
const storedLetters = ["R", "P", "S"];
const rockPaperScissors = storedLetters[Math.floor(Math.random() * storedLetters.length)]; 
console.log(rockPaperScissors);
var howManyTimesDidYouWin = 0;
var howMayTimesDidILose = 0;
var howManyTimesDidItie = 0;
// Scanner mySccanner = new Scanner(System.in);
if(prompt = "R") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors == "R") {
alert("We have Tied!");
} else if (rockPaperScissors == "P") {
alert("Computer has won!");
} else {
alert("You have won!");
}  
} else if(prompt = "P") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors == "P") {
alert("We have Tied!");
} else if (rockPaperScissors == "S") {
alert("Computer has won!");
} else {
alert("You have won!");
}
} else if(prompt =="S") {
alert("1, 2, 3! " + rockPaperScissors);
if(rockPaperScissors = "S") {
alert("We have Tied!");
} else if (rockPaperScissors == "R") {
alert("Computer has won!");
} else {
alert("You have won!");
}
} 
if (alert = "We have Tied") {
howManyTimesDidItie++;
} else if (alert = "You have won!") {
howManyTimesDidYouWin++;
} else if (alert = "Computer has won!") {
howMayTimesDidILose++;
} 
console.log(`Your total wins are:  ${howManyTimesDidYouWin} and Your Loss are: ${howMayTimesDidILose} and You Tied: ${howManyTimesDidItie}`);
let confirmation = confirm(`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`);
//This is where I get stuck! 
// if(confirmation == false) {
//    break;
// } else {
//    continue;
// while(confirmation == true) {

// }

// while(confirmation) {
//     continue;
// }
// while(confirmation = true) {
//     continue;
// } 
// var returnToStart = function() {
//     if(confirmation == true) {
//        continue; 
//     } else {
//         break;
//   }

通过一些重构和将公共逻辑提取到函数中,您可以使整个程序更简单一些,并实现您想要的重复性。

我已经将每种情况的计数提取为常量,以便您可以轻松地跟踪统计信息。

我还在它自己的函数中添加了重复的游戏逻辑,然后在游戏运行的逻辑中使用(runGame())。

这允许我们重用重复的代码。然后,我将整个游戏逻辑放入playGame()函数中,最后,game()函数负责接收玩家的输入并循环运行整个游戏,直到玩家取消。

let WIN_COUNT = 0;
let LOSE_COUNT = 0;
let TIE_COUNT = 0;
function gameLogic(rockPaperScissors, firstLetter, secondLetter) {
alert("1, 2, 3! " + rockPaperScissors);
if (rockPaperScissors === firstLetter) {
alert("We have Tied!");
TIE_COUNT++;
} else if (rockPaperScissors === secondLetter) {
alert("Computer has won!");
LOSE_COUNT++;
} else {
alert("You have won!");
WIN_COUNT++;
}
}
function runGame(input, rockPaperScissors, letters) {
if (input === letters[0]) {
gameLogic(rockPaperScissors, letters[0], letters[1]);
} else if (input === letters[1]) {
gameLogic(rockPaperScissors, letters[1], letters[2]);
} else if (input === letters[2]) {
gameLogic(rockPaperScissors, letters[2], letters[0]);
}
}
function playGame() {
alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
const input = prompt("Type in P for Paper, R for Rock, Or S for Scissors!");
const storedLetters = ["R", "P", "S"];
const rockPaperScissors =
storedLetters[Math.floor(Math.random() * storedLetters.length)];
console.log(rockPaperScissors);
runGame(input, rockPaperScissors, storedLetters);
console.log(
`Your total wins are:  ${WIN_COUNT} and Your Loss are: ${LOSE_COUNT} and You Tied: ${TIE_COUNT}`
);
}
function game() {
let playAgain = true;
while (playAgain !== false) {
playGame();
playAgain = confirm(
`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`
);
}
}
game();

您需要将不同的逻辑分离为可以单独调用的函数。在下面的示例中,我创建了4个函数:gameInitgameStartaskUsercheckResult

  • gameInit重置所有数据为零,然后通过调用gameStart开始游戏。

  • gameStart启动游戏并保存结果。在此之后,系统会提示用户是否要继续游戏,还是重置所有状态并再次游戏。调用gameInit用于重置,gameStart用于继续。

  • askUser提示用户选择,确保它是有效的。RPS(不区分大小写)。

  • checkResult使用预定义变量judge检查结果。

我还调整了一些你的代码,使它看起来有点可读(即,删除了太多的if-else)。

const storedLetters = ['r', 'p', 's'];
//store here for easy message formatting.
const rpsNames = ['rock', 'paper', 'scissors'];
// yeah, here's the judge that tells you which option
// will beat the one in the right
const judge = {
'rock': 'scissors', // r beats s
'paper': 'rock', // p beats r
'scissors': 'paper' // s beats p
};
// store here so we can easily access using `msgs[result]`
const msgs = {
tie: 'We have Tied!',
lose: 'Computer has won!',
win: 'You have won!'
};
// store results as objects so we can do `results[result]++`
// instead of incrementing different variables using `if-else`
var results = {
win: 0,
lose: 0,
tie: 0
};
function gameInit() {
alert("Welcome to Rock Paper Scissors Game! Press OK to continue");
results = {
win: 0,
lose: 0,
tie: 0
};
gameStart();
}
function gameStart() {
let userLetter = askUser();
let userIdx = storedLetters.indexOf(userLetter);
let userSelect = rpsNames[userIdx];
let compSelectIdx = Math.floor(Math.random() * 3); //randomly select 0-2
let compSelect = rpsNames[compSelectIdx];
alert("1, 2, 3! Computer picks " + compSelect);
let res = checkResult(userSelect, compSelect);
let msg = msgs[res];
alert(`${msg} You: ${userSelect}, Computer: ${compSelect}`);
//update stats
results[res]++;
alert(`Your total wins are:  ${results.win} and Your Loss are: ${results.lose} and You Tied: ${results.tie}`);
let confirmation = confirm(`Do you want to play again? If Yes, press "OK"! If you do not wish to continue, press "Cancel"`);
if (confirmation) {
gameStart();
} else {
let restart = confirm('Do you want to reset all stats and play again?');
if (restart) {
gameInit();
}
}
}
function askUser() {
//make sure use it's not case-sensitive
var res = prompt("Type in P for Paper, R for Rock, Or S for Scissors!");
if (res) {
res = res.toLowerCase();
}
if (storedLetters.indexOf(res) === -1)
return askUser(); //ask again if incorrect selection
else
return res;
}
function checkResult(user, comp) {
if (user === comp) {
return 'tie';
}
var loser = judge[user]; //who loses vs user
// user beats comp
if (loser === comp) {
return 'win';
} else {
return 'lose';
}
}
gameInit();

最新更新