Skip to content

Instantly share code, notes, and snippets.

@IsakUlstrup

IsakUlstrup/.elm Secret

Last active April 9, 2021 10:07
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 IsakUlstrup/314e0c91e52d95279d9abcd688f76f56 to your computer and use it in GitHub Desktop.
Save IsakUlstrup/314e0c91e52d95279d9abcd688f76f56 to your computer and use it in GitHub Desktop.
ECS
module Ecs exposing
( Component
, ComponentId
, Entity
, World
, addComponent
, addEntity
, emptyWorld
, getEntityComponents
, removeComponent
, removeEntity
)
type alias World data =
{ entities : List Entity
, components : List (Component data)
, systems : List (System data)
, idCounter : Int
}
type alias Entity =
Int
type alias ComponentId =
Int
type alias Component data =
{ id : ComponentId
, parent : Entity
, enabled : Bool
, data : data
}
type alias System data =
List (Component data) -> List (Component data)
emptyWorld : World data
emptyWorld =
World [] [] [] 0
getNewId : World data -> Int
getNewId world =
world.idCounter + 1
addComponent : data -> Entity -> World data -> World data
addComponent componentData parent world =
let
id =
getNewId world
in
{ world
| components = Component id parent True componentData :: world.components
, idCounter = id
}
removeComponent : ComponentId -> World data -> World data
removeComponent componentId world =
{ world | components = List.filter (\c -> c.id /= componentId) world.components }
addEntity : World data -> World data
addEntity world =
let
id =
getNewId world
in
{ world
| entities = id :: world.entities
, idCounter = id
}
removeEntity : Entity -> World data -> World data
removeEntity entity world =
{ world
| entities = List.filter (\e -> e /= entity) world.entities
, components = List.filter (\c -> c.parent /= entity) world.components
}
getEntityComponents : Entity -> World data -> List (Component data)
getEntityComponents entity world =
world.components
|> List.filter (\c -> c.parent == entity)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment