Very intelligent monsters calculate whether it is more advantageous in terms of damaging the enemy versus taking damage themselves to pursue a target in melee, keep a safe distance and attack from range, or flee. Complex solutions would involve the monster storing lots of data about which attacks it has seen its opponents perform; however, this might get memory-intensive and expand save files quite a bit. A possible algorithm that relies only on game state and is based on FIQhack’s dragon AI algorithm is as follows:

   If able to attack at range (spit/breathe/shoot missiles/use items/etc):
     If the target is in range but not adjacent:
       Attack at range.
     Else if the target is adjacent, and is at least as fast as the monster:
       Attack in melee, or use ranged attacks point blank.
     Otherwise:
       Try to move somewhere aligned with the target, as far away as possible while still being in range.
   Else if the monster is unable to attack at range but will be able to soon (dragon):
     Stay out of line with the target.
   Otherwise:
      Close to melee range.