Create a Flash racing game – Flex version

Read all posts about "" game

Hamilton Lombardi is a brazilian Flex programmer who decided to rewrite the code you can find in the original post for Flex 4.

Moreover he added a splash screen, as you can see:

The source code is clearly formatted and commented as you can see from Level class:

package
{
	import flash.geom.*;
	import flash.media.*;
	import flash.net.*;
	import flash.utils.*;
	
	import mx.containers.Canvas;
	import mx.controls.Alert;
	import mx.controls.Label;
	import mx.controls.Text;
	import mx.core.*;
	
	public class Level
	{
		protected static var instance:Level = null;	
		public static var player:Player = null;
		public static var track:Track = null;
		
		//this is the max number of laps
		public const totalLaps:Number = 3;
		
		// Moment the race started
		public var initialTime:Date;
		// Current lap time
		public var lapTime:Date;
		// Current fastest lap
		public var bestLap:Number = 0;
		// Current lap number
		public var currentLap:int = 0;
		// Current checkpoint - 1 Start Line , 2 - Mid track
		public var currentCheckpoint:int = 1;
		// History of all the lap times
		public var raceHistory:String;

		static public function get Instance():Level
		{
			if ( instance == null )
				instance = new Level();
			return instance;
		}
		
		public function Level(caller:Function = null )
		{
			if ( Level.instance != null )
			throw new Error( "Only one Singleton instance should be instantiated" );
		}
		
		public function startup():void
		{
			// Start all clock timers
			startupTimeClocks();
			
			// Start time display
			startupTimeDisplay();
			
			// Creates the race track
			track = new Track();
			track.startupTrack();	
			
			// Creates the racer
			player = new Player();
			player.startupPlayer();			
		}
		
		public function shutdown():void
		{			
		}
		
		public function enterFrame():void
		{
			// Check if the lap had been completed
			checkPoints();
			
			// Update total race time display
			setTimes();				
		}
		
		public function setTimes():void {
			
			var timeElapsed:Number = 0;
			var milliseconds:Number = 0;
			var seconds:Number = 0;
			var minutes:Number = 0;
			
			var minutesTXT:Number = 0;
			var secondsTXT:Number = 0;
			var tensTXT:Number = 0;
			
			var totalTXT:String;
			
			var totalTimeLabel:Label;
			var timeCanvas:Canvas;
			
			// Only starts the timer if the car cross the start line for the first time
			if (this.currentLap != 0) {
				//we calculate the time elapsed from the moment the race started in millisecond
				var thisTime:Date = new Date();
				timeElapsed = (thisTime.getTime() - initialTime.getTime());
				
				//we calculate the minutes, seconds and tens of seconds and set them to their respective variables
				milliseconds = timeElapsed;
				seconds = Math.floor(milliseconds/1000);
				minutes = Math.floor(seconds/60);
				minutesTXT = minutes;
				secondsTXT = seconds-minutes*60;
				tensTXT = Math.round((milliseconds-seconds*1000)/10);
				//if the minutes, seconds or the tens of seconds number has only one character we add a "0" before it - that's just because we want the time to look good ;)
				if (minutesTXT<10) totalTXT = "0" + minutesTXT;
				else totalTXT = "" + minutesTXT;
				
				if (secondsTXT<10) totalTXT = totalTXT + "." + "0" + secondsTXT;
				else totalTXT = totalTXT + "." + secondsTXT;
				
				if (tensTXT<10) totalTXT = totalTXT + "." + "0" + tensTXT;
				else totalTXT = totalTXT + "." + tensTXT;
				
				//Update total time label 
				timeCanvas = FlexGlobals.topLevelApplication.timeDisplay;
				totalTimeLabel = (Label) (timeCanvas.getChildByName("totalTimeTXT"));			
				totalTimeLabel.text = totalTXT;
			}
		}
		
		//and the second function
		public function setBestLap():void {
			
			//this function does the exact same thing as the first one, only here we will use the time elapsed from the last time the car has passed the finish line
			var currentTime: Date = new Date();
			var currentLap:Number = 0;
			currentLap = currentTime.getTime()- this.lapTime.getTime();
			
			var seconds:Number = 0;
			var minutes:Number = 0;			
			var minutesTXT:Number = 0;
			var secondsTXT:Number = 0;
			var tensTXT:Number = 0;			
			var bestLapTXT:String;
			var bestLapLabel:Label;
			var timeCanvas:Canvas;			
			
			seconds = Math.floor(currentLap/1000);
			minutes = Math.floor(seconds/60);
			minutesTXT = minutes;
			secondsTXT = seconds-minutes*60;
			tensTXT = Math.round((currentLap-seconds*1000)/10);
			//if the minutes, seconds or the tens of seconds number has only one character we add a "0" before it - that's just because we want the time to look good ;)
			if (minutesTXT<10) bestLapTXT = "0" + minutesTXT;
			else bestLapTXT = "" + minutesTXT;
			
			if (secondsTXT<10) bestLapTXT = bestLapTXT + "." + "0" + secondsTXT;
			else bestLapTXT = bestLapTXT + "." + secondsTXT;
			
			if (tensTXT<10) bestLapTXT = bestLapTXT + "." + "0" + tensTXT;
			else bestLapTXT = bestLapTXT + "." + tensTXT;
			
			//we don't calculate the lap time if the car passes the finish/start line for the first time
			if ( (this.bestLap>currentLap) || (this.bestLap == 0) ) {
				
				this.bestLap = currentLap;
				//Update best lap time label 
				timeCanvas = FlexGlobals.topLevelApplication.timeDisplay;
				bestLapLabel = (Label) (timeCanvas.getChildByName("bestLapTXT"));			
				bestLapLabel.text = bestLapTXT;
			}
			
			// Save race history
			if (this.raceHistory == null) this.raceHistory = "Lap: " + this.currentLap + " - " + bestLapTXT + "\n";
			else this.raceHistory = this.raceHistory  + "Lap: " + this.currentLap + " - " + bestLapTXT + "\n"; 
			
			//we set the initial time to the moment the car passed the finish line 
			this.lapTime = new Date();
		}
		
		public function checkPoints():void 
		{
			var currentLapTXT:String;
			var currentLapLabel:Label;
			var timeCanvas:Canvas;
			var levelEndCanvas:Canvas;
			var historyText:Text;
			
			//we check to see if the car "touches" the checkpoint1 - start/finish line)
			if (FlexGlobals.topLevelApplication.finishLine.hitTestPoint(player.position.x, player.position.y, true)) {
				// 
				if (this.currentLap == 0) {
					this.initialTime = new Date();
					this.lapTime = new Date();
					this.currentLap = 1;
				}
				//if the current checkpoint is the mid track line - increase the lap number				
				if (this.currentCheckpoint === 2) {
					//check if this is the best lap
					this.setBestLap();					
					//if this is the final lap, move to the "finish" frame 
					if (this.currentLap == totalLaps) {
						historyText = new Text();
						historyText.text = this.raceHistory;
						historyText.x = 10; historyText.y = 115;	
						FlexGlobals.topLevelApplication.currentState = "LevelEnd";
						FlexGlobals.topLevelApplication.levelEndCanvas.addChild(historyText);
						
					} else {
						//if the current checkpoint is the start line - increase the lap number					
						this.currentLap++;
					}					
					currentLapTXT = this.currentLap + "/" + totalLaps;
					
					//Update cuurent lap label 
					timeCanvas = FlexGlobals.topLevelApplication.timeDisplay;
					currentLapLabel = (Label) (timeCanvas.getChildByName("currentLapTXT"));			
					currentLapLabel.text = currentLapTXT;
					
					//we set to checkpoint to be checked to the next checkpoint 
					this.currentCheckpoint = 1;					
				}				
			}
			
			//we check to see if the car "touches" the checkpoint2 - mid track line)
			if (FlexGlobals.topLevelApplication.checkpoint.hitTestPoint(player.position.x, player.position.y, true)) {
				//if the current checkpoint is the start line - reached the mid track point				
				if (this.currentCheckpoint === 1) {					
					//we set to checkpoint to be checked is the next checkpoint 
					this.currentCheckpoint = 2;					
				}				
			}
		}
		
		public function startupTimeClocks():void 
		{			
			this.initialTime = new Date();			
			this.lapTime = new Date();
			this.bestLap = 0;
			this.currentLap = 0;
			this.currentCheckpoint = 1;			
			this.raceHistory = "";			
		}
		
		public function startupTimeDisplay():void 
		{
			
			var timeCanvas:Canvas;
			var currentLapLabel:Label;
			var bestLapLabel:Label;
			var totalTimeLabel:Label;
			
			//Update time display labels 
			timeCanvas = FlexGlobals.topLevelApplication.timeDisplay;
			currentLapLabel = (Label) (timeCanvas.getChildByName("currentLapTXT"));			
			currentLapLabel.text = (this.currentLap + 1) + "/" + totalLaps;
			bestLapLabel = (Label) (timeCanvas.getChildByName("bestLapTXT"));			
			bestLapLabel.text = "00.00.00";
			totalTimeLabel = (Label) (timeCanvas.getChildByName("totalTimeTXT"));			
			totalTimeLabel.text = "00.00.00";			
			
		}
		
	}
}

