HTML and CSS Reference
Simple Homegrown AI Overview
Theenemytankschasethe player objectbasedonasetofsimplerules.Wehavecodedthose
rules into the gameStateEnemyMove() function, which is one of the longest and most com-
plicated functions in this topic. Let's first step through the logic used to create the function,
This function starts by looping through the enemy array. It must determine a new tile location
in which the testBounds() function will test the movement directions:
1. First, it tests to see whether the player is closer to the enemy vertically or horizontally.
2. If vertically, and the player is above the enemy, it places up and then down in the dir-
3. If vertically, and the player is below the enemy, it places down and then up in the dir-
The up and then down , or down and then up , directions are pushed into the directionsTest
array to simplify the AI. The logic here is if the player is up from the enemy, but the enemy
be no instance when an object blocks the direction the enemy tank wants to move in, because
the only illegal direction is trying to move off the bounds of the screen. If we add tiles to our
playfield that block the enemy, this entire set of AI code suddenly becomes very useful and
necessary. We have included this entire homegrown chase AI in our game in case more of
these tile types are added.
4. It then looks where to add the left and right directions. It does this based on which
way will put it closer to the player.
5. If the horizontal direction and not the vertical direction is the shortest, it runs through
thesametypeoflogic,butthistimeusing left andthen right ,then up andthen down .
6. When this is complete, all four directions will be in the directionsToTest array.
Next, the logic finds a number between 0 and 99 and checks whether it is less than the
chanceRandomEnemyMovement value. If it is, it ignores the directionsToTest array and
simply tries to find a random direction to move in. In either case, all the directions (either