PhysInjector game prototype in only 100 lines of code

Read all posts about "" game

Some days ago I showed you a new Box2D library called PhysInjector, now it’s time to let you see how can you make a fully working physics game prototype in only 100 lines of code, braces and classes included.

It’s (not that) vaguely based on my BarBalance game, an old game which I sold to FOG.

In this prototype, which would need to be a bit optimized but I wanted to keep it with only 100 lines of code, you have to create boxes by clicking with mouse button above the black line. Boxes will fall on the balance at the bottom of the screen, which color represents the next box you are about to create.

When two boxes of the same color collide, they become a bit transparent, and when a box turns completely transparent, it disappears. If a box falls down the balance, you lose a life. Lose al lives and it’s game over.

Give it a go:

Although the game is made by only 100 lines, it features:

* Static bodies
* Dynamic bodies
* Sensors
* Revolute joints
* Motors
* Collision detection
* Score
* Lives
* 8 different box colors
* Increasing difficulty

All these features in just a few lines are possible thanks to PhysInjector which allowed me to add Box2D physics in a snap.

This is the source code.

package {
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.text.TextField;
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.Joints.b2RevoluteJoint;
	import Box2D.Dynamics.Contacts.b2Contact;
	import com.reyco1.physinjector.PhysInjector;
	import com.reyco1.physinjector.data.PhysicsObject;
	import com.reyco1.physinjector.data.PhysicsProperties;
	import com.reyco1.physinjector.factory.JointFactory;
	import com.reyco1.physinjector.contact.ContactManager;
	public class Main extends Sprite {
		private var physics:PhysInjector=new PhysInjector(stage,new b2Vec2(0,10),true);
		private var joint:b2RevoluteJoint;
		private var floor:Sprite= new Sprite();
		private var colorArray:Array=[0xff0000,0x00ff00,0x0000ff,0xffff00,0xff00ff,0x00ffff,0x000000,0xffffff];
		private var boxColor:Number=Math.floor(Math.random()*colorArray.length);
		private var lives:Number=3;
		private var score:Number=0;
		private var scoreText:TextField = new TextField();
		public function Main() {
			graphics.lineStyle(2,0x000000)
			graphics.moveTo(0,100);
			graphics.lineTo(640,100);
			addChild(scoreText);
			floor.x=50;
			floor.y=420;
			addChild(floor);
			fillFloor();
			var box2dFloor:PhysicsObject=physics.injectPhysics(floor,PhysInjector.SQUARE,new PhysicsProperties({isDynamic:true,friction:0.2,restitution:0,density:10,isDraggable:false,contactGroup:"bar"}));
			joint=JointFactory.createRevoluteJoint(PhysInjector.WORLD.GetGroundBody(),box2dFloor.body,box2dFloor.getDisplayObjectCenterPoint(),false,false,0,360);
			joint.EnableMotor(true);
			var sensor:Sprite=new Sprite();
			sensor.graphics.beginFill(0x000000);
			sensor.graphics.drawRect(0,0,1280,20);
			sensor.graphics.endFill();
			addChild(sensor);
			sensor.x=-320;
			sensor.y=500;
			var box2dSensor:PhysicsObject=physics.injectPhysics(sensor,PhysInjector.SQUARE,new PhysicsProperties({isDynamic:false,isDraggable:false,contactGroup:"sensor",isSensor:true}));
			addEventListener(Event.ENTER_FRAME,update);
			stage.addEventListener(MouseEvent.CLICK,addBox);
			ContactManager.onContactBegin("crate", "crate", crateVsCrate,true);
			ContactManager.onContactBegin("crate", "sensor", crateVsSensor,true);
		}
		private function fillFloor():void {
			floor.graphics.clear();
			floor.graphics.beginFill(colorArray[boxColor]);
			floor.graphics.drawRect(0,0,540,20);
			floor.graphics.endFill();
		}
		private function addBox(e:MouseEvent):void {
			if (mouseY<100) {
				var box:Sprite = new Sprite();
				box.graphics.beginFill(colorArray[boxColor]);
				box.graphics.drawRect(0,0,50,50);
				box.graphics.endFill();
				box.x=mouseX-25;
				box.y=mouseY-25;
				addChild(box);
				var box2dBox:PhysicsObject=physics.injectPhysics(box,PhysInjector.SQUARE,new PhysicsProperties({isDynamic:true,friction:0.2,restitution:0,density:1+score/100,isDraggable:false,contactGroup:"crate",name:boxColor}));
				boxColor=Math.floor(Math.random()*colorArray.length);
				fillFloor();
			}
		}
		private function crateVsCrate(objectA:PhysicsObject,objectB:PhysicsObject,contact:b2Contact):void {
			if (objectA.name==objectB.name) {
				score++;
				processCollision(objectA.displayObject);
				processCollision(objectB.displayObject);
			}
			scoreText.text=score.toString()+" - "+lives.toString()+" lives";
		}
		private function processCollision(s:Sprite):void {
			s.alpha-=0.25;
			if (s.alpha<=0) {
				physics.removePhysics(s);
				removeChild(s);
				score+=5;
			}
		}
		private function crateVsSensor(objectA:PhysicsObject,objectB:PhysicsObject,contact:b2Contact):void {
			physics.removePhysics(objectA.displayObject);
			removeChild(objectA.displayObject);
			lives--;
			scoreText.text=score.toString()+" - "+lives.toString()+" lives";
			if (lives==0) {
				removeEventListener(Event.ENTER_FRAME,update);
				stage.removeEventListener(MouseEvent.CLICK,addBox);
			}
		}
		private function update(event:Event):void {
			physics.update();
			joint.SetMotorSpeed(-floor.rotation/2);
			joint.SetMaxMotorTorque(Math.abs(floor.rotation)*50);
		}
	}
}

During next days, I will show you how to create the same thing using the standard Box2D library, and we’ll then count the lines.

Download the source code of the entire project. What’s your best score?

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

214 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
// 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