求助:用JavaScript开发含三个骰子与投注功能的测试程序
完善骰子投注游戏的Bet函数方案
没问题,我来帮你搞定这个Bet函数!根据你的游戏规则——任意一个投注命中骰子点数就加1分,我们可以用简洁的数组方法来实现逻辑,同时优化一下变量声明的规范。
完整代码实现
// 初始化游戏变量(建议用let/const替代var,更符合现代JS标准) let points = 1; let slot1 = Math.floor((Math.random() * 6) + 1); let slot2 = Math.floor((Math.random() * 6) + 1); let slot3 = Math.floor((Math.random() * 6) + 1); let dices = [slot1, slot2, slot3]; function Bet(bet1, bet2, bet3) { // 将投注选项转为数组,方便统一检查 const userBets = [bet1, bet2, bet3]; // 检查是否有任意一个投注命中骰子点数 const isWin = userBets.some(bet => dices.includes(bet)); // 命中则加分 if (isWin) { points++; console.log(`🎉 命中了!当前分数:${points}`); // 可选:添加游戏反馈 } else { console.log(`😯 没命中,当前分数:${points}`); // 可选:添加游戏反馈 } } // 调用示例 Bet(1, 2, 3);
关键逻辑说明
Array.some():遍历投注数组,只要有一个元素满足条件(命中骰子点数)就返回true,避免了繁琐的多条件判断Array.includes():检查骰子数组中是否包含当前投注的数字,语法简洁直观- 用
let替代var:避免变量提升带来的潜在问题,让变量作用域更清晰
额外优化建议
如果希望每次投注都重新生成骰子点数(更符合真实游戏流程),可以添加一个摇骰子的函数:
// 新增摇骰子函数 function rollDices() { slot1 = Math.floor((Math.random() * 6) + 1); slot2 = Math.floor((Math.random() * 6) + 1); slot3 = Math.floor((Math.random() * 6) + 1); dices = [slot1, slot2, slot3]; console.log(`🎲 新骰子点数:${dices.join(', ')}`); } // 游戏流程示例 rollDices(); // 先摇骰子 Bet(1, 2, 3); // 然后投注
内容的提问来源于stack exchange,提问作者Richard Phan
相关产品推荐
相关产品推荐

