ForumsProgramming ForumHappy Blocks - Adding AI

0 8632
1,299 posts

Happy Blocks - hero blitting and movement

Download the img's above and place into your assets folder then open your programming software and load the file.

For simplicity the rules will be, spawn a block outside of the screen, have them run across the screen, then remove them when they exit the other side.

First we will create an array that will contain a list of each block that is created. We will also create a sprite layer that will contain all of the sprites of the blocks.

Scroll down to your game loop and update it to include 2 new functions. Spawn blocks and AI movement. It could look something like this.

Pretty straight forward. Move the hero, calculate spawn data, then move all the blocks.

Jumping into the spawnBlocks function. There will be a 1:10 random spawn calculation. If the condition is met then there will be a 1:4 random color calculation. When the blocks spawn, depending on the color either x or y coordinates will be random. Once all the conditions have been met the block will be added to the block layer, and added (push) to the blockArray. It will look like this.

If you followed along with the first portion Happy Blocks - hero blitting and movement you should already know how to get the img's to display correctly. Instead I will briefly show the passing arguments in the RedBlockClass.

Once spawned, the tells the newly created block where it is located and it appears at the specific coordinates. The coordinates here are outside the screen so the player will not see it appear.

Simple enough we have spawning blocks. Now lets move into the function that tells them to move.

The for loop

for (var i:int = blockArray.length - 1; i >= 0; i--)

looking closely it creates a variable of i and gives it a number based on each block in the array.


Then it is cast as an object and tells the object to loop.

Going back to your created blocks you need to add a public function that is controlled by the block itself.

The block will continue to do what it is programmed to do until it needs to be removed. Then it "returns" if it is still alive or not by using a boolean.

public function loop():Boolean

Up until now, functions have been voided out but this ensures that a boolean is required to be returned.

Now back to your and in the for loop, if the block returns a false that it is not alive anymore the sprite will be removed from the blockLayer and the data removed (splice) from the array


HappyBlocks - Collision and Score

var blockArray:Array = new Array();
var blockLayer:Sprite = new Sprite();
  • 0 Replies
Showing 16-15 of 0

We may use cookies to help customize your experience, including performing analytics and serving ads.
Learn More