Magic Exam Randomizer Stumping me

Okay so I figured out all the solutions but the doors keep randomizing. I assume this is so I have to do something. Is this a loop I need to do with all the potential solutions? I’m sort of at a loss on how to beat the randomizer here.

I’ve gotten 21 gold a couple times but I feel like I’m cheesing it without actually coding in identifiers (?)

// Try to get the best grade (gold) at the magic exam.
// Move to each X mark, then use a spell.

hero.moveXY(18, 40);
var friend = hero.findNearestFriend();
if (friend) {
    hero.cast("heal", friend);
}
hero.moveXY(18, 25);
var enemy = hero.findNearestEnemy();
if (enemy) {
    hero.cast("force-bolt", enemy);
}
hero.moveXY(34, 40);
var friend = hero.findNearestFriend();
if (friend) {
    hero.cast("grow", friend);
}
hero.moveXY(34, 24);    
var enemy = hero.findNearestEnemy();
if (enemy) {
    hero.cast("shrink", enemy);


}

hero.moveXY(50, 24);
var friend = hero.findNearestFriend();
if (friend) {
    hero.cast("regen", friend);
}
hero.moveXY(50, 40);
var enemy = hero.findNearestEnemy();
if (enemy) {
    hero.cast("poison-cloud", enemy);
}
hero.moveXY(66, 40);
var item = hero.findNearestItem()
if (item.type == "potion") {
   hero.say("HEALTH");
   hero.moveXY(item.pos.x, item.pos.y);
}
hero.moveXY(66, 24);
var item = hero.findNearestItem()
if (item.type == "poison") {
   hero.say("BOOOOOOOOOOOO");
  hero.cast("grow", hero);
  hero.moveXY(item.pos.x, item.pos.y);
}