Pen Settings

HTML

CSS

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

JavaScript

Babel is required to process package imports. If you need a different preprocessor remove all packages first.

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

Behavior

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.

Format on Save

If enabled, your code will be formatted when you actively save your Pen. Note: your code becomes un-folded during formatting.

Editor Settings

Code Indentation

Want to change your Syntax Highlighting theme, Fonts and more?

Visit your global Editor Settings.

HTML

              
                
              
            
!

CSS

              
                
              
            
!

JS

              
                const scaling = "fit"; // this will resize to fit inside the screen dimensions
const width = 1024;
const height = 768;
const color = blue.lighten(.4);
const outerColor = darker;

const frame = new Frame(scaling, width, height, color, outerColor);
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
	const stage = frame.stage;
	const stageW = frame.width;
	const stageH = frame.height;

	// REFERENCES for ZIM at https://zimjs.com
	// see https://zimjs.com/intro.html for an intro example
	// see https://zimjs.com/learn.html for video and code tutorials
	// see https://zimjs.com/docs.html for documentation
	// see https://codepen.io/topic/zim/ for ZIM on CodePen

	// CODE HERE

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// CREATE THE BOARD

	// isometric Board from game module - or can be just flat top view
	const board = new Board({
		size:28,
		cols:14,
		rows:14,
		backgroundColor:grey,
		borderColor:dark
	}).center();

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// ADDING PEOPLE ON MOUSE DOWN AND DRAG

	// create people on mousedown and drag
	board.on("mousedown", (e) => {

		// only add people before pressing play or if paused
		if (play.text != "PLAY" && !pause.checked) return;

		// we also call makePerson() from restart where there is no currentTile
		// so send in col and row information from currentTile
		makePerson(board.currentTile.boardCol, board.currentTile.boardRow);

		// we want to make people as we drag as well
		// the board dispatches a change event when we rollover different tiles
		let dragEvent = board.on("change", ()=>{
			if (!board.currentTile) return; // mouse could be outside board
			makePerson(board.currentTile.boardCol, board.currentTile.boardRow);
		});

		// remove the change event when we pressup
		board.on("pressup", ()=>{
			board.off("change", dragEvent);
		}, null, true); // remove this event after it is run once
		// this type of event work has been around since CD ROMs in Director
	})

	function makePerson(col, row) {

		// if there is an item then remove it otherwise add one
		// the board can handle multiple items on a tile
		// so the method is called getItems and it will return an array
		// the array [0] will have something in it if there is an item
		let item = board.getItems(col, row)[0];
		if (item) {
			board.remove(item);
		} else {
			board.add(new Person().sca(.8), col, row);
		}
		// adjust the tally of how many elements are on the board
		// we use a game module Scorer() to keep track of these
		// it has a score property - same for the generations later
		// board.pieces is the container that holds the pieces
		// so this is one way we can get how many elements there are
		elements.score = board.pieces.numChildren;
		stage.update();
	}


	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// TOP INTERFACE

	new Label("GaMe of LiFe").alp(.6).pos(-10,30,CENTER); // -10 from center and 30 from top

	// used .place() to loc() these - also put to .bot() so trees go over text boxes
	// passing in LEFT or RIGHT will turn these isometric
	const elements = new Scorer(0, LEFT, null, null, white, orange).loc(189, 169).bot();
	new Label("elements  ").sca(.5).alp(.6).pos(0,-30,CENTER,TOP,elements);

	const generations = new Scorer(0, RIGHT, null, null, white, yellow).loc(961, 235).bot();
	new Label("  generations").sca(.5).alp(.6).pos(0,-30,CENTER,TOP,generations);


	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// MAIN GAME OF LIFE LOGIC

	// we just had the board and the ACTUAL LOGIC below in an interval to start
	// we added some start objects and it worked
	// so the bulk of this app is the interface

	// this gets called from an interval run by the play button
	// interval passes in an interval obj that holds the interval count and other things
	function playGame(obj) {
		generations.score = obj.count;

		// this count is used to trigger a timeout time to animate game changes
		let count = 0;

		// loop through the board data rows and cols
		loop(board.data, (rows, j)=>{
			loop(rows, (cols, i)=>{

				// this item will either be undefined or an object
				let item = board.getItems(i,j)[0]; // there can be multiple items on a tile
				let around = board.getTilesAround(i,j);  // gets an array of tiles around item
				let numItems = 0;
				loop(around, tile=>{
					// if on edge, the tile around may be off the edge - undefined
					// increase the numItems if there is an item in the tile's items array
					if (tile && board.getItems(tile).length > 0) numItems++;
				});
				// animate the change
				// the count increases for each square and there are board.num squares
				// so we want to divide the total time based on the speed slider
				// by the total number of squares - this gets the average time per square
				// and then we multiply that by which square we are on (count)
				// This creates a wave effect as we update the board (totally optional!)
				count++;

				// ACTUAL LOGIC
				// here are the game rules being applied
				if (item) { // alive
					if (numItems < 2 || numItems > 3) { // too few or too many
						timeout(speed.currentValue/board.num*count, () => {
							if (play.text == "PLAY" || pause.checked) return; // have stopped game
							board.remove(item);
							elements.score = board.pieces.numChildren;
							stage.update();
						});
					}
				} else { // not alive
					if (numItems == 3) { // creation!
						timeout(speed.currentValue/board.num*count, () => {
							if (play.text == "PLAY" || pause.checked) return; // have stopped game
							// ternary operator: boolean ? if true : if false ;
							// spread across three lines with internal ternary operator
							// deciding which item to add
							let newItem = trees.checked ?
								 rand()>.1 ? new Person().sca(.8) : new Tree().sca(.8).alp(.9)
							: new Person().sca(.8);
							board.add(newItem, i, j);
							elements.score = board.pieces.numChildren;
							stage.update();
						});
					}
				}
			}); // end col loop
		}); // end row loop

		// at the end of the life process, do we have any elements?
		if (board.pieces.numChildren == 0) {
			playInterval.clear();
			stage.update();
		}
		// could also try and test for repeat patterns - did not bother

	} // end playGame()


	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// BOTTOM INTERFACE

	// these components will be added to a Tile and placed at bottom
	// this is optional but it is easier than positioning each one

	const speed = new Slider({
		min:50,
		max:2000,
		barLength:200,
		currentValue:1000
	}).sca(.8);
	new Label("speed").sca(.7).alp(.5).pos(-5,-40,CENTER,TOP,speed);

	// we are duplicating a few components so use STYLE to simplify
	// could add the Slider styles above but there is only on Slider
	STYLE = {
		type:{
			Button:{
				backgroundColor:series(yellow,green),
				rollBackgroundColor:pink,
				corner:10,
				scale:.7
			},
			CheckBox:{
				size:35,
				alpha:.7
			}
		}
	}

	// note... cannot call variable new
	const newGame = new Button({label:"NEW"})
		.tap(()=>{
			play.toggle(false); // incase currently playing set toggle back
			if (playInterval) playInterval.clear(); // stop the play interval if running
			board.clearItems();
			elements.score = 0;
			generations.score = 0;
			speed.visible = true;
			trees.visible = true;
			pause.checked = false;
			stage.update();
		});

	let playInterval = null;
	let lastElements = []; // used to remember elements for replay
	const play = new Button({label:"PLAY", toggle:"REPLAY"})
		.tap(()=>{
			if (play.toggled) { // start playing
				generations.score = 0;
				// remember current items to use if replay
				lastElements = [];
				loop(board.getAllItems(), item=>{
					// record col and row of item
					lastElements.push({col:item.boardCol, row:item.boardRow});
				});
				
				// here is the interval that starts the game
				// firt true is start right away - last true is pause on window losing focus
				playInterval = interval(speed.currentValue, playGame, null, true, true);

				// hide the speed and the trees setting
				// with the animation timeouts it can conflict to change speed while running
				// so just hide the speed Slider
				// trees would be fine but unchecking would not actually remove trees
				// unless we went through the items and replaced trees - not worth it
				// plus, removing the trees checkbox balances the removal of the slider
				speed.visible = false;
				trees.visible = false;

			} else { // stoppin play and setting up for replay

				playInterval.clear();
				board.clearItems();
				// remake from lastElements data
				loop(lastElements, item=>{
					makePerson(item.col, item.row);
				});
				elements.score = lastElements.length;
				speed.visible = true;
				trees.visible = true;
			}

			// in all cases reset the generations and the pause
			generations.score = 0;
			pause.checked = false;
			stage.update();

		}); // end play button

	const pause = new CheckBox({label:"pause"}).change(()=>{
		if (playInterval) playInterval.pause(pause.checked);
	});
	const trees = new CheckBox({label:"trees", startChecked:true});

	// Tile the components and add to bottom
	// usually we set a spacingH
	// but here we needed the checkboxes to be closer together
	// so we set colSize using the ZIM VEE series value
	// NOTE: the clone is set to false so we keep our events
	const interface = new Tile({
		obj:series(speed, newGame, play, pause, trees),
		cols:5,
		colSize:series(200,180,165,140),
		valign:CENTER,
		clone:false
	}).pos(0, 30, CENTER, BOTTOM);

	// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
	// DEMO

	// just starting with some people to demonstrate
	makePerson(5,5);
	makePerson(6,5);
	makePerson(7,5);
	makePerson(8,5);

	makePerson(5,8);
	makePerson(6,8);
	makePerson(7,8);
	makePerson(8,8);

	// the interface controls things so need to set and reset stuff
	interface.alpha = 0;
	speed.currentValue = 400;
	trees.checked = false;
	play.toggle(true);
	playInterval = interval(()=>speed.currentValue, playGame);
	timeout(3000, ()=>{
		speed.currentValue = 1000;
		trees.checked = true;
		play.toggle(false);
		interface.animate({alpha:1});
	});
	

	stage.update(); // this is needed to show any changes

	// DOCS FOR ITEMS USED
	// https://zimjs.com/docs.html?item=Frame
	// https://zimjs.com/docs.html?item=Label
	// https://zimjs.com/docs.html?item=Button
	// https://zimjs.com/docs.html?item=CheckBox
	// https://zimjs.com/docs.html?item=Slider
	// https://zimjs.com/docs.html?item=tap
	// https://zimjs.com/docs.html?item=change
	// https://zimjs.com/docs.html?item=animate
	// 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=bot
	// https://zimjs.com/docs.html?item=alp
	// https://zimjs.com/docs.html?item=sca
	// https://zimjs.com/docs.html?item=center
	// https://zimjs.com/docs.html?item=place
	// https://zimjs.com/docs.html?item=Tile
	// https://zimjs.com/docs.html?item=rand
	// https://zimjs.com/docs.html?item=timeout
	// https://zimjs.com/docs.html?item=interval
	// https://zimjs.com/docs.html?item=lighten
	// https://zimjs.com/docs.html?item=zog
	// https://zimjs.com/docs.html?item=STYLE

	// FOOTER
	// call remote script to make ZIM icon - you will not need this
	createIcon(); 

}); // end of ready
              
            
!
999px

Console