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

JS宝可梦小游戏结束后自动重启、执行完thanksForPlaying仍调用game问题排查

问题排查与修复方案

问题1:选择不再重玩后仍自动启动攻击流程

根本原因

你代码中所有判断胜负的逻辑都错误使用了while循环而非if判断,且游戏流程是递归调用链(game()→攻击函数→opponentAttack()→game())没有终止机制:

  1. 当胜负条件满足时,while会执行win()/lose(),进而调用restart()
  2. 你选择不再重玩后,thanksForPlaying执行完毕,代码会回到while循环的调用位置,继续执行当前函数后续的逻辑
  3. 最终会走到opponentAttack()末尾的game()调用,重新触发攻击流程

问题2:游戏结束后自动重启

根本原因

  1. win()/lose()函数执行完胜负提示后直接调用了restart(),没有额外的确认流程
  2. while循环只要血量条件满足就会反复执行win()/lose(),进一步导致restart()被重复触发

修复步骤

第一步:新增全局状态控制游戏是否终止

在全局变量声明区新增:

let isGameOver = false

第二步:修改所有while胜负判断为if+return

修改game()函数中的判断:

// 原来的while改成if,执行完win/lose后return终止后续代码
if (opponentHealth <= 0) {
  win()
  return
}
if (pokemonHealth <= 0) {
  lose()
  return
}

同步修改opponentAttack()函数中的判断:

if (opponentHealth <= 0) {
  win()
  return
}
if (pokemonHealth <= 0) {
  lose()
  return
}

第三步:终止递归调用链

修改opponentAttack()末尾的game()调用,增加状态判断:

if (!isGameOver) {
  game()
}

第四步:修改restart()和thanksForPlaying()同步状态

restart()开头重置游戏状态:

function restart() {
  isGameOver = false
  opponentHealth = 100
  pokemonHealth = 100
  pokemonEnergy = 100
  // 其余原有代码不变
}

thanksForPlaying()修改为终止状态:

function thanksForPlaying(){
  alert("Thank you for playing pokemon game\n By Spencer")
  isGameOver = true
}

可选优化:修复能量判断死代码

你当前的能量判断逻辑是死代码永远不会触发,可以调整为:

// game函数中攻击选择部分修改
attackChoice = prompt("Which attack do you want to use?\n1." + attack1 + "\n2." + attack2 + "\n3." + attack3 + "\nType 1, 2 or 3")
let needEnergy
if (attackChoice == 1) needEnergy = 5
else if (attackChoice == 2) needEnergy = 15
else if (attackChoice == 3) needEnergy = 15
else {
  alert(pokemon + " has missed\n(invalid input)")
  opponentAttack()
  return
}
// 先判断能量是否足够
if (pokemonEnergy < needEnergy) {
  alert("Not enough energy")
  opponentAttack()
  return
}
// 能量足够再扣能量执行对应攻击
pokemonEnergy -= needEnergy
if (attackChoice == 1) attackOne()
else if (attackChoice == 2) attackTwo()
else if (attackChoice == 3) attackThree()

内容的提问来源于stack exchange,提问作者Cody Brynlund

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 10:48:04