I simply changed the distance to be dynamic based on closeness to the edge and it's getting into the many 100's of thousands. This simple change also seemed to fix the edge case of the respawn hitting the player is solved since the player never gets into that magic position (the enemy has to be in a very specific position for the eyes to reach the end just as the player does).
function bot() {
/* direction of the enemy: to our right (1) or to our left (-1) */
dir = (enemy.x > player.x) ? 1 : -1;
nearWall = enemy.x < 10 || enemy.x > 90
/* if pac-man... */
if (
(
/* ...has no powerup or powerup expires in less than 10 "ticks" */
powerTicks < 10 &&
/* ...is headed toward enemy */ player.vx == dir &&
/* ...is too close to enemy */ abs(player.x - enemy.x)
/* ...the distance before running away can be lower if we're near an edge */
< (dir == 1 ? player.x / 7 : ((100 - player.x) / 7))+7 &&
/* and if enemy's state is not "eyes flying back" */
enemy.eyeVx == 0)
) {
// "ArrowUp" or any arrow key reverses the direction of pac-man
document.dispatchEvent(new KeyboardEvent('keydown', {code: 'ArrowUp'}));
document.dispatchEvent(new KeyboardEvent('keyup', {code: 'ArrowUp'}));
}
}
setInterval(bot, 10);