Wednesday, 26 December 2012

Action script.

All of the action script was made in separate files this was to done so i could see the individual classes, to do this i had to use a slightly different method to add the classes and functions to the main FLA. To do this i had to;

  1. name the files appropriate to the class name
  2. have everything on a file inside a "package"
  3. import everything buy using the "import statement"
Avatar

package
{
import flash.display.MovieClip;
public class Avatar extends MovieClip
{
public function Avatar()
{

}
}
}

Enemy

package
{
import flash.display.MovieClip;
public class Enemy extends MovieClip
{
public function Enemy( startX:Number, startY:Number )
{
x = startX;
y = startY;
}

public function moveDownAbit():void
{
var xSpeed:Number = 0; //pixels moved to the right per tick
var ySpeed:Number = 6; //pixels moved downwards per tick

x = x + xSpeed;
y = y + ySpeed;
}
}
}
Score

package
{
import flash.text.TextField;
public class Score extends Counter
{
public function Score()
{
super();
}
override public function updateDisplay():void
{
super.updateDisplay();
scoreDisplay.text = currentValue.toString();
}
}
}
Menu Screen

package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;

public class MenuScreen extends MovieClip
{
public function MenuScreen()
{
startButton.addEventListener( MouseEvent.CLICK, onClickStart );
}

public function onClickStart( event:MouseEvent ):void
{
dispatchEvent( new NavigationEvent( NavigationEvent.START ) );
}
}
}
Navigation Event

package
{
import flash.events.Event;
public class NavigationEvent extends Event
{
public static const RESTART:String = "restart";
public static const START:String = "start";
public function NavigationEvent( type:String )
{
super( type );
}
}
}
Avatar Event

package
{
import flash.events.Event;
public class AvatarEvent extends Event
{
public static const DEAD:String = "dead";

public function AvatarEvent( type:String )
{
super( type );
}
}
}
Counter

package
{
import flash.display.MovieClip;
public class Counter extends MovieClip
{
public var currentValue:Number;

public function Counter()
{
reset();
}

public function addToValue( amountToAdd:Number ):void
{
currentValue = currentValue + amountToAdd;
updateDisplay();
}

public function reset():void
{
currentValue = 0;
updateDisplay();
}

public function updateDisplay():void
{

}
}
}
Level Data

package
{
public class LevelData
{
public var backgroundImage:String;
public var pointsToReachNextLevel:Number;
public var enemySpawnRate:Number;
public var levelNum:Number;

public function LevelData( levelNumber:Number )
{
levelNum = levelNumber;
{
backgroundImage = "grey";
pointsToReachNextLevel = 500;
enemySpawnRate = 0.1;
}
if ( levelNumber == 2 )
{
backgroundImage = "red";
pointsToReachNextLevel = 1500;
enemySpawnRate = 0.2;
}
if ( levelNumber == 3 )
{
backgroundImage = "skyblue";
pointsToReachNextLevel = 2500;
enemySpawnRate = 0.3;
}
if ( levelNumber == 4 )
{
backgroundImage = "black";
pointsToReachNextLevel = 3500;
enemySpawnRate = 0.5;
}
if ( levelNumber == 5 )
{
backgroundImage = "blue";
pointsToReachNextLevel = 99999;
enemySpawnRate = 0.55;
}
}
}
}
Game Over Screen

package
{
import flash.display.MovieClip;
import flash.display.SimpleButton;
import flash.events.MouseEvent;
import flash.text.TextField;
import flash.ui.Mouse;
import flash.net.SharedObject;

public class GameOverScreen extends MovieClip
{
var sharedObject:SharedObject;

public function GameOverScreen()
{
Mouse.show();
restartButton.addEventListener( MouseEvent.CLICK, onClickRestart );
sharedObject = SharedObject.getLocal("alienavoider");
}
public function onClickRestart( mouseEvent:MouseEvent ):void
{
dispatchEvent( new NavigationEvent( NavigationEvent.RESTART ) );
}
public function setFinalScore( scoreValue:Number ):void
{
finalScore.text = scoreValue.toString();
try
{
if (sharedObject.data.bestScore == null)
{
sharedObject.data.bestScore = scoreValue;
}
else if ( scoreValue > sharedObject.data.bestScore )
{
sharedObject.data.bestScore = scoreValue;
}
bestScore.text = sharedObject.data.bestScore.toString();
sharedObject.flush();
}
catch (sharedObjectError:Error)
{
trace( "Caught this error:", sharedObjectError.name, sharedObjectError.message );
bestScore.text = "???";
}
}
}
}
Pixel Perfect Collision

