Skip to content

Add game loop and simple skeleton #1

@tobyjsullivan

Description

@tobyjsullivan

After reading that one blog post on the Entity-Component-System pattern, I came up with the following pseudocode for how I imagine a game loop would look. It's imperative/go-style. Maybe somebody could oxidise it and get it in as a jumping-off point.

I decided to share here since I won't have a laptop this weekend and won't be able to do it myself.

Note: This is not at all fp-appropriate. I imagine you'd have to turn it on its head to get it to be good rust. A challenge left for the reader.

// An entity represents each unique object in the world.
// Entities themselves do not maintain any state.
struct Entity {
    id int
}

// Components track the current state of their particular attributes.
struct Transform {
    x int
    y int
}

struct Motion {
    accelerationX int
    accelerationY int
    velocityX int
    velocityY int
}

// ComponentManagers maintain a mapping 
struct TransformCM {
    map[Entity]Transform entities
}

struct MotionCM {
    map[Entity]Motion entities
}

// Systems perform the heavy lifting on each tick.
interface System {
    tick()
}

// The necessary component managers are injected into each system at initialization.
// 
struct MovementSystem {
    cmTransform TransformCM
    cmMotion MotionCM
}

func (sys MovementSystem) tick() {
    for entity, motion := range sys.cmMotion.entities {
        transform := sys.cmTransform.entities[entity]
        transform.x += motion.velocityX
        transform.y += motion.velocityY
        motion.velocityX += motion.accelerationX
        motion.velocityY += motion.accelerationY
    }
}

func main() {
    cmTransform := TransformCM{
        entities: make(map[Entity]Transform)
    }

    cmMotion := MotionCM{
        entities: make(map[Entity]Motion)
    }

    systems := []System{
        MovementSystem{
            cmTransform,
            cmMotion
        }
    }

    // Game loop
    for {
        for _, system := range systems {
            system.tick()
        }
    }
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions