Simple Homegrown AI Overview
The enemy tanks chase the player
object
based on a set of simple rules. We have coded those rules into the
gameStateEnemyMove()
function, which
is one of the longest and most complicated functions in this book. Let’s
first step through the logic used to create the function, and then you
can examine it in Example 9-2.
This function starts by looping through the enemy
array. It must determine a new tile
location on which to move each enemy. To do so, it follows some simple
rules that determine the order in which the testBounds()
function will test the movement
directions:
First, it tests to see whether the player is closer to the enemy vertically or horizontally.
If vertically, and the player is above the enemy, it places
up
and thendown
in thedirectionsToTest
array.If vertically, and the player is below the enemy, it places
down
and thenup
in thedirectionsToTest
array.Note
The
up
and thendown
, ordown
and thenup
, directions are pushed into thedirectionsTest
array to simplify the AI. The logic here is if the player is up from the enemy, but the enemy is blocked by an object, the enemy will try the opposite direction first. In our game, there will 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 ...
Get HTML5 Canvas, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.