package { import mx.core.UIComponent; import flash.events.MouseEvent; import flash.display.Loader; import flash.net.URLRequest; import flash.events.Event; public class MoonPatrolGame extends UIComponent { private var backgroundLoader:Loader; private var middlegroundLoader:Loader; private var foregroundLoader:Loader; private var buggyLoader:Loader; private var verticalSpeed:int; private var groundLevel:int; public function MoonPatrolGame() { // Call the constructor for the superclass UIComponent super(); // Load the images for the buggy, the foreground, midddleground and background backgroundLoader = new Loader(); middlegroundLoader = new Loader(); foregroundLoader = new Loader(); buggyLoader = new Loader(); backgroundLoader.load(new URLRequest("./img/background.png")); middlegroundLoader.load(new URLRequest("./img/middleground.png")); foregroundLoader.load(new URLRequest("./img/foreground.png")); buggyLoader.load(new URLRequest("./img/buggy.png")); } public function initialiseGame():void { // buggy is at groundLevel buggyLoader.y = 375; // The buggy stays in the centre buggyLoader.x = (width / 2) - (buggyLoader.content.width / 2); // We want to update every frame so we add a listener for ENTER_FRAME events addEventListener(Event.ENTER_FRAME, drawGame); // Check for a mouse click addEventListener(MouseEvent.CLICK, clickCallback); // Add the background, middleground, foreground and buggy objects to the display list addChild(backgroundLoader); addChild(middlegroundLoader); addChild(foregroundLoader); addChild(buggyLoader); // These variables are for making the buggy jump up in the air verticalSpeed = 0; // this is the rate at which the buggy is moving upwards (in pixels per frame) groundLevel = 375; // this is the y-value of the ground level } public function drawGame(event:Event):void { // Move the background, middleground and foreground at different rates backgroundLoader.x = backgroundLoader.x - 1; middlegroundLoader.x = middlegroundLoader.x - 2; foregroundLoader.x = foregroundLoader.x - 4; // This makes the the buggy move up and down according to it's vertical speed if (buggyLoader.y > groundLevel) { buggyLoader.y = groundLevel; verticalSpeed = 0; } buggyLoader.y = buggyLoader.y - verticalSpeed; verticalSpeed = verticalSpeed - 1; } // This gets called when the mouse is clicked public function clickCallback(event:MouseEvent):void { buggyLoader.y = groundLevel - 1; verticalSpeed = 20; } } }