Create a Flash game like Space is Key with a lot of room for customization

Read all posts about "" game

Did you ever play Space is Key by Christopher Jeffrey and its sequels?

It’s a quick one button game which can be used to learn some programming basics, so I am showing you this little prototype which allows a lot of customization such as player speed, jump height, jump rotation, number of floors and some minor features.

I am not using any physics engine because there’s no need in a game like this one, so let me show you the fully commented source code:

package {
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	public class Main extends Sprite {
		// the square!! the hero of the game
		private var theSquare:TheSquare;
		// square's horizontal speed in pixels/frame
		private var xSpeed:Number=4;
		// square's jump height, in pixels
		private var jumpHeight:Number=40;
		// square's jump width, in pixels. xSpeed must divide jumpWidth
		private var jumpWidth:Number=120;
		// rotation performed at every jump, in degrees
		private var jumpRotation:Number=180;
		// time passed since the player started jumping, in frames
		private var jumpTime:Number=0;
		// is the player jumping?
		private var isJumping:Boolean;
		// simple degrees to radians conversion
		private var degToRad:Number=0.0174532925;
		// array containing all various floor y positions, in pixels
		private var floorY:Array=[92,184,276,368,460];
		// floor I am currently moving on
		private var currentFloor:Number;
		// floor height, in pixels
		private var floorHeight:Number=20;
		// x position where the level starts, in pixels
		private var levelStart:Number=0;
		// x position where the level ends, in pixels
		private var levelEnd:Number=640;
		public function Main() {
			drawBG();
			init();
		}
		private function drawBG():void {
			// simply drawing all floors, as rectangles from levelStart to levelEnd, height floorHeight
			var floorCanvas:Sprite=new Sprite();
			addChild(floorCanvas);
			for (var i:Number=0; i<floorY.length; i++) {
				floorCanvas.graphics.lineStyle(1,0x440044);
				floorCanvas.graphics.beginFill(0x440044);
				floorCanvas.graphics.drawRect(levelStart,floorY[i],levelEnd-levelStart,floorHeight);
				floorCanvas.graphics.endFill();
			}
		}
		private function init():void {
			// we start on floor zero.
			currentFloor=0;
			// we aren't jumping
			isJumping=false;
			// adding and placing the square
			theSquare=new TheSquare();
			addChild(theSquare);
			theSquare.x=levelStart;
			theSquare.y=floorY[currentFloor]-theSquare.height/2;
			// event listeners to update the game and jump
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.CLICK,jump);
		}
		private function jump(e:MouseEvent):void {
			// if we aren't jumping... then JUMP!!
			if (! isJumping) {
				jumpTime=0;
				isJumping=true;
			}
		}
		private function update(e:Event):void {
			// temp variable to let us know if we are on an odd or even floor
			var mod:Number=currentFloor%2
			// updating square x position
			theSquare.x+=xSpeed*(1-2*mod);
			// if the square reached the end of the floor...
			if (theSquare.x>levelEnd&&mod==0||theSquare.x<levelStart&&mod==1) {
				// move onto next floor
				currentFloor++;
				// even or odd?
				mod=currentFloor%2
				// we start on the ground
				isJumping=false;
				theSquare.rotation=0;
				theSquare.x=levelEnd*mod+levelStart*(1-mod);
				theSquare.y=floorY[currentFloor]-theSquare.height/2;
				// if we just finished the lowest floor...
				if (currentFloor>floorY.length-1) {
					// start the game again
					removeEventListener(Event.ENTER_FRAME,update);
					stage.removeEventListener(MouseEvent.CLICK,jump);
					removeChild(theSquare);
					init();
				}
			}
			// if we are jumping...
			if (isJumping) {
				// calculating the number of frames we will be jumping
				var jumpFrames:Number=jumpWidth/xSpeed;
				// calculating how many degrees should the square rotate at each frame
				var degreesPerFrame:Number=jumpRotation/jumpFrames*(1-2*mod);
				// calculating how may radians we have to apply to sine trigonometry function to simulate player jump
				var radiansPerFrame:Number=(180/jumpFrames)*degToRad
				// anohter frame jumping...
				jumpTime++;
				// updating rotation
				theSquare.rotation+=degreesPerFrame;
				// updating y position
				theSquare.y=floorY[currentFloor]-theSquare.height/2-jumpHeight*Math.sin(radiansPerFrame*jumpTime);
				// if we jumped enough...
				if (jumpTime==jumpFrames) {
					// ... just stop jumping
					isJumping=false;
					theSquare.y=floorY[currentFloor]-theSquare.height/2;
				}
			}
		}
	}
}

As you can see, I did not use any tween or special library, so the code can be easily ported in your preferred language.

And this is the result:

Try to jump with the mouse (yeah, no space here). No obstacles at the moment, I will introduce them in next step. If you are a fan of Space is Key series, you will notice I also fixed the jumping rotation when moving from right to left.

Edit: Got a mail from Chris, he told me « Also wanted to address the left/right jump that you ‘fixed’. It was actually designed and intended that way to do doing the ‘backflip’ instead of the ‘frontflip’ on some levels throws the player off and adds to the difficulty. »

Download the 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