Disclaimer, this isn’t aimed at beginners, but to intermediate / advanced CodeCombaters.
This post is inspired by the Notepad idea. Here is one of my CodeCombat Notepad functions
In repeatable levels, I’ve been improving from the bottom up my initial code. As new enemy types are to be considered, I’ve been having a lot of
if ( enemy.type == "munckin" ) {
} else if ( enemy.type == "thrower" ){
} else if ( ... ) {
} else if ( ... ) {
etc...
As complexity goes up, it’s rather messy and clunky. So I decided to try and create a function to sort the prioritizing problem. Here is my shot at it.
var arrEnemyTypes = ["brawler","shaman","fangrider","ogre","thrower","scout","munchkin"];
// Types from highest priority to lowest.
function findBestTarget(This){
var myTarget = null ;
for( var iType = 0 ; iType < arrEnemyTypes.length ; iType++ ){
// Checking each group of enemy, from top priority to bottom priority.
var currGroup = This.findByType( arrEnemyTypes[iType] );
if( myTarget ){ // If I found a priority target _
break; // _ no need to go further in lower priorities.
}
if( currGroup[0] ) { // If this group isn't empty
// ****** Selection Algorithm *********
// For loop within the currGroup
// that sets myTarget if a specific criterium is met
// **************************************
} // if currGroup[0]
} // for iType
return myTarget;
}
In the example below, I’m playing a PotionMaster with Lightning Twig with a stream of unit coming my way. I want to throw bolts through the entire stream, and selecting a close target could tilt 45°, rendering my deadly weapon useless.
Thus my Selection Algorithm is selecting the farthest highpriority enemy away from me. I also check if it is not out of range, and if it isn’t too close. You can swap in any selection algorithm you want (like selecting closest, or healthiest, or fastest or whatever criterium you want).
if( currGroup[0] ) { // If this group isn't empty
var maxiDist = 0; // loop initialization
for( var iUnit = 0 ; iUnit < currGroup.length ; iUnit++){
// Loop to select the criterium you want.
var currUnit = currGroup[iUnit];
var currDist = This.distanceTo( currUnit ) ;
if( currDist > This.attackRange || currDist < 10 ){
// if out of range, or too close _
continue; // _ don't select this unit.
}
if(currDist>maxiDist){
// Selecting farthest unit
maxiDist = currDist;
myTarget = currUnit;
}
} // for iUnit
} // if currGroup
I’d be glad if someone told me “you can improve this here”. I’d love if this function could be useful to somebody.