| 1 | import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js"; |
| 2 | import { BlockType } from "/shared/definitions/tiles.js"; |
| 3 | import { GameSocket, defaultSocketUrl } from "../net/socket.js"; |
| 4 | import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js"; |
| 5 | import { WorldView } from "../render/worldView.js"; |
| 6 | import { initSocial } from "./social.js"; |
| 7 | import { initChat } from "./chat.js"; |
| 8 | import { initInventory } from "./inventory.js"; |
| 9 | import { initSkills } from "./skills.js"; |
| 10 | import { initCrafting } from "./crafting.js"; |
| 11 | import { initAlchemy } from "./alchemy.js"; |
| 12 | import { initStamina } from "./stamina.js"; |
| 13 | import { initContextMenu } from "./contextMenu.js"; |
| 14 | import { initDeath } from "./death.js"; |
| 15 | import { initToasts } from "./toasts.js"; |
| 16 | import { initShop } from "./shop.js"; |
| 17 | import { CraftingStationId } from "/shared/definitions/craftingStations.js"; |
| 18 | import { isOreBoulderState } from "/shared/definitions/materialTiers.js"; |
| 19 | import { formatQuantity } from "/shared/items/formatQuantity.js"; |
| 20 | import { ItemId } from "/shared/definitions/items.js"; |
| 21 | import { countCoinsInSlots } from "/shared/items/inventory.js"; |
| 22 | |
| 23 | const game = new Game(); |
| 24 | const hud = document.getElementById("hud"); |
| 25 | const overlay = document.getElementById("overlay"); |
| 26 | const statusEl = document.getElementById("status"); |
| 27 | const characterList = document.getElementById("character-list"); |
| 28 | const errorEl = document.getElementById("error"); |
| 29 | |
| 30 | let socket; |
| 31 | let session = null; |
| 32 | let playing = false; |
| 33 | let view = null; |
| 34 | let scene = null; |
| 35 | let gait = GAIT.walk; |
| 36 | let catalog = { grounds: {}, blocks: {} }; |
| 37 | let social; |
| 38 | let chat; |
| 39 | let inventory; |
| 40 | let skills; |
| 41 | let crafting; |
| 42 | let alchemy; |
| 43 | let staminaUi; |
| 44 | let contextMenu; |
| 45 | let death; |
| 46 | let toasts; |
| 47 | let shop; |
| 48 | let pendingPickup = null; |
| 49 | /** @type {{ kind: "bank" | "cauldron" | "station" | "mine", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */ |
| 50 | let pendingInteract = null; |
| 51 | /** Framework can report mousePressed for two frames; latch so one physical click is one command. */ |
| 52 | let leftClickConsumed = false; |
| 53 | |
| 54 | function showError (message) |
| 55 | { |
| 56 | errorEl.textContent = message ?? ""; |
| 57 | } |
| 58 | |
| 59 | function renderCharacters (characters) |
| 60 | { |
| 61 | characterList.innerHTML = ""; |
| 62 | for (const character of characters) |
| 63 | { |
| 64 | const row = document.createElement("div"); |
| 65 | row.className = "character-row"; |
| 66 | const pending = character.deletionScheduledAt |
| 67 | ? ` (deleting ${new Date(character.deletionScheduledAt).toLocaleString()})` |
| 68 | : ""; |
| 69 | row.innerHTML = `<strong>${character.firstName} ${character.lastName}</strong> · ${character.sex}${pending}`; |
| 70 | const play = document.createElement("button"); |
| 71 | play.textContent = "Play"; |
| 72 | play.disabled = !!character.deletionScheduledAt; |
| 73 | play.addEventListener("click", () => socket.send({ type: MessageType.selectCharacter, characterId: character.characterId })); |
| 74 | const del = document.createElement("button"); |
| 75 | del.textContent = character.deletionScheduledAt ? "Cancel delete" : "Delete"; |
| 76 | del.addEventListener("click", () => |
| 77 | { |
| 78 | socket.send({ |
| 79 | type: character.deletionScheduledAt ? MessageType.cancelDeleteCharacter : MessageType.scheduleDeleteCharacter, |
| 80 | characterId: character.characterId |
| 81 | }); |
| 82 | }); |
| 83 | row.append(play, del); |
| 84 | characterList.append(row); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | function uiBlocked () |
| 89 | { |
| 90 | return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking() |
| 91 | || crafting?.isBlocking() || alchemy?.isBlocking() || contextMenu?.isOpen() || death?.isBlocking()); |
| 92 | } |
| 93 | |
| 94 | function clearPendingPickup () |
| 95 | { |
| 96 | pendingPickup = null; |
| 97 | } |
| 98 | |
| 99 | function clearPendingInteract () |
| 100 | { |
| 101 | pendingInteract = null; |
| 102 | } |
| 103 | |
| 104 | function clearAllPendingActions () |
| 105 | { |
| 106 | clearPendingPickup(); |
| 107 | clearPendingInteract(); |
| 108 | } |
| 109 | |
| 110 | function approachAdjacentTile (tileX, tileY) |
| 111 | { |
| 112 | const local = view.entities.get(view.localEntityId); |
| 113 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 114 | { return true; } |
| 115 | let best = null; |
| 116 | let bestDist = Infinity; |
| 117 | for (let dy = -1; dy <= 1; dy++) |
| 118 | { |
| 119 | for (let dx = -1; dx <= 1; dx++) |
| 120 | { |
| 121 | if (dx === 0 && dy === 0) |
| 122 | { continue; } |
| 123 | const destX = tileX + dx; |
| 124 | const destY = tileY + dy; |
| 125 | const dist = local |
| 126 | ? chebyshev(local.tileX, local.tileY, destX, destY) |
| 127 | : 0; |
| 128 | if (dist < bestDist) |
| 129 | { |
| 130 | bestDist = dist; |
| 131 | best = { tileX: destX, tileY: destY }; |
| 132 | } |
| 133 | } |
| 134 | } |
| 135 | if (best) |
| 136 | { socket.send({ type: MessageType.moveTo, tileX: best.tileX, tileY: best.tileY }); } |
| 137 | return false; |
| 138 | } |
| 139 | |
| 140 | function requestOpenBank (tileX, tileY, { getCheques = false } = {}) |
| 141 | { |
| 142 | clearAllPendingActions(); |
| 143 | pendingInteract = { kind: "bank", tileX, tileY, getCheques: !!getCheques }; |
| 144 | const local = view?.entities.get(view.localEntityId); |
| 145 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 146 | { flushPendingInteract(); } |
| 147 | else |
| 148 | { approachAdjacentTile(tileX, tileY); } |
| 149 | } |
| 150 | |
| 151 | function requestOpenCauldron (tileX, tileY) |
| 152 | { |
| 153 | clearAllPendingActions(); |
| 154 | pendingInteract = { kind: "cauldron", tileX, tileY }; |
| 155 | const local = view?.entities.get(view.localEntityId); |
| 156 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 157 | { flushPendingInteract(); } |
| 158 | else |
| 159 | { approachAdjacentTile(tileX, tileY); } |
| 160 | } |
| 161 | |
| 162 | function requestOpenFurnace (tileX, tileY) |
| 163 | { |
| 164 | requestOpenCraftStation(CraftingStationId.furnace, tileX, tileY); |
| 165 | } |
| 166 | |
| 167 | function requestOpenCraftStation (stationId, tileX, tileY) |
| 168 | { |
| 169 | clearAllPendingActions(); |
| 170 | pendingInteract = { kind: "station", stationId, tileX, tileY }; |
| 171 | const local = view?.entities.get(view.localEntityId); |
| 172 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 173 | { flushPendingInteract(); } |
| 174 | else |
| 175 | { approachAdjacentTile(tileX, tileY); } |
| 176 | } |
| 177 | |
| 178 | function requestMine (tileX, tileY) |
| 179 | { |
| 180 | clearAllPendingActions(); |
| 181 | pendingInteract = { kind: "mine", tileX, tileY }; |
| 182 | const local = view?.entities.get(view.localEntityId); |
| 183 | if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1) |
| 184 | { flushPendingInteract(); } |
| 185 | else |
| 186 | { approachAdjacentTile(tileX, tileY); } |
| 187 | } |
| 188 | |
| 189 | function requestTalk (targetEntityId) |
| 190 | { |
| 191 | clearPendingPickup(); |
| 192 | pendingInteract = { kind: "talk", targetEntityId }; |
| 193 | const target = view.entities.get(targetEntityId); |
| 194 | if (!target) |
| 195 | { |
| 196 | clearPendingInteract(); |
| 197 | return; |
| 198 | } |
| 199 | if (approachAdjacentTile(target.tileX, target.tileY)) |
| 200 | { flushPendingInteract(); } |
| 201 | } |
| 202 | |
| 203 | function flushPendingInteract () |
| 204 | { |
| 205 | if (!pendingInteract || !view) |
| 206 | { return; } |
| 207 | const local = view.entities.get(view.localEntityId); |
| 208 | if (!local) |
| 209 | { return; } |
| 210 | |
| 211 | if (pendingInteract.kind === "bank") |
| 212 | { |
| 213 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 214 | { return; } |
| 215 | const getCheques = !!pendingInteract.getCheques; |
| 216 | socket.send({ type: MessageType.openBank }); |
| 217 | if (getCheques) |
| 218 | { inventory?.getBlankCheques(); } |
| 219 | clearPendingInteract(); |
| 220 | return; |
| 221 | } |
| 222 | |
| 223 | if (pendingInteract.kind === "cauldron") |
| 224 | { |
| 225 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 226 | { return; } |
| 227 | socket.send({ type: MessageType.openCauldron }); |
| 228 | clearPendingInteract(); |
| 229 | return; |
| 230 | } |
| 231 | |
| 232 | if (pendingInteract.kind === "station") |
| 233 | { |
| 234 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 235 | { return; } |
| 236 | socket.send({ |
| 237 | type: MessageType.openStation, |
| 238 | stationId: pendingInteract.stationId |
| 239 | }); |
| 240 | clearPendingInteract(); |
| 241 | return; |
| 242 | } |
| 243 | |
| 244 | if (pendingInteract.kind === "mine") |
| 245 | { |
| 246 | if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1) |
| 247 | { return; } |
| 248 | socket.send({ |
| 249 | type: MessageType.mine, |
| 250 | tileX: pendingInteract.tileX, |
| 251 | tileY: pendingInteract.tileY |
| 252 | }); |
| 253 | clearPendingInteract(); |
| 254 | return; |
| 255 | } |
| 256 | |
| 257 | if (pendingInteract.kind === "talk") |
| 258 | { |
| 259 | const target = view.entities.get(pendingInteract.targetEntityId); |
| 260 | if (!target) |
| 261 | { |
| 262 | clearPendingInteract(); |
| 263 | return; |
| 264 | } |
| 265 | if (chebyshev(local.tileX, local.tileY, target.tileX, target.tileY) > 1) |
| 266 | { |
| 267 | // Target may have moved — keep chasing. |
| 268 | approachAdjacentTile(target.tileX, target.tileY); |
| 269 | return; |
| 270 | } |
| 271 | socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId }); |
| 272 | clearPendingInteract(); |
| 273 | } |
| 274 | } |
| 275 | |
| 276 | function requestPickup (ground) |
| 277 | { |
| 278 | if (!ground) |
| 279 | { return; } |
| 280 | clearPendingInteract(); |
| 281 | pendingPickup = { |
| 282 | groundItemId: ground.groundItemId, |
| 283 | tileX: ground.tileX, |
| 284 | tileY: ground.tileY |
| 285 | }; |
| 286 | const local = view.entities.get(view.localEntityId); |
| 287 | if (local && local.tileX === ground.tileX && local.tileY === ground.tileY) |
| 288 | { |
| 289 | flushPendingPickup(); |
| 290 | return; |
| 291 | } |
| 292 | socket.send({ type: MessageType.moveTo, tileX: ground.tileX, tileY: ground.tileY }); |
| 293 | } |
| 294 | |
| 295 | function flushPendingPickup () |
| 296 | { |
| 297 | if (!pendingPickup || !view) |
| 298 | { return; } |
| 299 | const item = view.groundItems.get(pendingPickup.groundItemId); |
| 300 | if (!item) |
| 301 | { |
| 302 | clearPendingPickup(); |
| 303 | return; |
| 304 | } |
| 305 | const local = view.entities.get(view.localEntityId); |
| 306 | if (!local) |
| 307 | { return; } |
| 308 | if (local.tileX !== pendingPickup.tileX || local.tileY !== pendingPickup.tileY) |
| 309 | { return; } |
| 310 | socket.send({ type: MessageType.pickupItem, groundItemId: pendingPickup.groundItemId }); |
| 311 | clearPendingPickup(); |
| 312 | } |
| 313 | |
| 314 | function requestAttack (targetEntityId) |
| 315 | { |
| 316 | clearAllPendingActions(); |
| 317 | socket.send({ type: MessageType.attack, targetEntityId }); |
| 318 | } |
| 319 | |
| 320 | function isAttackableEntity (entity) |
| 321 | { |
| 322 | if (!entity || entity.untargetable) |
| 323 | { return false; } |
| 324 | if (entity.canFight) |
| 325 | { return true; } |
| 326 | // Snapshots can omit canFight; mobs are still attackable via LMB. |
| 327 | return !!entity.mobTypeId && !entity.talkable; |
| 328 | } |
| 329 | |
| 330 | function handleLeftClick (mouseX, mouseY) |
| 331 | { |
| 332 | const entity = view.entityAtScreen(mouseX, mouseY); |
| 333 | if (entity && entity.entityId !== view.localEntityId && !entity.untargetable) |
| 334 | { |
| 335 | clearPendingPickup(); |
| 336 | if (entity.characterId) |
| 337 | { |
| 338 | clearPendingInteract(); |
| 339 | social.inspect(entity); |
| 340 | return; |
| 341 | } |
| 342 | if (entity.talkable) |
| 343 | { |
| 344 | requestTalk(entity.entityId); |
| 345 | return; |
| 346 | } |
| 347 | if (isAttackableEntity(entity)) |
| 348 | { |
| 349 | requestAttack(entity.entityId); |
| 350 | return; |
| 351 | } |
| 352 | // Clicked an entity we don't act on — do not fall through to walk (that cancels combat). |
| 353 | return; |
| 354 | } |
| 355 | |
| 356 | const tile = view.screenToTile(mouseX, mouseY); |
| 357 | const ground = view.groundItemAtTile(tile.tileX, tile.tileY); |
| 358 | if (ground) |
| 359 | { requestPickup(ground); } |
| 360 | else if (isBankTile(view, tile.tileX, tile.tileY)) |
| 361 | { requestOpenBank(tile.tileX, tile.tileY); } |
| 362 | else if (isCauldronTile(view, tile.tileX, tile.tileY)) |
| 363 | { requestOpenCauldron(tile.tileX, tile.tileY); } |
| 364 | else if (isFurnaceTile(view, tile.tileX, tile.tileY)) |
| 365 | { requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY); } |
| 366 | else if (isAnvilTile(view, tile.tileX, tile.tileY)) |
| 367 | { requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY); } |
| 368 | else if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) |
| 369 | { requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY); } |
| 370 | else if (isOreBoulderTile(view, tile.tileX, tile.tileY)) |
| 371 | { requestMine(tile.tileX, tile.tileY); } |
| 372 | else |
| 373 | { |
| 374 | clearAllPendingActions(); |
| 375 | socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | function handleRightClick (event, mouseX, mouseY) |
| 380 | { |
| 381 | event.preventDefault(); |
| 382 | const tile = view.screenToTile(mouseX, mouseY); |
| 383 | const items = []; |
| 384 | const walkTileX = tile.tileX; |
| 385 | const walkTileY = tile.tileY; |
| 386 | |
| 387 | items.push({ |
| 388 | label: "Walk here", |
| 389 | onSelect: () => |
| 390 | { |
| 391 | clearAllPendingActions(); |
| 392 | socket.send({ type: MessageType.moveTo, tileX: walkTileX, tileY: walkTileY }); |
| 393 | } |
| 394 | }); |
| 395 | |
| 396 | for (const entity of view.entitiesAtTile(tile.tileX, tile.tileY)) |
| 397 | { |
| 398 | if (entity.entityId === view.localEntityId) |
| 399 | { continue; } |
| 400 | const targetName = entityLabel(entity); |
| 401 | items.push({ |
| 402 | label: `Follow ${targetName}`, |
| 403 | onSelect: () => |
| 404 | { |
| 405 | clearAllPendingActions(); |
| 406 | socket.send({ type: MessageType.follow, targetEntityId: entity.entityId }); |
| 407 | } |
| 408 | }); |
| 409 | if (entity.untargetable) |
| 410 | { continue; } |
| 411 | if (entity.talkable) |
| 412 | { |
| 413 | items.push({ |
| 414 | label: `Trade with ${targetName}`, |
| 415 | onSelect: () => requestTalk(entity.entityId) |
| 416 | }); |
| 417 | } |
| 418 | if (entity.characterId) |
| 419 | { |
| 420 | items.push({ |
| 421 | label: `${targetName} info`, |
| 422 | onSelect: () => |
| 423 | { |
| 424 | clearAllPendingActions(); |
| 425 | social.inspect(entity); |
| 426 | } |
| 427 | }); |
| 428 | } |
| 429 | items.push({ |
| 430 | label: `Attack ${targetName}`, |
| 431 | onSelect: () => requestAttack(entity.entityId) |
| 432 | }); |
| 433 | } |
| 434 | |
| 435 | for (const ground of view.groundItemsAtTile(tile.tileX, tile.tileY)) |
| 436 | { |
| 437 | const name = groundLabel(ground); |
| 438 | items.push({ |
| 439 | label: `Pick up ${name}`, |
| 440 | onSelect: () => requestPickup(ground) |
| 441 | }); |
| 442 | } |
| 443 | |
| 444 | if (isBankTile(view, tile.tileX, tile.tileY)) |
| 445 | { |
| 446 | items.push({ |
| 447 | label: "Bank", |
| 448 | onSelect: () => requestOpenBank(tile.tileX, tile.tileY) |
| 449 | }); |
| 450 | items.push({ |
| 451 | label: "Get Blank Cheques", |
| 452 | onSelect: () => requestOpenBank(tile.tileX, tile.tileY, { getCheques: true }) |
| 453 | }); |
| 454 | } |
| 455 | |
| 456 | if (isCauldronTile(view, tile.tileX, tile.tileY)) |
| 457 | { |
| 458 | items.push({ |
| 459 | label: "Alchemy", |
| 460 | onSelect: () => requestOpenCauldron(tile.tileX, tile.tileY) |
| 461 | }); |
| 462 | } |
| 463 | |
| 464 | if (isFurnaceTile(view, tile.tileX, tile.tileY)) |
| 465 | { |
| 466 | items.push({ |
| 467 | label: "Smelt", |
| 468 | onSelect: () => requestOpenCraftStation(CraftingStationId.furnace, tile.tileX, tile.tileY) |
| 469 | }); |
| 470 | } |
| 471 | |
| 472 | if (isAnvilTile(view, tile.tileX, tile.tileY)) |
| 473 | { |
| 474 | items.push({ |
| 475 | label: "Smith", |
| 476 | onSelect: () => requestOpenCraftStation(CraftingStationId.anvil, tile.tileX, tile.tileY) |
| 477 | }); |
| 478 | } |
| 479 | |
| 480 | if (isWoodworkingBenchTile(view, tile.tileX, tile.tileY)) |
| 481 | { |
| 482 | items.push({ |
| 483 | label: "Woodwork", |
| 484 | onSelect: () => requestOpenCraftStation(CraftingStationId.woodworkingBench, tile.tileX, tile.tileY) |
| 485 | }); |
| 486 | } |
| 487 | |
| 488 | if (isOreBoulderTile(view, tile.tileX, tile.tileY)) |
| 489 | { |
| 490 | items.push({ |
| 491 | label: "Mine", |
| 492 | onSelect: () => requestMine(tile.tileX, tile.tileY) |
| 493 | }); |
| 494 | } |
| 495 | |
| 496 | contextMenu.show(event.clientX, event.clientY, items); |
| 497 | } |
| 498 | |
| 499 | function entityLabel (entity) |
| 500 | { |
| 501 | const first = (entity?.firstName ?? "").trim(); |
| 502 | const last = (entity?.lastName ?? "").trim(); |
| 503 | if (first && last) |
| 504 | { return `${first} ${last}`; } |
| 505 | return first || "target"; |
| 506 | } |
| 507 | |
| 508 | function groundLabel (ground) |
| 509 | { |
| 510 | const name = (ground?.displayName ?? "").trim() || "item"; |
| 511 | const qty = ground?.quantity ?? 1; |
| 512 | if (qty <= 1) |
| 513 | { return name; } |
| 514 | return `${name} (${formatQuantity(qty)})`; |
| 515 | } |
| 516 | |
| 517 | function startPlay (payload) |
| 518 | { |
| 519 | playing = true; |
| 520 | overlay.hidden = true; |
| 521 | hud.hidden = false; |
| 522 | document.getElementById("you").textContent = `${payload.firstName} ${payload.lastName} (${session.authSubject})`; |
| 523 | gait = payload.gait ?? GAIT.walk; |
| 524 | document.getElementById("gait").textContent = gait; |
| 525 | staminaUi?.show(); |
| 526 | if (payload.stamina != null) |
| 527 | { staminaUi?.apply(payload.stamina); } |
| 528 | if (!scene) |
| 529 | { |
| 530 | scene = new Scene(0, 0, window.innerWidth, window.innerHeight); |
| 531 | game.loadScene(scene); |
| 532 | useNearestNeighbour(scene, game.images); |
| 533 | view = new WorldView(game, scene, catalog); |
| 534 | const ticker = new GameObject(0, 0, null, 10); |
| 535 | ticker.update = (dt) => |
| 536 | { |
| 537 | const leftPressed = GameInput.mousePressed(GameInput.MouseButtons.Left); |
| 538 | const leftHeld = GameInput.mouseHeld(GameInput.MouseButtons.Left); |
| 539 | if (!leftPressed && !leftHeld) |
| 540 | { leftClickConsumed = false; } |
| 541 | else if (!leftClickConsumed && playing && !uiBlocked()) |
| 542 | { |
| 543 | leftClickConsumed = true; |
| 544 | const canvas = scene.canvas; |
| 545 | const rect = canvas.getBoundingClientRect(); |
| 546 | const mouseX = GameInput.mousePosition.x - rect.left; |
| 547 | const mouseY = GameInput.mousePosition.y - rect.top; |
| 548 | handleLeftClick(mouseX, mouseY); |
| 549 | } |
| 550 | if (GameInput.isPressed(82) && !uiBlocked()) |
| 551 | { |
| 552 | const next = gait === GAIT.run ? GAIT.walk : GAIT.run; |
| 553 | if (next === GAIT.run && (staminaUi?.getCurrent?.() ?? 1) <= 0) |
| 554 | { return; } |
| 555 | socket.send({ type: MessageType.setGait, gait: next }); |
| 556 | // Walk always applies; run waits for authoritative STAMINA (may reject if empty). |
| 557 | if (next === GAIT.walk) |
| 558 | { |
| 559 | gait = next; |
| 560 | document.getElementById("gait").textContent = gait; |
| 561 | } |
| 562 | } |
| 563 | if (playing && !death?.isBlocking()) |
| 564 | { |
| 565 | flushPendingPickup(); |
| 566 | flushPendingInteract(); |
| 567 | social?.updateNametag(view, scene, view.localEntityId); |
| 568 | chat?.update(view, scene); |
| 569 | } |
| 570 | view.update(dt); |
| 571 | }; |
| 572 | scene.addObject(ticker); |
| 573 | window.addEventListener("resize", () => |
| 574 | { |
| 575 | scene.size.x = window.innerWidth; |
| 576 | scene.size.y = window.innerHeight; |
| 577 | scene.g_fixSize(); |
| 578 | useNearestNeighbour(scene, game.images); |
| 579 | }); |
| 580 | window.addEventListener("wheel", (event) => |
| 581 | { |
| 582 | if (!playing || uiBlocked()) |
| 583 | { return; } |
| 584 | view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25)); |
| 585 | document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`; |
| 586 | }, { passive: true }); |
| 587 | scene.canvas.addEventListener("contextmenu", (event) => |
| 588 | { |
| 589 | if (!playing || uiBlocked()) |
| 590 | { return; } |
| 591 | const rect = scene.canvas.getBoundingClientRect(); |
| 592 | handleRightClick(event, event.clientX - rect.left, event.clientY - rect.top); |
| 593 | }); |
| 594 | } |
| 595 | view.setSettings(payload.settings ?? view.settings); |
| 596 | chat?.syncSettings(); |
| 597 | view.worldHour = payload.worldTime?.hour ?? 12; |
| 598 | view.setLocalEntity( |
| 599 | payload.entityId, |
| 600 | payload.tileX, |
| 601 | payload.tileY, |
| 602 | payload.gait, |
| 603 | payload.sex, |
| 604 | payload.firstName, |
| 605 | payload.lastName, |
| 606 | payload.characterId, |
| 607 | payload.layers |
| 608 | ); |
| 609 | } |
| 610 | |
| 611 | async function main () |
| 612 | { |
| 613 | catalog = await loadSpriteCatalog(); |
| 614 | await preloadCatalogImages(game, catalog); |
| 615 | applySpriteSheets(game.images, catalog); |
| 616 | social = initSocial({ |
| 617 | socket: { send (payload) { socket.send(payload); } }, |
| 618 | MessageType |
| 619 | }); |
| 620 | contextMenu = initContextMenu(); |
| 621 | inventory = initInventory({ |
| 622 | socket: { send (payload) { socket.send(payload); } }, |
| 623 | MessageType, |
| 624 | contextMenu, |
| 625 | resolveSpriteUrl (name) |
| 626 | { |
| 627 | return catalog?.images?.find((entry) => entry.name === name)?.url ?? null; |
| 628 | }, |
| 629 | getFriends () |
| 630 | { |
| 631 | return social?.getFriends?.() ?? []; |
| 632 | }, |
| 633 | getLocalName () |
| 634 | { |
| 635 | const you = document.getElementById("you")?.textContent ?? ""; |
| 636 | return you.split("(")[0].trim() || "Unknown"; |
| 637 | } |
| 638 | }); |
| 639 | skills = initSkills(); |
| 640 | crafting = initCrafting({ |
| 641 | socket: { send (payload) { socket.send(payload); } }, |
| 642 | MessageType, |
| 643 | getInventorySlots () |
| 644 | { |
| 645 | return inventory?.getInventorySlots?.() ?? []; |
| 646 | }, |
| 647 | getSkillLevel (skillId) |
| 648 | { |
| 649 | return skills?.skillLevel?.(skillId) ?? 1; |
| 650 | } |
| 651 | }); |
| 652 | alchemy = initAlchemy({ |
| 653 | socket: { send (payload) { socket.send(payload); } }, |
| 654 | MessageType, |
| 655 | getInventorySlots () |
| 656 | { |
| 657 | return inventory?.getInventorySlots?.() ?? []; |
| 658 | } |
| 659 | }); |
| 660 | staminaUi = initStamina(); |
| 661 | toasts = initToasts(); |
| 662 | shop = initShop({ |
| 663 | socket: { send (payload) { socket.send(payload); } }, |
| 664 | MessageType, |
| 665 | getCoinCount () |
| 666 | { |
| 667 | return countCoinsInSlots(inventory?.getInventorySlots?.() ?? []); |
| 668 | } |
| 669 | }); |
| 670 | chat = initChat({ |
| 671 | socket: { send (payload) { socket.send(payload); } }, |
| 672 | MessageType, |
| 673 | getSettings: () => view?.settings |
| 674 | }); |
| 675 | death = initDeath({ |
| 676 | socket: { send (payload) { socket.send(payload); } }, |
| 677 | MessageType |
| 678 | }); |
| 679 | game.startGame(); |
| 680 | |
| 681 | socket = new GameSocket(defaultSocketUrl(), (message) => |
| 682 | { |
| 683 | switch (message.type) |
| 684 | { |
| 685 | case MessageType.session: |
| 686 | session = message; |
| 687 | statusEl.textContent = `Signed in as ${message.authSubject} (stub admin)`; |
| 688 | renderCharacters(message.characters); |
| 689 | break; |
| 690 | case MessageType.characterList: |
| 691 | renderCharacters(message.characters); |
| 692 | if (!playing) |
| 693 | { overlay.hidden = false; } |
| 694 | break; |
| 695 | case MessageType.enterWorld: |
| 696 | startPlay(message); |
| 697 | inventory?.setLocalCharacterId(message.characterId); |
| 698 | break; |
| 699 | case MessageType.chunkSnapshot: |
| 700 | view?.applySnapshot(message); |
| 701 | break; |
| 702 | case MessageType.chunkDelta: |
| 703 | for (const tile of message.tiles ?? []) |
| 704 | { |
| 705 | view?.updateAuthoredTile( |
| 706 | message.chunkX, |
| 707 | message.chunkY, |
| 708 | tile.localX, |
| 709 | tile.localY, |
| 710 | { ground: tile.ground, block: tile.block, light: tile.light } |
| 711 | ); |
| 712 | } |
| 713 | break; |
| 714 | case MessageType.unsubscribeChunk: |
| 715 | view?.removeChunk(message.chunkX, message.chunkY); |
| 716 | break; |
| 717 | case MessageType.entitySpawn: |
| 718 | view?.spawnEntity(message); |
| 719 | break; |
| 720 | case MessageType.entityMove: |
| 721 | view?.moveEntity(message); |
| 722 | if (message.entityId === view?.localEntityId && message.gait) |
| 723 | { |
| 724 | gait = message.gait; |
| 725 | document.getElementById("gait").textContent = gait; |
| 726 | } |
| 727 | break; |
| 728 | case MessageType.entityDespawn: |
| 729 | view?.despawnEntity(message.entityId); |
| 730 | break; |
| 731 | case MessageType.entityAppearance: |
| 732 | view?.setAppearance(message); |
| 733 | break; |
| 734 | case MessageType.groundItemAppear: |
| 735 | view?.upsertGroundItem(message); |
| 736 | break; |
| 737 | case MessageType.groundItemDespawn: |
| 738 | view?.despawnGroundItem(message.groundItemId); |
| 739 | break; |
| 740 | case MessageType.inventory: |
| 741 | inventory?.handleInventory(message); |
| 742 | crafting?.refresh(); |
| 743 | alchemy?.refresh(); |
| 744 | shop?.refresh(); |
| 745 | break; |
| 746 | case MessageType.skills: |
| 747 | skills?.render(message.skills); |
| 748 | crafting?.refresh(); |
| 749 | break; |
| 750 | case MessageType.stamina: |
| 751 | staminaUi?.apply(message); |
| 752 | if (message.gait) |
| 753 | { |
| 754 | gait = message.gait; |
| 755 | document.getElementById("gait").textContent = gait; |
| 756 | } |
| 757 | break; |
| 758 | case MessageType.bankSnapshot: |
| 759 | inventory?.handleBank(message); |
| 760 | break; |
| 761 | case MessageType.cauldronSnapshot: |
| 762 | alchemy?.handleSnapshot(message); |
| 763 | break; |
| 764 | case MessageType.pigeonDispatched: |
| 765 | inventory?.handlePigeonDispatched(message); |
| 766 | break; |
| 767 | case MessageType.pigeonDelivered: |
| 768 | inventory?.handlePigeonDelivered(message); |
| 769 | break; |
| 770 | case MessageType.characterSearchResult: |
| 771 | inventory?.handleCharacterSearch(message); |
| 772 | break; |
| 773 | case MessageType.craftResult: |
| 774 | crafting?.handleCraftResult(message); |
| 775 | break; |
| 776 | case MessageType.worldStatus: |
| 777 | if (view) |
| 778 | { |
| 779 | view.setSettings(message.settings ?? view.settings); |
| 780 | view.worldHour = message.worldTime?.hour ?? view.worldHour; |
| 781 | chat?.syncSettings(); |
| 782 | } |
| 783 | break; |
| 784 | case MessageType.chatBubble: |
| 785 | chat?.showBubble(message); |
| 786 | break; |
| 787 | case MessageType.friends: |
| 788 | social?.handleFriends(message); |
| 789 | break; |
| 790 | case MessageType.combatSwing: |
| 791 | view?.spawnCombatSwing(message); |
| 792 | break; |
| 793 | case MessageType.gatherSwing: |
| 794 | case MessageType.tileShove: |
| 795 | view?.spawnGatherSwing(message); |
| 796 | break; |
| 797 | case MessageType.stationOpen: |
| 798 | if (message.stationId) |
| 799 | { crafting?.openStation(message.stationId); } |
| 800 | break; |
| 801 | case MessageType.shopOpen: |
| 802 | shop?.handleShopOpen(message); |
| 803 | break; |
| 804 | case MessageType.itemBubble: |
| 805 | chat?.showItemBubble(message); |
| 806 | break; |
| 807 | case MessageType.gatherComplete: |
| 808 | crafting?.refresh(); |
| 809 | break; |
| 810 | case MessageType.combatHit: |
| 811 | view?.updateEntityHealth(message.targetId, message.health, message.maxHealth); |
| 812 | view?.flashDamage(message.targetId); |
| 813 | view?.spawnDamageNumber(message.targetId, message.damage); |
| 814 | break; |
| 815 | case MessageType.playerDied: |
| 816 | clearAllPendingActions(); |
| 817 | contextMenu?.hide(); |
| 818 | death?.show(); |
| 819 | break; |
| 820 | case MessageType.playerRespawned: |
| 821 | death?.hide(); |
| 822 | view?.updateEntityHealth(message.entityId, message.health, message.maxHealth); |
| 823 | if (message.stamina != null || message.maxStamina != null) |
| 824 | { |
| 825 | staminaUi?.apply({ |
| 826 | current: message.stamina ?? staminaUi.getCurrent?.(), |
| 827 | max: message.maxStamina ?? staminaUi.getMax?.() |
| 828 | }); |
| 829 | } |
| 830 | break; |
| 831 | case MessageType.error: |
| 832 | if (playing) |
| 833 | { toasts?.show(message.message); } |
| 834 | else |
| 835 | { showError(message.message); } |
| 836 | social?.showError(message.message); |
| 837 | break; |
| 838 | case MessageType.forceLogout: |
| 839 | returnToMenu(message.reason); |
| 840 | break; |
| 841 | } |
| 842 | }, { |
| 843 | onClose (event) |
| 844 | { |
| 845 | if (playing) |
| 846 | { returnToMenu(event.reason || "Disconnected from server."); } |
| 847 | } |
| 848 | }); |
| 849 | await socket.connect(); |
| 850 | if (typeof window !== "undefined") |
| 851 | { |
| 852 | window.__craftDev = (stationId = CraftingStationId.craftingBench) => |
| 853 | { |
| 854 | crafting?.openStation(stationId); |
| 855 | }; |
| 856 | } |
| 857 | } |
| 858 | |
| 859 | function returnToMenu (reason = "") |
| 860 | { |
| 861 | playing = false; |
| 862 | clearAllPendingActions(); |
| 863 | social?.reset(); |
| 864 | chat?.reset(); |
| 865 | inventory?.reset(); |
| 866 | crafting?.reset(); |
| 867 | alchemy?.reset(); |
| 868 | staminaUi?.hide(); |
| 869 | skills?.hide(); |
| 870 | contextMenu?.hide(); |
| 871 | death?.reset(); |
| 872 | if (view) |
| 873 | { |
| 874 | for (const key of [...(view.chunks?.keys?.() ?? [])]) |
| 875 | { |
| 876 | const [chunkX, chunkY] = key.split(",").map(Number); |
| 877 | view.removeChunk(chunkX, chunkY); |
| 878 | } |
| 879 | } |
| 880 | overlay.hidden = false; |
| 881 | hud.hidden = true; |
| 882 | if (reason) |
| 883 | { statusEl.textContent = reason; } |
| 884 | } |
| 885 | |
| 886 | document.getElementById("create-form").addEventListener("submit", (event) => |
| 887 | { |
| 888 | event.preventDefault(); |
| 889 | showError(""); |
| 890 | socket.send({ |
| 891 | type: MessageType.createCharacter, |
| 892 | firstName: document.getElementById("first-name").value, |
| 893 | lastName: document.getElementById("last-name").value, |
| 894 | sex: document.getElementById("sex").value |
| 895 | }); |
| 896 | }); |
| 897 | |
| 898 | document.getElementById("leave").addEventListener("click", () => |
| 899 | { |
| 900 | socket.send({ type: MessageType.leaveWorld }); |
| 901 | returnToMenu(); |
| 902 | }); |
| 903 | |
| 904 | main().catch((error) => |
| 905 | { |
| 906 | showError(error.message); |
| 907 | console.error(error); |
| 908 | }); |
| 909 | |
| 910 | function isBankTile (view, tileX, tileY) |
| 911 | { |
| 912 | return blockTypeAt(view, tileX, tileY) === BlockType.bank; |
| 913 | } |
| 914 | |
| 915 | function isCauldronTile (view, tileX, tileY) |
| 916 | { |
| 917 | return blockTypeAt(view, tileX, tileY) === BlockType.cauldron; |
| 918 | } |
| 919 | |
| 920 | function isFurnaceTile (view, tileX, tileY) |
| 921 | { |
| 922 | return blockTypeAt(view, tileX, tileY) === BlockType.furnace; |
| 923 | } |
| 924 | |
| 925 | function isAnvilTile (view, tileX, tileY) |
| 926 | { |
| 927 | return blockTypeAt(view, tileX, tileY) === BlockType.anvil; |
| 928 | } |
| 929 | |
| 930 | function isWoodworkingBenchTile (view, tileX, tileY) |
| 931 | { |
| 932 | return blockTypeAt(view, tileX, tileY) === BlockType.woodworkingBench; |
| 933 | } |
| 934 | |
| 935 | function isOreBoulderTile (view, tileX, tileY) |
| 936 | { |
| 937 | const block = blockAt(view, tileX, tileY); |
| 938 | return block?.typeId === BlockType.boulder && isOreBoulderState(block.state); |
| 939 | } |
| 940 | |
| 941 | function blockTypeAt (view, tileX, tileY) |
| 942 | { |
| 943 | return blockAt(view, tileX, tileY)?.typeId ?? null; |
| 944 | } |
| 945 | |
| 946 | function blockAt (view, tileX, tileY) |
| 947 | { |
| 948 | const chunkX = Math.floor(tileX / CHUNK_SIZE); |
| 949 | const chunkY = Math.floor(tileY / CHUNK_SIZE); |
| 950 | const snapshot = view.chunks.get(`${chunkX},${chunkY}`); |
| 951 | if (!snapshot) |
| 952 | { return null; } |
| 953 | const localX = tileX - chunkX * CHUNK_SIZE; |
| 954 | const localY = tileY - chunkY * CHUNK_SIZE; |
| 955 | return snapshot.blocks[localY * CHUNK_SIZE + localX] ?? null; |
| 956 | } |
| 957 | |
| 958 | function chebyshev (ax, ay, bx, by) |
| 959 | { |
| 960 | return Math.max(Math.abs(ax - bx), Math.abs(ay - by)); |
| 961 | } |