Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              
// Playing around with this pen https://codepen.io/borntofrappe/pen/BaBeNoV
// was going to compare P5js with ZIM but then got carried away...
// thanks Gabriele for the initial layout

	
const frame = new Frame({scaling:"fit", width:1024, height:600, color:yellow, outerColor:darker, allowDefault:true});
frame.on("ready", ()=>{ // ES6 Arrow Function - similar to function(){}
    zog("ready from ZIM Frame"); // logs in console (F12 - choose console)

    // often need below - so consider it part of the template
    let stage = frame.stage;
    let stageW = frame.width;
    let stageH = frame.height;

    // REFERENCES for ZIM at http://zimjs.com
    // see http://zimjs.com/learn.html for video and code tutorials
    // see http://zimjs.com/docs.html for documentation
    // see https://www.youtube.com/watch?v=pUjHFptXspM for INTRO to ZIM
    // see https://www.youtube.com/watch?v=v7OT0YrDWiY for INTRO to CODE

    // CODE HERE
			
		// normally would load assets in Frame call 
		// but on CodePen previews... we want to see something 
		// so get the stage and show intro drone - then call loadAssets()
		const introDrone = new Rectangle(60, 40, darker, null, null, [60, 60, 30, 30])
			.reg(30, -150)
			.sca(5)
			.center();		
		introDrone
			.wiggle("rotation", 0, 2, 4, 1500, 2000)
			.wiggle("y", introDrone.y, 10, 30, 2000, 4000);	
		stage.update();
	
		const assets = [
			"drone1.mp3",
			"drone2.mp3",
			"drone3.mp3",
			"explosion.mp3",
			"projectile.mp3",
			{src:"https://fonts.googleapis.com/css?family=Saira+Stencil+One"}
		]
		const path = "https://s3-us-west-2.amazonaws.com/s.cdpn.io/1604712/";
		const waiter = new Waiter({backgroundColor:yellow, corner:0}).show().mov(0,-170);
	
		frame.loadAssets(assets, path); // show loading at least 2 seconds
		frame.on("complete", ()=>{	
			waiter.removeFrom();
			introDrone.stopAnimate()
			introDrone.removeFrom();	

			// GAME CONFIG CONSTANTS	
			const minTime = 1000;
			const maxTime = 4000;
			const maxTargets = 5;
			const bulletTime = 1000;
			const totalTime = 60;
			const goodScore = 500;
			const scorePlus = 1; // added in Ticker when there is silence (no drones)
			const scoreMinus = 1; // removed in Ticker when there are maxTarget drones
			const shootCost = 5;
			const tankColor = darker;

			// CLASSES FOR TANK, PROJECTILE AND TARGET	
			class Tank extends Container {
				constructor(color=darker) {
					// CreateJS needs super constructor called
					// could also put dimensions here - see ZIM Container
					super(); 
					this._color = color;
					new Rectangle(120,25, color).addTo(this);
					new Rectangle(100,25, color).center(this).mov(0,-8);
					new Rectangle(20, 25, color).center(this).mov(0,-20);
					new Rectangle(10, 25, color).center(this).mov(0,-20);
				}			
				shoot(projectile) {	// METHOD
						frame.asset("projectile.mp3").play({pan:getPan(tank)});
						projectile
								.loc(this.x, this.y-50, projectiles) // add to projectiles
								.animate({
									props:{y:-20},
									ease:"linear",
									time:bulletTime,
									call:target=>{target.removeFrom();}
								});			
				}
				set color(c) { // GETTER SETTER FOR COLOR
					this._color = c;
					this.loop(part=>{part.color = c;});
				}
				get color() {return this._color;}
			}

			class Projectile extends Rectangle {
				constructor(w=8, h=16, color=darker) {
					// no border and corner round on top
					super(w, h, color, null, null, [w/2,w/2,0, 0]); 
				}
			}

			class Target extends Rectangle {
				constructor(w=60, h=40, color=darker) {
					// make it look like a copter
					super(w,h,color,null,null,[w,w,w/2,w/2]); 
					this.centerReg({add:false});				
				}
			}

			// CREATE GAME ASSETS

			const floor = new Rectangle(stageW, 8, darker).pos(0, 20, null, true);

			const tank = new Tank(tankColor)
				.sca(.8)
				.centerReg() // easier to fire from and to set boundary below
				.pos(50, 35, null, true); // null for default left and true for from bottom

			var boundary = new Boundary(0, tank.y, stageW, 0);
			if (mobile()) {
				const backing = new Rectangle(stageW, stageH, frame.color).addTo(stage, 0);
				backing.on("mousedown", e=>{				
					smoke.spurt(10);
					tank.shoot(new Projectile());				
				});
				const mobileSpeed = 10;
				const mc = new MotionController({
					target:tank, 
					type:"custom", 
					axis:"horizontal",
					boundary:boundary,
					damp:.5
				});
				const tabs = new Tabs({
					width:200,
					height:90,
					tabs:["<",">"],
					spacing:10,
					currentEnabled:true,
					currentSelected:false
				}).pos(10,120,null,true).alp(.5);
				let right = 0;
				let left = 0;
				tabs.on("mousedown", e=>{
					if (e.target.text == ">") right = 1;
					else left = 1;
				});
				tabs.on("pressup", e=>{
					if (e.target.text == ">") right = 0;
					else left = 0;
				});
				Ticker.add(()=>{
					mc.x+=(right-left)*mobileSpeed;
				});
			} else { // not mobile
				new MotionController({
					target:tank, 
					type:"keydown", 
					axis:"horizontal",
					boundary:boundary,
					damp:.1
				});
			}		

			const smoke = new Emitter({
				obj:new Circle(8),
				angle:{min:-130, max:-50},
				num:3, // 3 particles sent each interval
				life:600,			
				decayTime:600,
				startPaused:true,
				gravity:1,
				force:1.5
			}).center(tank).mov(0,-25);

			// SHOOTING 
			shootCheck = true; // to avoid spacebar being held down
			frame.on("keydown", e=>{
				zog("here")
				if (!shootCheck || !playCheck) return;
				if (e.keyCode == 32 || e.keyCode == 38) { // spacebar or up				
					shootCheck = false;
					smoke.spurt(10);
					tank.shoot(new Projectile());
					scorer.score -= shootCost;
					if (scorer.score < 0) scorer.score = 0;
				}
			});		
			frame.on("keyup", e=>{
				shootCheck = true;
			});

			// containers to hold targets and projectiles 
			// this lets us loop through and test for hits
			const targets = new Container(stageW, stageH).addTo(); 
			const projectiles = new Container(stageW, stageH).addTo(); 

			// MAKE TARGETS
			const inter = interval({min:minTime, max:maxTime}, ()=>{
				if (targets.numChildren < maxTargets) {
					let target = new Target()
						.centerReg(targets)
						.loc(rand(stageW), rand(150, 250))
						.sca(0)
						.animate({
								// animate in targets and then start them swaying
								// by setting their registration points high and wiggling rotation
								props:{scale:rand(1,1.5)}, 
								time:rand(1000,2000),
								call:target=>{
									target.reg(null,-rand(100,400),true);
									target.wiggle("rotation", 0, 2, 4, 1500, 2000);
									target.wiggle("y", target.y, 10, 30, 2000, 4000);
								}
						});
					target.sound = frame.asset("drone"+rand(1,3)+".mp3").play({loop:true, pan:getPan(target)});
					stage.update();
				}
			});

			// panning sounds really helps a game like this 
			// we can almost play this game with our eyes closed
			function getPan(obj) {
				return (obj.x-stageW/2)/(stageW/2);
			}

			const explosion = new Emitter({
				obj:new Circle({min:20, max:40}, darker).alp(1),
				num:5, // 5 particles sent each interval
				interval:30,
				life:500,
				decayTime:500,
				gravity:6,
				force:3,
				startPaused:true
			});

			// TIMER AND SCORE
			const timer = new Timer({time:totalTime, backgroundColor:orange}).sca(.8).alp(.8).pos(20, 20);
			timer.on("complete", endGame);
			const scorer = new Scorer({backgroundColor:pink}).sca(.8).alp(.8).pos(20, 20, true); // at right

			// CONSTANT TEST FOR HITS
			Ticker.add(()=>{
					if (!playCheck) return;
					targets.loop(target=>{
							projectiles.loop(projectile=>{
								if (target.hitTestRect(projectile)) {
									frame.asset("explosion.mp3").play({pan:getPan(target)});
									target.sound.stop();
									explosion.loc(projectile).spurt(30);
									projectile.removeFrom();
									target.stopAnimate();
									target.removeFrom();								
									stage.update();
								}									
							}, true);
					}, true);			
					if (targets.numChildren == 0) {
						if (tank.color != purple) tank.color = purple;
						scorer.score += scorePlus;
						if (scorer.score < 0) scorer.score = 0;
					} else if (targets.numChildren == maxTargets) {
						if (tank.color != red) tank.color = red;		
						scorer.score -= scoreMinus;
						if (scorer.score < 0) scorer.score = 0;
					} else {
						if (tank.color != tankColor) tank.color = tankColor;
					}					
			});

			// STARTING AND STOPPING
			// handle starting and stopping game
			// built the working game first 
			// then paused all the parts to start or when done 
			// show a message and then unpause when message closes

			let playCheck = false;
			pauseGame();

			const intro = new Pane({
				width:750,
				height:80,
				corner:0,
				backgroundColor:yellow,
				label:"Must silence that droning!"
			}).show();
			intro.on("close", startGame);

			const end = new Pane({
				width:750,
				height:80,
				corner:0,
				backgroundColor:yellow,
				label:""
			});
			end.on("close", startGame);

			function startGame() { // works for both start and restart
				pauseAnimate(false);
				targets.removeAllChildren();
				inter.pause(false, null, true); // true is start the interval at its start when unpaused
				playCheck = true;
				timer.start(totalTime);
				scorer.score = 0;
			};	

			function pauseGame() {
				pauseAnimate();
				inter.pause();
				timer.pause();
				createjs.Sound.stop();
				projectiles.removeAllChildren();
				playCheck = false;
			}

			function endGame() {	
				pauseGame();
				end.text = "Your score is " + scorer.score + (scorer.score > goodScore ? ".  Whew!" : ". Sigh.");			
				end.show();
			}

			// TITLE
			new Label({
				text:"P E A C E",
				font:"Saira Stencil One",
				color:purple,
				size:40,
				backgroundColor:blue,
				paddingVertical:3,
				paddingHorizontal:50,
			})	
				.center()
				.pos(null, 20)
				.alp(0)
				.animate({alpha:.8}, 1000)

			stage.update(); // this is needed to show any changes
			
  	}, null, true); // end of asset load (strange on codepen is being called twice so run it only once - true)
	
    // DOCS FOR ITEMS USED
		// https://zimjs.com/docs.html?item=Frame
		// https://zimjs.com/docs.html?item=Container
		// https://zimjs.com/docs.html?item=Circle
		// https://zimjs.com/docs.html?item=Rectangle
		// https://zimjs.com/docs.html?item=Label
		// https://zimjs.com/docs.html?item=Pane
		// https://zimjs.com/docs.html?item=Tabs
		// https://zimjs.com/docs.html?item=hitTestRect
		// https://zimjs.com/docs.html?item=animate
		// https://zimjs.com/docs.html?item=stopAnimate
		// https://zimjs.com/docs.html?item=pauseAnimate
		// https://zimjs.com/docs.html?item=wiggle
		// https://zimjs.com/docs.html?item=loop
		// https://zimjs.com/docs.html?item=pos
		// https://zimjs.com/docs.html?item=loc
		// https://zimjs.com/docs.html?item=mov
		// https://zimjs.com/docs.html?item=alp
		// https://zimjs.com/docs.html?item=reg
		// https://zimjs.com/docs.html?item=sca
		// https://zimjs.com/docs.html?item=addTo
		// https://zimjs.com/docs.html?item=removeFrom
		// https://zimjs.com/docs.html?item=centerReg
		// https://zimjs.com/docs.html?item=center
		// https://zimjs.com/docs.html?item=MotionController
		// https://zimjs.com/docs.html?item=Emitter
		// https://zimjs.com/docs.html?item=rand
		// https://zimjs.com/docs.html?item=interval
		// https://zimjs.com/docs.html?item=Boundary
		// https://zimjs.com/docs.html?item=zog
		// https://zimjs.com/docs.html?item=Ticker
  
    // FOOTER
    // call remote script to make ZIM Foundation for Creative Coding icon
    createIcon(null, 50); 

}); // end of ready
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.

Console