about summary refs log tree commit diff stats
path: root/html/text-world/js/game.js
blob: 8f2d4d6d86ae33fb37845a3dfa860f14a4dddbe8 (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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
class Game {
    constructor() {
        const generated = WorldGenerator.generate();
        this.state = {
            world: generated.world,
            playerId: generated.playerId
        };
        
        this.setupUI();
        this.print("Welcome to the Text Adventure!");
        this.describeCurrentLocation();
    }

    setState(newState) {
        this.state = newState;
    }

    setupUI() {
        this.output = document.getElementById('output');
        this.input = document.getElementById('input');
        
        this.input.addEventListener('keypress', (e) => {
            if (e.key === 'Enter') {
                const command = this.input.value.toLowerCase();
                this.input.value = '';
                this.handleCommand(command);
            }
        });
    }

    print(text) {
        const line = document.createElement('div');
        line.textContent = text;
        this.output.appendChild(line);
        this.output.scrollTop = this.output.scrollHeight;
    }

    handleCommand(command) {
        this.print(`> ${command}`);

        if (command.match(/^(where am i|look around)$/)) {
            this.describeCurrentLocation();
        }
        else if (command.startsWith('move ')) {
            const newState = this.handleMove(command.split(' ')[1]);
            if (newState) {
                this.setState(newState);
                this.describeCurrentLocation();
            }
        }
        else if (command.startsWith('explore ') || command.startsWith('look at ')) {
            const target = command.replace(/^(explore|look at) /, '');
            this.exploreTarget(target);
        }
        else if (command === 'phone') {
            this.checkMessages();
        }
        else if (command === 'inventory') {
            this.checkInventory();
        }
        else if (command.startsWith('get ') || command.startsWith('take ')) {
            const itemName = command.replace(/^(get|take) /, '');
            const newState = this.collectItem(itemName);
            if (newState) {
                this.setState(newState);
            }
        }
        else {
            this.print("I don't understand that command.");
        }
    }

    getCurrentLocation() {
        const playerPos = World.getComponent(this.state.world, this.state.playerId, 'Position');
        
        if (!playerPos) {
            console.error('Player position not found');
            return null;
        }
        
        // Find the environment at the player's position
        const locationEntity = Array.from(this.state.world.entities.entries()).find(([entityId, _]) => {
            if (entityId === this.state.playerId) return false;
            
            const pos = World.getComponent(this.state.world, entityId, 'Position');
            return pos && pos.x === playerPos.x && pos.y === playerPos.y;
        });

        if (!locationEntity) return null;

        const [entityId, _] = locationEntity;
        const desc = World.getComponent(this.state.world, entityId, 'Description');
        
        // Add items to the location description
        const items = this.getItemsAtLocation(playerPos);
        return { entityId, desc, items };
    }

    getItemsAtLocation(pos) {
        return Array.from(this.state.world.entities.entries())
            .filter(([entityId, _]) => {
                const itemPos = World.getComponent(this.state.world, entityId, 'Position');
                const item = World.getComponent(this.state.world, entityId, 'Item');
                return itemPos && item && 
                       itemPos.x === pos.x && 
                       itemPos.y === pos.y;
            })
            .map(([entityId, _]) => ({
                entityId,
                item: World.getComponent(this.state.world, entityId, 'Item')
            }));
    }

    describeCurrentLocation() {
        const location = this.getCurrentLocation();
        if (location) {
            this.print(`You are in: ${location.desc.short}`);
            this.print(location.desc.long);
            
            if (location.items.length > 0) {
                this.print("\nYou can see:");
                location.items.forEach(({ item }) => {
                    this.print(`- ${item.name}`);
                });
            }
        }
    }

    handleMove(direction) {
        const playerPos = World.getComponent(this.state.world, this.state.playerId, 'Position');
        
        if (!playerPos) {
            console.error('Player position not found');
            return null;
        }

        const moves = {
            'north': { x: 0, y: -1 },
            'south': { x: 0, y: 1 },
            'east': { x: 1, y: 0 },
            'west': { x: -1, y: 0 }
        };

        if (!moves[direction]) {
            this.print("Invalid direction. Use north, south, east, or west.");
            return null;
        }

        const newX = playerPos.x + moves[direction].x;
        const newY = playerPos.y + moves[direction].y;

        if (newX < 0 || newX >= 10 || newY < 0 || newY >= 10) {
            this.print("You can't go that way - you've reached the edge of the world.");
            return null;
        }

        const newWorld = World.addComponent(
            this.state.world,
            this.state.playerId,
            new Position(newX, newY)
        );

        this.print(`You move ${direction}.`);
        
        return {
            ...this.state,
            world: newWorld
        };
    }

    exploreTarget(target) {
        const location = this.getCurrentLocation();
        if (location && location.desc.explorable[target]) {
            this.print(location.desc.explorable[target]);
        } else {
            this.print("There's nothing special about that.");
        }
    }

    checkMessages() {
        const messages = World.getComponent(this.state.world, this.state.playerId, 'Messages');
        if (messages.messages.length === 0) {
            this.print("You have no messages.");
        } else {
            this.print("Your messages:");
            messages.messages.forEach(msg => this.print(`- ${msg}`));
        }
    }

    collectItem(itemName) {
        const playerPos = World.getComponent(this.state.world, this.state.playerId, 'Position');
        const items = this.getItemsAtLocation(playerPos);
        
        const itemEntry = items.find(({ item }) => 
            item.name.toLowerCase() === itemName.toLowerCase()
        );

        if (!itemEntry) {
            this.print(`There is no ${itemName} here.`);
            return null;
        }

        if (!itemEntry.item.collectable) {
            this.print(`You can't take the ${itemName}.`);
            return null;
        }

        // Add to inventory
        const inventory = World.getComponent(this.state.world, this.state.playerId, 'Inventory');
        const updatedInventory = new Inventory([...inventory.items, itemEntry.item]);
        
        // Remove from world and update inventory
        let newWorld = World.removeComponent(this.state.world, itemEntry.entityId, 'Position');
        newWorld = World.addComponent(newWorld, this.state.playerId, updatedInventory);

        this.print(`You take the ${itemName}.`);
        return {
            ...this.state,
            world: newWorld
        };
    }

    checkInventory() {
        const inventory = World.getComponent(this.state.world, this.state.playerId, 'Inventory');
        if (inventory.items.length === 0) {
            this.print("Your inventory is empty.");
        } else {
            this.print("Your inventory contains:");
            inventory.items.forEach(item => {
                this.print(`- ${item.name}`);
            });
        }
    }
}

// Start the game when the page loads
window.addEventListener('load', () => {
    window.game = new Game();
});