Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Created February 7, 2013 04:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warmwaffles/4728487 to your computer and use it in GitHub Desktop.
Save warmwaffles/4728487 to your computer and use it in GitHub Desktop.
My ruby prototype entity system
module Athena
class Entity
attr_reader :components
def initialize
@components = Hash.new
end
def add component
@components[component.class] = component
self
end
def remove component_class
@components.delete(component_class)
self
end
end
class Component
end
class System
attr_reader :nodes
def initialize
@nodes = Hash.new
end
def node klass
@nodes[klass] = Array.new
end
def entity_added entity
entity.components.each do |k,v|
if @nodes.key?(k)
@nodes[k] << v
end
end
end
def entity_removed entity
entity.components.each do |k,v|
if @nodes.key?(k)
@nodes[k].delete(v)
end
end
end
def update delta
true
end
end
class Engine
attr_reader :entities, :systems
def initialize
@entities = Array.new
@systems = Hash.new
end
def add_entity entity
@systems.each do |k,v|
v.entity_added(entity)
end
@entities << entity
self
end
def remove_entity entity
@systems.each do |k,v|
v.entity_removed(entity)
end
@entities.delete(entity)
self
end
def add_system system
@systems[system.class] = system
self
end
def remove_system system_class
@systems.delete(system_class)
self
end
end
end
require 'athena'
module Game
module Components
class Position < Athena::Component
attr_accessor :x, :y
def initialize x, y
@x = x
@y = y
end
end
class Motion < Athena::Component
attr_accessor :velocity, :direction
def initialize velocity, direction
@velocity = velocity
@direction = direction
end
end
end
module Systems
class Collision < Athena::System
def initialize
super
node Game::Components::Position
node Game::Components::Motion
end
end
class Movement < Athena::System
def initialize
super
node Game::Components::Position
node Game::Components::Motion
end
end
end
def self.build_player
entity = Athena::Entity.new
entity.add(Game::Components::Position.new(0,0))
entity.add(Game::Components::Motion.new(10,0))
entity
end
end
require 'game'
engine = Athena::Engine.new
engine.add_system(Game::Systems::Collision.new)
engine.add_system(Game::Systems::Movement.new)
entity = Game.build_player
engine.add_entity(entity)
puts "Done"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment