-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstore.ts
More file actions
423 lines (357 loc) · 13.9 KB
/
Copy pathstore.ts
File metadata and controls
423 lines (357 loc) · 13.9 KB
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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
import { create } from 'zustand';
import { BlockType, InventoryItem, MobEntity, MobType, Dimension, ItemType, GameItemType } from './types';
import { nanoid } from 'nanoid';
import { noise } from './utils/noise';
import { CHUNK_SIZE, LOOT_TABLE, RECIPES } from './constants';
// Mutable input state for smooth physics loop without re-renders
export const inputState = {
joystick: { x: 0, y: 0 },
isJumping: false
};
interface GameState {
blocks: Map<string, BlockType>;
chunksGenerated: Set<string>;
playerPos: [number, number, number];
dimension: Dimension;
health: number;
isDead: boolean;
hunger: number;
thirst: number;
xp: number;
inventory: InventoryItem[];
selectedSlot: number;
isInventoryOpen: boolean;
timeOfDay: number;
isDay: boolean;
mobs: MobEntity[];
nearestVillage: [number, number] | null;
// Actions
setBlock: (x: number, y: number, z: number, type: BlockType) => void;
removeBlock: (x: number, y: number, z: number) => void;
updatePlayerPos: (pos: [number, number, number]) => void;
generateChunk: (cx: number, cz: number) => void;
damagePlayer: (amount: number) => void;
respawn: () => void;
addXp: (amount: number) => void;
tickTime: () => void;
spawnMob: (type: MobType, pos: [number, number, number]) => void;
damageMob: (id: string, amount: number) => void;
selectSlot: (index: number) => void;
toggleInventory: () => void;
craftItem: (recipeIndex: number) => void;
switchDimension: (dim: Dimension) => void;
swapHeldItem: (newItem: GameItemType) => void;
}
const INITIAL_INVENTORY: InventoryItem[] = [
{ id: ItemType.MAP, count: 1 },
{ id: BlockType.TORCH, count: 16 },
{ id: BlockType.WOOD, count: 16 },
{ id: ItemType.DIAMOND_PICKAXE, count: 1 },
{ id: ItemType.DIAMOND_SWORD, count: 1 },
{ id: BlockType.OBSIDIAN, count: 10 },
{ id: BlockType.NETHER_PORTAL, count: 1 },
{ id: ItemType.BUCKET, count: 1 },
];
export const useStore = create<GameState>((set, get) => ({
blocks: new Map(),
chunksGenerated: new Set(),
playerPos: [0, 40, 0],
dimension: Dimension.OVERWORLD,
health: 100,
isDead: false,
hunger: 100,
thirst: 100,
xp: 0,
inventory: INITIAL_INVENTORY,
selectedSlot: 0,
isInventoryOpen: false,
timeOfDay: 800,
isDay: true,
mobs: [
{ id: 'cat-companion', type: MobType.CAT, position: [2, 40, 2], health: 20, maxHealth: 20, target: 'player' }
],
nearestVillage: null,
setBlock: (x, y, z, type) => {
set((state) => {
const newBlocks = new Map(state.blocks);
const key = `${Math.floor(x)},${Math.floor(y)},${Math.floor(z)}`;
if (type === BlockType.AIR) {
newBlocks.delete(key);
} else {
newBlocks.set(key, type);
}
return { blocks: newBlocks };
});
},
removeBlock: (x, y, z) => {
const state = get();
const key = `${Math.floor(x)},${Math.floor(y)},${Math.floor(z)}`;
const block = state.blocks.get(key);
// Loot & XP
if (block) {
let drop = block as GameItemType;
let count = 1;
let xpGain = 0;
const loot = LOOT_TABLE[block];
if (loot) {
drop = loot.item;
count = Math.floor(Math.random() * (loot.max - loot.min + 1)) + loot.min;
}
// XP Logic
if (block === BlockType.COAL_ORE) xpGain = 1;
if (block === BlockType.DIAMOND_ORE) xpGain = 5;
if (block === BlockType.LAPIS_ORE) xpGain = 3;
if (block === BlockType.WOOD) xpGain = 1;
// Special: Leaves
if (block === BlockType.LEAF) {
if (Math.random() < 0.05) drop = ItemType.APPLE;
else if (Math.random() < 0.1) drop = ItemType.SAPLING;
else drop = BlockType.AIR;
}
if (drop !== BlockType.AIR) {
const newInv = [...state.inventory];
const existing = newInv.find(i => i.id === drop);
if (existing) existing.count += count;
else newInv.push({ id: drop, count });
set({ inventory: newInv });
}
if (xpGain > 0) state.addXp(xpGain);
}
state.setBlock(x, y, z, BlockType.AIR);
},
updatePlayerPos: (pos) => set({ playerPos: pos }),
switchDimension: (dim) => {
set({ dimension: dim, chunksGenerated: new Set(), blocks: new Map(), playerPos: [0, 50, 0] });
},
generateChunk: (cx, cz) => {
const key = `${cx},${cz}`;
const state = get();
if (state.chunksGenerated.has(key)) return;
set((s) => {
const newBlocks = new Map(s.blocks);
const newMobs = [...s.mobs];
const dim = s.dimension;
// Village Logic
const villageNoise = noise.noise2D(cx * 0.1, cz * 0.1);
const hasVillage = dim === Dimension.OVERWORLD && villageNoise > 0.6;
let villageLoc = s.nearestVillage;
if (hasVillage) {
const vX = cx * CHUNK_SIZE + 8;
const vZ = cz * CHUNK_SIZE + 8;
if (!villageLoc || (Math.abs(vX - s.playerPos[0]) < Math.abs(villageLoc[0] - s.playerPos[0]))) {
villageLoc = [vX, vZ];
}
}
for (let x = 0; x < CHUNK_SIZE; x++) {
for (let z = 0; z < CHUNK_SIZE; z++) {
const globalX = cx * CHUNK_SIZE + x;
const globalZ = cz * CHUNK_SIZE + z;
let groundHeight = 0;
let surfaceBlock = BlockType.GRASS;
let subBlock = BlockType.DIRT;
if (dim === Dimension.OVERWORLD) {
const f = 0.02;
const h = noise.noise2D(globalX * f, globalZ * f);
groundHeight = Math.floor((h + 1) * 0.5 * 12) + 5;
if (h > 0.5) groundHeight += Math.floor((h - 0.5) * 20);
} else if (dim === Dimension.NETHER) {
const f = 0.03;
const h = noise.noise2D(globalX * f, globalZ * f);
groundHeight = Math.floor((h + 1) * 0.5 * 15) + 10;
surfaceBlock = BlockType.NETHERRACK;
subBlock = BlockType.NETHERRACK;
const ceilH = 40 + Math.floor(noise.noise2D(globalX * 0.05, globalZ * 0.05) * 5);
for(let y=ceilH; y<50; y++) {
newBlocks.set(`${globalX},${y},${globalZ}`, BlockType.NETHERRACK);
}
} else if (dim === Dimension.END) {
const f = 0.05;
const h = noise.noise2D(globalX * f, globalZ * f);
if (h > 0.2) {
groundHeight = 30 + Math.floor(h * 10);
surfaceBlock = BlockType.END_STONE;
subBlock = BlockType.END_STONE;
} else {
groundHeight = -100;
}
}
if (groundHeight > 0) {
for (let y = 0; y <= groundHeight; y++) {
const blockKey = `${globalX},${y},${globalZ}`;
let type = BlockType.STONE;
if (y === groundHeight) type = surfaceBlock;
else if (y > groundHeight - 3) type = subBlock;
else if (y === 0) type = BlockType.BEDROCK;
if (dim === Dimension.OVERWORLD && type === BlockType.STONE) {
const r = Math.random();
if (r < 0.01) type = BlockType.COAL_ORE;
else if (r < 0.015) type = BlockType.IRON_ORE;
else if (r < 0.002 && y < 10) type = BlockType.DIAMOND_ORE;
else if (r < 0.005 && y < 20) type = BlockType.GOLD_ORE;
else if (r < 0.005 && y < 30) type = BlockType.LAPIS_ORE;
}
if (y > 1 && y < groundHeight && dim !== Dimension.END) {
const cave = noise.noise3D(globalX * 0.06, y * 0.06, globalZ * 0.06);
if (cave > 0.5) type = BlockType.AIR;
}
if (type !== BlockType.AIR) newBlocks.set(blockKey, type);
}
}
if (dim === Dimension.OVERWORLD && groundHeight < 6) {
for (let y = groundHeight + 1; y <= 6; y++) {
newBlocks.set(`${globalX},${y},${globalZ}`, BlockType.WATER);
}
}
if (dim === Dimension.NETHER && groundHeight < 10) {
for (let y = groundHeight + 1; y <= 10; y++) {
newBlocks.set(`${globalX},${y},${globalZ}`, BlockType.LAVA);
}
}
if (dim === Dimension.OVERWORLD && groundHeight > 6 && Math.random() < 0.01 && !hasVillage) {
const treeH = 4 + Math.floor(Math.random() * 2);
for(let i=1; i<=treeH; i++) newBlocks.set(`${globalX},${groundHeight+i},${globalZ}`, BlockType.WOOD);
for(let lx=-2; lx<=2; lx++){
for(let lz=-2; lz<=2; lz++){
for(let ly=treeH-1; ly<=treeH+1; ly++){
if (Math.abs(lx)+Math.abs(lz) > 3) continue;
const key = `${globalX+lx},${groundHeight+ly},${globalZ+lz}`;
if(!newBlocks.has(key)) newBlocks.set(key, BlockType.LEAF);
}
}
}
}
}
}
if (hasVillage) {
const hX = cx * CHUNK_SIZE + 8;
const hZ = cz * CHUNK_SIZE + 8;
const h = Math.floor((noise.noise2D(hX * 0.02, hZ * 0.02) + 1) * 0.5 * 12) + 5;
if (h > 6) {
for(let bx=-2; bx<=2; bx++){
for(let bz=-2; bz<=2; bz++){
for(let by=0; by<4; by++){
const k = `${hX+bx},${h+by+1},${hZ+bz}`;
if (by === 3 || Math.abs(bx)===2 || Math.abs(bz)===2) {
newBlocks.set(k, BlockType.PLANKS);
} else {
newBlocks.set(k, BlockType.AIR);
}
}
}
}
newBlocks.set(`${hX},${h+1},${hZ+2}`, BlockType.AIR);
newBlocks.set(`${hX},${h+2},${hZ+2}`, BlockType.AIR);
newBlocks.set(`${hX-1},${h+1},${hZ-1}`, BlockType.FURNACE);
newBlocks.set(`${hX+1},${h+1},${hZ-1}`, BlockType.CRAFTING_TABLE);
}
}
const newChunks = new Set(s.chunksGenerated);
newChunks.add(key);
return { blocks: newBlocks, chunksGenerated: newChunks, mobs: newMobs, nearestVillage: villageLoc };
});
},
damagePlayer: (amount) => set((state) => {
if (state.isDead) return {};
const newHealth = Math.max(0, state.health - amount);
if (newHealth === 0) {
return { health: 0, isDead: true };
}
return { health: newHealth };
}),
respawn: () => set(state => ({
health: 100,
isDead: false,
playerPos: [0, 50, 0],
hunger: 100,
thirst: 100
})),
addXp: (amount) => set(state => ({ xp: state.xp + amount })),
tickTime: () => set((state) => {
let newTime = state.timeOfDay + 0.5;
if (newTime >= 2400) newTime = 0;
const isDay = newTime > 600 && newTime < 1800;
let newMobs = state.mobs;
if (!isDay && Math.random() < 0.02 && state.mobs.length < 25) {
const type = Math.random() > 0.6 ? MobType.ZOMBIE : (Math.random() > 0.5 ? MobType.CREEPER : MobType.ZOMBIE);
const angle = Math.random() * Math.PI * 2;
const r = 15 + Math.random() * 15;
const x = state.playerPos[0] + Math.cos(angle) * r;
const z = state.playerPos[2] + Math.sin(angle) * r;
newMobs = [...state.mobs, {
id: nanoid(),
type,
position: [x, state.playerPos[1] + 5, z],
health: 20, maxHealth: 20
}];
}
return { timeOfDay: newTime, isDay, mobs: newMobs };
}),
spawnMob: (type, pos) => set(state => ({
mobs: [...state.mobs, { id: nanoid(), type, position: pos, health: 20, maxHealth: 20 }]
})),
damageMob: (id, amount) => set(state => {
const mobIndex = state.mobs.findIndex(m => m.id === id);
if (mobIndex === -1) return {};
const mob = state.mobs[mobIndex];
const newHealth = mob.health - amount;
if (newHealth <= 0) {
state.addXp(5);
return {
mobs: state.mobs.filter(m => m.id !== id),
};
}
const newMobs = [...state.mobs];
newMobs[mobIndex] = { ...mob, health: newHealth };
return { mobs: newMobs };
}),
selectSlot: (index) => set({ selectedSlot: index }),
toggleInventory: () => set(state => ({ isInventoryOpen: !state.isInventoryOpen })),
craftItem: (recipeIndex) => set(state => {
const recipe = RECIPES[recipeIndex];
const newInv = [...state.inventory];
for (const ing of recipe.ingredients) {
const slot = newInv.find(i => i.id === ing.item);
if (!slot || slot.count < ing.count) return {};
}
for (const ing of recipe.ingredients) {
const slot = newInv.find(i => i.id === ing.item)!;
slot.count -= ing.count;
if (slot.count <= 0) {
const idx = newInv.indexOf(slot);
newInv.splice(idx, 1);
}
}
const outSlot = newInv.find(i => i.id === recipe.output);
if (outSlot) outSlot.count += recipe.count;
else newInv.push({ id: recipe.output, count: recipe.count });
return { inventory: newInv };
}),
swapHeldItem: (newItemId) => set(state => {
const newInv = [...state.inventory];
const currentItem = newInv[state.selectedSlot];
if (currentItem && currentItem.count > 0) {
currentItem.count -= 1;
if (currentItem.count === 0) {
// If ran out of current item, replace directly
newInv[state.selectedSlot] = { id: newItemId, count: 1 };
return { inventory: newInv };
}
}
// Look for existing stack of new item to add to, or empty slot
// Simplified: Just push new item to end or replace slot if empty
// For bucket logic: usually you swap.
// We will try to add `newItemId` to inventory.
const existing = newInv.find(i => i.id === newItemId);
if (existing) {
existing.count += 1;
} else {
// Find empty slot or append
newInv.push({ id: newItemId, count: 1 });
}
// Remove current slot if empty
if (currentItem && currentItem.count === 0) {
newInv.splice(state.selectedSlot, 1);
}
return { inventory: newInv };
})
}));