package
{
import flash.display.BitmapData;
import flash.display.BitmapDataChannel;
import flash.display.BlendMode;
import flash.display.DisplayObject;
import flash.display.DisplayObjectContainer;
import flash.geom.Matrix;
import flash.geom.Point;
import flash.geom.Rectangle;
public class PixelPerfectCollisionDetection
{
/** Get the collision rectangle between two display objects. **/
public static function getCollisionRect(target1:DisplayObject, target2:DisplayObject, commonParent:DisplayObjectContainer, pixelPrecise:Boolean = false, tolerance:Number = 0):Rectangle
{
// get bounding boxes in common parent's coordinate space
var rect1:Rectangle = target1.getBounds(commonParent);
var rect2:Rectangle = target2.getBounds(commonParent);
// find the intersection of the two bounding boxes
var intersectionRect:Rectangle = rect1.intersection(rect2);
if (intersectionRect.size.length> 0)
{
if (pixelPrecise)
{
// size of rect needs to integer size for bitmap data
intersectionRect.width = Math.ceil(intersectionRect.width);
intersectionRect.height = Math.ceil(intersectionRect.height);
// get the alpha maps for the display objects
var alpha1:BitmapData = getAlphaMap(target1, intersectionRect, BitmapDataChannel.RED, commonParent);
var alpha2:BitmapData = getAlphaMap(target2, intersectionRect, BitmapDataChannel.GREEN, commonParent);
// combine the alpha maps
alpha1.draw(alpha2, null, null, BlendMode.LIGHTEN);
// calculate the search color
var searchColor:uint;
if (tolerance <= 0)
{
searchColor = 0x010100;
}
else
{
if (tolerance> 1) tolerance = 1;
var byte:int = Math.round(tolerance * 255);
searchColor = (byte <<16) | (byte <<8) | 0;
}
// find color
var collisionRect:Rectangle = alpha1.getColorBoundsRect(searchColor, searchColor);
collisionRect.x += intersectionRect.x;
collisionRect.y += intersectionRect.y;
return collisionRect;
}
else
{
return intersectionRect;
}
}
else
{
// no intersection
return null;
}
}
/** Gets the alpha map of the display object and places it in the specified channel. **/
private static function getAlphaMap(target:DisplayObject, rect:Rectangle, channel:uint, commonParent:DisplayObjectContainer):BitmapData
{
// calculate the transform for the display object relative to the common parent
var parentXformInvert:Matrix = commonParent.transform.concatenatedMatrix.clone();
parentXformInvert.invert();
var targetXform:Matrix = target.transform.concatenatedMatrix.clone();
targetXform.concat(parentXformInvert);
// translate the target into the rect's space
targetXform.translate(-rect.x, -rect.y);
// draw the target and extract its alpha channel into a color channel
var bitmapData:BitmapData = new BitmapData(rect.width, rect.height, true, 0);
bitmapData.draw(target, targetXform);
var alphaChannel:BitmapData = new BitmapData(rect.width, rect.height, false, 0);
alphaChannel.copyChannel(bitmapData, bitmapData.rect, new Point(0, 0), BitmapDataChannel.ALPHA, channel);
return alphaChannel;
}
/** Get the center of the collision's bounding box. **/
public static function getCollisionPoint(target1:DisplayObject, target2:DisplayObject, commonParent:DisplayObjectContainer, pixelPrecise:Boolean = false, tolerance:Number = 0):Point
{
var collisionRect:Rectangle = getCollisionRect(target1, target2, commonParent, pixelPrecise, tolerance);
if (collisionRect != null && collisionRect.size.length> 0)
{
var x:Number = (collisionRect.left + collisionRect.right) / 2;
var y:Number = (collisionRect.top + collisionRect.bottom) / 2;
return new Point(x, y);
}
return null;
}
/** Are the two display objects colliding (overlapping)? **/
public static function isColliding(target1:DisplayObject, target2:DisplayObject, commonParent:DisplayObjectContainer, pixelPrecise:Boolean = false, tolerance:Number = 0):Boolean
{
var collisionRect:Rectangle = getCollisionRect(target1, target2, commonParent, pixelPrecise, tolerance);
if (collisionRect != null && collisionRect.size.length> 0) return true;
else return false;
}
}
}
Document Class

