如何通过for循环重复执行函数实现五轮石头剪刀布游戏?
如何通过for循环重复执行函数实现五轮石头剪刀布游戏?
嘿,我看了你的代码,问题其实很明显——你定义了playRound函数,但从来没调用它!这就是为什么输入后控制台没反应的核心原因。另外还有几个可以优化的小细节,我一步步给你梳理清楚:
问题分析与修复步骤
- 函数定义位置优化:你把
getComputerChoice、getHumanChoice和playRound都放在了for循环里面,这意味着每一轮循环都会重新定义一遍这些函数,完全没必要,把它们移到playGame函数内部、for循环外面就好,既高效又整洁。 - 必须调用playRound函数:你已经获取了人类和电脑的选择,但没有触发对决逻辑,所以在循环里拿到
humanChoice和computerChoice后,一定要调用playRound(humanChoice, computerChoice)才能让回合逻辑执行起来。 - (可选)平局回合的处理:如果希望平局不消耗回合数(也就是直到完成5次分出胜负的对局),可以把for循环改成while循环,但如果只是严格执行5轮不管结果,保持for循环就好。
修改后的完整代码
function playGame() { let humanScore = 0; let computerScore = 0; // 把函数移到循环外面,避免重复定义 function getComputerChoice() { let result = Math.ceil(Math.random() * 3); if (result === 1) { return "rock"; } else if (result === 2) { return "paper"; } else { return "scissors"; } } function getHumanChoice() { let humanResult = prompt("Let's play Rock, Paper, Scissors! Enter your choice:"); if (!humanResult) return "invalid"; // 处理用户取消输入的情况 const lowerChoice = humanResult.toLowerCase(); if (["rock", "paper", "scissors"].includes(lowerChoice)) { return lowerChoice; } else { return "invalid"; } } function playRound(humanChoice, computerChoice) { if (humanChoice === "invalid") { console.log("Try again! That's not a valid choice."); return; // 无效选择不处理分数 } if (humanChoice === computerChoice) { console.log(`Y'all both picked ${humanChoice}! It's a tie! AI:${computerScore} Human:${humanScore}`); } else if ( (humanChoice === "rock" && computerChoice === "scissors") || (humanChoice === "paper" && computerChoice === "rock") || (humanChoice === "scissors" && computerChoice === "paper") ) { humanScore++; console.log(`${humanChoice.charAt(0).toUpperCase() + humanChoice.slice(1)} beats ${computerChoice}! You win! AI:${computerScore} Human:${humanScore}`); } else { computerScore++; console.log(`${computerChoice.charAt(0).toUpperCase() + computerChoice.slice(1)} beats ${humanChoice}! AI wins! AI:${computerScore} Human:${humanScore}`); } } // 五轮循环,每轮执行完整的对决流程 for (let i = 0; i < 5; i++) { const computerChoice = getComputerChoice(); const humanChoice = getHumanChoice(); playRound(humanChoice, computerChoice); } // 五轮结束后显示最终结果 console.log("\nGame Over! Final Score:"); console.log(`AI: ${computerScore} | You: ${humanScore}`); if (humanScore > computerScore) { console.log("Congratulations! You won the game! 🎉"); } else if (computerScore > humanScore) { console.log("AI took the win this time! Better luck next time!"); } else { console.log("It's an overall tie!"); } }; playGame();
额外说明
我还帮你优化了一些细节:比如简化了playRound的判断逻辑(不用写那么多else if),处理了用户取消输入的情况,最后添加了五轮结束后的最终结果展示,让游戏体验更完整。
备注:内容来源于stack exchange,提问作者Jessi B.
相关产品推荐
相关产品推荐

