BlueGit

timfa questward

Files

questward / server / src / simulation / tileInteract.js

tileInteract.js

tileInteract.js 1.5 KiB Download Raw
1import { Component } from "../ecs/components.js";
2import { tileToChunk, tileToLocal } from "../world/coordinates.js";
3import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
4
5/** Find a neighbouring (or same) tile with the given block type. Prefer non-self when possible. */
6export function findAdjacentBlockTile (world, tileX, tileY, blockType)
7{
8 let fallback = null;
9 for (let dy = -1; dy <= 1; dy++)
10 {
11 for (let dx = -1; dx <= 1; dx++)
12 {
13 const x = tileX + dx;
14 const y = tileY + dy;
15 const data = world.chunkData(tileToChunk(x), tileToChunk(y));
16 const index = tileToLocal(y) * CHUNK_SIZE + tileToLocal(x);
17 if (data.blocks[index]?.typeId !== blockType)
18 { continue; }
19 if (dx !== 0 || dy !== 0)
20 { return { tileX: x, tileY: y }; }
21 fallback = { tileX: x, tileY: y };
22 }
23 }
24 return fallback;
25}
26
27/** Shove the actor toward a world tile (bank, furnace, mine, craft, …). */
28export function tileShoveEvent (entityId, fromTileX, fromTileY, tileX, tileY)
29{
30 return {
31 type: "tile-shove",
32 attackerId: entityId,
33 fromTileX,
34 fromTileY,
35 tileX,
36 tileY
37 };
38}
39
40export function tileShoveTowardBlock (world, handle, entityId, blockType)
41{
42 const position = world.ecs.get(handle, Component.position);
43 if (!position)
44 { return null; }
45 const target = findAdjacentBlockTile(world, position.tileX, position.tileY, blockType);
46 if (!target)
47 { return null; }
48 return tileShoveEvent(entityId, position.tileX, position.tileY, target.tileX, target.tileY);
49}