ECS

Entity Component System

by onejdc

HTML

<canvas id='game'>

</canvas>

CSS

#game {position:absolute;background-color:rgba(235,235,235,1);}
.character {
  position:absolute;
  float:left;
}

JavaScript

/* Small helper function from https://stackoverflow.com/questions/105034/how-do-i-create-a-guid-uuid
*/
function getUUID() {
  return ([1e7]+-1e3+-4e3+-8e3+-1e11).replace(/[018]/g, 
  c => (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
                                             );
}

/**********************************************************
 * How to use:
 *
 * - Entities are the things in your world
 * - They are made up of Components (data)
 * - Systems then work with the entities that have the
 *   necessary components to make things happen
 * - The World owns it all and is used for implementation
 **********************************************************/
class World {

}
class Entity {
	constructor() {
  	this.id = getUUID;
  }
  
  /**
   * My original thought was to register components using their tag. While
   * that is still an option, it may be better to register using the entire
   * component instance. e.g.
   *		let n = new Entity(new Component()) */
   
  registerComponent(componentInstance) {
  	if (Object.getPrototypeOf(componentInstance.constructor) === Component) {
    
    } else {
    	// throw an error because this isn't a valid component
    }
  }
  registerComponentByTag(tag){}
  unregisterComponent(tag){}
  
  // each component has a tag
  hasComponent(tag){
  	return true;
  }
  
  hasAllComponents(tags) {}
  hasSomeComonents(tags) {}
  
  // other options
  affectedBy(){} // boolean to see if Entity is affected by a particular system
  
  
  
  // attach any systems that 
  attachSystem(){}
  detachSystem(){}
}

class Component {

	get fields() {
  	return this._fields;
  }
  set fields(field) {
  	this._fields = field;
  }

	constuctor(name, tag) {
  	this.name = name;
    this.tag = tag;
  }
  
}

class System {}

/********************* Implementation *********************/

// create a new world

// create new entities
	// could be a class or just an object
  
  const player = {
  	position: {x: 20,...