about summary refs log tree commit diff stats
path: root/html/text-world/js/ecs.js
blob: c2c5adde5bff0486f89fb21904c695feb9c0a01d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
'use strict';

// Components remain as simple data structures
class Component {
    constructor(data = {}) {
        Object.assign(this, data);
    }
}

class Position extends Component {
    constructor(x = 0, y = 0) {
        super({ x, y });
    }
}

class Description extends Component {
    constructor(short = "", long = "", explorable = {}) {
        super({ short, long, explorable });
    }
}

class Inventory extends Component {
    constructor(items = []) {
        super({ items });
    }
}

class Messages extends Component {
    constructor(messages = []) {
        super({ messages });
    }
}

class Item extends Component {
    constructor(name, description, collectable = true) {
        super({ name, description, collectable });
    }
}

// World becomes a pure functional interface
const World = {
    create() {
        return {
            entities: new Map(),
            nextEntityId: 1
        };
    },

    createEntity(world) {
        const id = world.nextEntityId;
        const newEntities = new Map(world.entities);
        newEntities.set(id, new Map());
        
        return {
            ...world,
            entities: newEntities,
            nextEntityId: id + 1
        };
    },

    addComponent(world, entityId, component) {
        if (!world.entities.has(entityId)) return world;
        
        const newEntities = new Map(world.entities);
        const entityComponents = new Map(world.entities.get(entityId));
        entityComponents.set(component.constructor.name, component);
        newEntities.set(entityId, entityComponents);
        
        return {
            ...world,
            entities: newEntities
        };
    },

    getComponent(world, entityId, componentType) {
        if (!world.entities.has(entityId)) return null;
        return world.entities.get(entityId).get(componentType);
    },

    removeComponent(world, entityId, componentType) {
        if (!world.entities.has(entityId)) return world;
        
        const newEntities = new Map(world.entities);
        const entityComponents = new Map(world.entities.get(entityId));
        entityComponents.delete(componentType);
        newEntities.set(entityId, entityComponents);
        
        return {
            ...world,
            entities: newEntities
        };
    }
};