You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助:我开发的蛇水枪JavaScript游戏运行异常,请帮忙排查

蛇水枪游戏异常问题排查与修复

问题1:大小写不匹配导致判断失效

代码里words数组存的是首字母大写的选项('Snake'/'Water'/'Gun'),但判断用户输入时用的是全小写字符串。比如电脑随机选中Snake,你输入snake时,两者因大小写不同无法匹配,直接被判定为无效输入,完全打乱了胜负逻辑。

问题2:电脑选择未每轮重新随机

random变量定义在循环外面,只会在游戏启动时生成一次随机选项,后续所有回合电脑都用同一个选项,完全不符合“每回合随机选”的游戏规则。


修复后的代码

let words = ['snake', 'water', 'gun']; // 统一为小写,和输入判断逻辑对齐
let input;
let user_points = 0;
let computer_points = 0;
let chances = 0;

do {
  // 每回合重新生成电脑的随机选择
  let random = words[Math.floor(Math.random() * words.length)];
  input = prompt("Enter any one (snake, water, gun) =");
  
  // 统一转换输入为小写,兼容用户大小写混合的输入
  input = input?.toLowerCase();

  if (input == random) {
    console.log("Draw");
    chances++;
  } else if (input == 'snake' && random == 'gun') {
    console.log("Computer wins!");
    chances++;
    computer_points++;
  } else if (input == 'snake' && random == 'water') {
    console.log("You win!");
    chances++;
    user_points++;
  } else if (input == 'water' && random == 'snake') {
    console.log("Computer wins!");
    chances++;
    computer_points++;
  } else if (input == 'water' && random == 'gun') {
    console.log("You win!");
    chances++;
    user_points++;
  } else if (input == 'gun' && random == 'water') {
    console.log("Computer wins!");
    chances++;
    computer_points++;
  } else if (input == 'gun' && random == 'snake') {
    console.log("You win!");
    chances++;
    user_points++;
  } else {
    console.log('Invalid input, please try again.');
  }
} while (chances <= 5);

console.log(`Your points = ${user_points}`);
console.log(`Computer points = ${computer_points}`);

if (user_points < computer_points) {
  console.log('Sorry, the final winner is computer.');
  console.log('Game ended');
} else if (user_points > computer_points) {
  console.log('Congrats! You are the final winner.');
  console.log('Game ended');
} else {
  console.log("The game has ended, it's a draw.");
}

内容的提问来源于stack exchange,提问作者Utkarsh Sharma

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 19:25:19