package
{
import flash.display.MovieClip;
public class DocumentClass extends MovieClip
{
public var menuScreen:MenuScreen;
public var playScreen:AvoiderGame;
public var gameOverScreen:GameOverScreen;

public function DocumentClass()
{
menuScreen = new MenuScreen();
menuScreen.addEventListener( NavigationEvent.START, onRequestStart, false, 0, true );
menuScreen.x = 0;
menuScreen.y = 0;
addChild( menuScreen );

stage.focus = menuScreen;
stage.stageFocusRect = false;
}

public function onAvatarDeath( avatarEvent:AvatarEvent ):void
{
var finalScore:Number = playScreen.getFinalScore();
gameOverScreen = new GameOverScreen();
gameOverScreen.addEventListener(NavigationEvent.RESTART, onRequestRestart, false, 0, true );
gameOverScreen.x = 0;
gameOverScreen.y = 0;
gameOverScreen.setFinalScore( finalScore );
addChild( gameOverScreen );

removeChild( playScreen );
playScreen = null;

stage.focus = gameOverScreen;
}

public function onRequestStart( navigationEvent:NavigationEvent ):void
{
playScreen = new AvoiderGame();
playScreen.addEventListener(AvatarEvent.DEAD, onAvatarDeath, false, 0, true );
playScreen.x = 0;
playScreen.y = 0;
addChild( playScreen );

removeChild( menuScreen );
menuScreen = null;

stage.focus = playScreen;
}

public function onRequestRestart( navigationEvent:NavigationEvent ):void
{
restartGame();
}

public function restartGame():void
{
playScreen = new AvoiderGame();
playScreen.addEventListener( AvatarEvent.DEAD, onAvatarDeath, false, 0, true );
playScreen.x = 0;
playScreen.y = 0;
addChild( playScreen );

removeChild( gameOverScreen );
gameOverScreen = null;

stage.focus = playScreen;
}
}
}
Avoider Game

package
{
import flash.display.MovieClip;
import flash.utils.Timer;
import flash.events.TimerEvent;
import flash.ui.Mouse;

public class AvoiderGame extends MovieClip
{
public var army:Array;
public var enemy:Enemy;
public var avatar:Avatar;
public var gameTimer:Timer;
public var currentLevelData:LevelData;

public function AvoiderGame()
{
currentLevelData = new LevelData(1);
if (currentLevelData.backgroundImage == "grey")
{
backgroundContainer.addChild( new GreyBackground() );
}
else if ( currentLevelData.backgroundImage == "red" )
{
backgroundContainer.addChild( new RedBackground() );
}
Mouse.hide();
army = new Array();


avatar = new Avatar();
addChild( avatar );
avatar.x = mouseX;
avatar.y = mouseY;

gameTimer = new Timer(25);
gameTimer.addEventListener( TimerEvent.TIMER, onTick );
gameTimer.start();
}

public function onTick( timerEvent:TimerEvent ):void
{
if (Math.random() < currentLevelData.enemySpawnRate)
{
var randomX:Number = Math.random() * 800;
var newEnemy:Enemy = new Enemy(randomX,-15);
army.push( newEnemy );
addChild( newEnemy );
gameScore.addToValue( 10 );
}
avatar.x = mouseX;
avatar.y = mouseY;

var i:int = army.length - 1;
var enemy:Enemy;
while ( i > -1 )
{
enemy = army[i];
enemy.moveDownAbit();
if ( PixelPerfectCollisionDetection.isColliding( avatar, enemy, this, true ) )
{
gameTimer.stop();
dispatchEvent( new AvatarEvent( AvatarEvent.DEAD ) );
}
if (enemy.y > 480)
{
removeChild( enemy );
army.splice( i, 1 );
}
i = i - 1;
}

if (gameScore.currentValue >= currentLevelData.pointsToReachNextLevel)
{
currentLevelData = new LevelData(currentLevelData.levelNum + 1);
setBackgroundImage();
}
}
public function setBackgroundImage():void
{
if (currentLevelData.backgroundImage == "grey")
{
backgroundContainer.addChild( new GreyBackground() );
}
else if ( currentLevelData.backgroundImage == "red" )
{
backgroundContainer.addChild( new RedBackground() );
}
else if ( currentLevelData.backgroundImage == "skyblue" )
{
backgroundContainer.addChild( new BlueBackground() );
}
else if ( currentLevelData.backgroundImage == "black" )
{
backgroundContainer.addChild( new BlackBackground() );
}
}
public function getFinalScore():Number
{
return gameScore.currentValue;
}
}
}