Firebase托管JS游戏代码跳过问题求助:战斗触发与存活检测异常
问题修复:JavaScript小游戏的两个偶发逻辑问题
问题1:有时tile返回有敌人却不触发战斗
原因
你在onNorthClick里调用了两次hasEnemy():一次用console.log打印结果,另一次在if条件里判断。因为hasEnemy()每次调用都会生成新的随机数,两次结果可能不一致——比如第一次随机出>0.6666的结果(日志显示true),第二次却生成了<=0.6666的数,导致if条件不成立,战斗不触发。
修复代码
把随机结果存到变量里,只调用一次hasEnemy():
gameView.onNorthClick = function(){ console.log("north"); oPos = thePlayer.pos; if ((thePlayer.pos - 5) < 0){ // 空操作可直接删除,不需要写null }else{ thePlayer.pos -= 5; gameView.updateLoc(oPos, thePlayer.pos); if(thePlayer.pos == 12){ gameView.updateNar("You are home"); gameView.homeMenu(); }else{ gameView.updateNar("You travel North"); const encounterEnemy = hasEnemy(); // 存储随机结果 console.log(encounterEnemy); if(encounterEnemy){ fightEnemy(); }else{ this.updateNar("Nothing around..."); } } } }
问题2:有时不检测玩家是否存活
原因
在onHitClick的逻辑里,你用else if判断玩家存活状态:如果敌人先死亡,代码会执行胜利分支,直接跳过玩家存活的判断。比如玩家攻击后,敌人血量归0,但玩家自己也因为敌人的反击血量归0,这时候只会触发“击败敌人”的逻辑,不会检测到玩家已经死亡。
修复代码
调整判断顺序,先检查玩家是否存活,确保玩家死亡的逻辑优先执行:
gameView.onHitClick = function(){ console.log("You Hit"); thePlayer.hp = thePlayer.hp - curEnemy.atk; curEnemy.hp = curEnemy.hp - thePlayer.atk; gameView.updateFight(thePlayer.hp, thePlayer.atk, thePlayer.def, curEnemy.hp, curEnemy.atk, curEnemy.def); this.updateNar("You hit for " + thePlayer.atk); // 优先检查玩家是否存活 if(!playerLive(thePlayer.hp)) { gameView.loseScene(thePlayer.kc, thePlayer.gold); gameView.loseMenu(); return; // 终止后续逻辑,避免冲突 } // 再检查敌人是否存活 if(!enemyLive(curEnemy.hp)){ this.updateNar("You beat the enemy"); thePlayer.kc += 1; thePlayer.exp += curEnemy.expw; thePlayer.gold += curEnemy.gold; gameView.mapScene(); gameView.moveMenu(); gameView.updateLoc(oPos, thePlayer.pos); } }
另外,你的playerLive函数可以简化成更简洁的写法:
function playerLive(php){ return php > 0; }
enemyLive函数如果逻辑相同,也可以做同样简化。
内容的提问来源于stack exchange,提问作者Aaron Johnson
相关产品推荐
相关产品推荐