Really a nice conversion.

Download the full source code.

Get the most popular Phaser 3 book

Through 202 pages, 32 source code examples and an Android Studio project you will learn how to build cross platform HTML5 games and create a complete game along the way.

Get the book

215 GAME PROTOTYPES EXPLAINED WITH SOURCE CODE
// 1+2=3
// 100 rounds
// 10000000
// 2 Cars
// 2048
// A Blocky Christmas
// A Jumping Block
// A Life of Logic
// Angry Birds
// Angry Birds Space
// Artillery
// Astro-PANIC!
// Avoider
// Back to Square One
// Ball Game
// Ball vs Ball
// Ball: Revamped
// Balloon Invasion
// BallPusher
// Ballz
// Bar Balance
// Bejeweled
// Biggification
// Block it
// Blockage
// Bloons
// Boids
// Bombuzal
// Boom Dots
// Bouncing Ball
// Bouncing Ball 2
// Bouncy Light
// BoxHead
// Breakout
// Bricks
// Bubble Chaos
// Bubbles 2
// Card Game
// Castle Ramble
// Chronotron
// Circle Chain
// Circle Path
// Circle Race
// Circular endless runner
// Cirplosion
// CLOCKS - The Game
// Color Hit
// Color Jump
// ColorFill
// Columns
// Concentration
// Crossy Road
// Crush the Castle
// Cube Jump
// CubesOut
// Dash N Blast
// Dashy Panda
// Deflection
// Diamond Digger Saga
// Don't touch the spikes
// Dots
// Down The Mountain
// Drag and Match
// Draw Game
// Drop Wizard
// DROP'd
// Dudeski
// Dungeon Raid
// Educational Game
// Elasticity
// Endless Runner
// Erase Box
// Eskiv
// Farm Heroes Saga
// Filler
// Flappy Bird
// Fling
// Flipping Legend
// Floaty Light
// Fuse Ballz
// GearTaker
// Gem Sweeper
// Globe
// Goat Rider
// Gold Miner
// Grindstone
// GuessNext
// Helicopter
// Hero Emblems
// Hero Slide
// Hexagonal Tiles
// HookPod
// Hop Hop Hop Underwater
// Horizontal Endless Runner
// Hundreds
// Hungry Hero
// Hurry it's Christmas
// InkTd
// Iromeku
// Jet Set Willy
// Jigsaw Game
// Knife Hit
// Knightfall
// Legends of Runeterra
// Lep's World
// Line Rider
// Lumines
// Magick
// MagOrMin
// Mass Attack
// Math Game
// Maze
// Meeblings
// Memdot
// Metro Siberia Underground
// Mike Dangers
// Mikey Hooks
// Nano War
// Nodes
// o:anquan
// One Button Game
// One Tap RPG
// Ononmin
// Pacco
// Perfect Square!
// Perfectionism
// Phyballs
// Pixel Purge
// PixelField
// Planet Revenge
// Plants Vs Zombies
// Platform
// Platform game
// Plus+Plus
// Pocket Snap
// Poker
// Pool
// Pop the Lock
// Pop to Save
// Poux
// Pudi
// Pumpkin Story
// Puppet Bird
// Pyramids of Ra
// qomp
// Quick Switch
// Racing
// Radical
// Rebuild Chile
// Renju
// Rise Above
// Risky Road
// Roguelike
// Roly Poly
// Run Around
// Rush Hour
// SameGame
// SamePhysics
// Save the Totem
// Security
// Serious Scramblers
// Shrink it
// Sling
// Slingy
// Snowflakes
// Sokoban
// Space Checkers
// Space is Key
// Spellfall
// Spinny Gun
// Splitter
// Spring Ninja
// Sproing
// Stabilize!
// Stack
// Stairs
// Stick Hero
// String Avoider
// Stringy
// Sudoku
// Super Mario Bros
// Surfingers
// Survival Horror
// Talesworth Adventure
// Tetris
// The Impossible Line
// The Moops - Combos of Joy
// The Next Arrow
// Threes
// Tic Tac Toe
// Timberman
// Tiny Wings
// Tipsy Tower
// Toony
// Totem Destroyer
// Tower Defense
// Trick Shot
// Tunnelball
// Turn
// Turnellio
// TwinSpin
// vvvvvv
// Warp Shift
// Way of an Idea
// Whack a Creep
// Wheel of Fortune
// Where's my Water
// Wish Upon a Star
// Word Game
// Wordle
// Worms
// Yanga
// Yeah Bunny
// Zhed
// zNumbers