Files

439 lines
12 KiB
JavaScript

import { createConnection, joinStudentRoom, student } from "./net.js";
const dayText = document.getElementById("trade-day");
const fishText = document.getElementById("trade-fish");
const woodText = document.getElementById("trade-wood");
const statusText = document.getElementById("trade-status");
const foundList = document.getElementById("trade-found-list");
const offerPanel = document.getElementById("trade-offer-panel");
const offerForm = document.getElementById("trade-offer-form");
const targetSelect = document.getElementById("trade-target");
const giveFishInput = document.getElementById("trade-give-fish");
const giveWoodInput = document.getElementById("trade-give-wood");
const wantFishInput = document.getElementById("trade-want-fish");
const wantWoodInput = document.getElementById("trade-want-wood");
const offerStatus = document.getElementById("trade-offer-status");
const incomingPanel = document.getElementById("trade-incoming-panel");
const incomingList = document.getElementById("trade-incoming-list");
const outgoingPanel = document.getElementById("trade-outgoing-panel");
const outgoingList = document.getElementById("trade-outgoing-list");
const rosterPanel = document.getElementById("trade-roster-panel");
const rosterBody = document.getElementById("trade-roster-body");
const identity = student.get();
let state = null;
let connected = false;
let connection = null;
let hasRendered = false;
function setStatus(text, tone = "") {
statusText.textContent = text;
statusText.dataset.tone = tone;
}
function setOfferStatus(text, tone = "") {
offerStatus.textContent = text;
offerStatus.dataset.tone = tone;
}
function makeCell(text, className) {
const cell = document.createElement("td");
cell.textContent = text;
if (className) cell.className = className;
return cell;
}
function makePlayerRow(player) {
const row = document.createElement("tr");
row.append(
makeCell(player.name),
makeCell(String(player.fish)),
makeCell(String(player.wood)),
makeCell(player.preserver ? "Yes" : "No"),
makeCell(player.boat ? "Yes" : "No"),
);
if (!player.connected) row.classList.add("offline-player");
return row;
}
function renderRoster(players) {
rosterPanel.hidden = false;
const known = new Set(state?.you?.found ?? []);
const visible = players.filter((player) => known.has(player.name));
if (visible.length === 0) {
const row = document.createElement("tr");
const cell = makeCell(
"You have not found any castaways to trade with yet.",
"empty",
);
cell.colSpan = 5;
row.append(cell);
rosterBody.replaceChildren(row);
return;
}
rosterBody.replaceChildren(...visible.map(makePlayerRow));
}
function renderFound(found) {
if (found.length === 0) {
foundList.textContent =
"No one yet. You can only trade with castaways you found during the day.";
offerPanel.hidden = true;
return;
}
foundList.textContent = `You know: ${found.join(", ")}.`;
offerPanel.hidden = false;
const names = [...found].sort((a, b) => a.localeCompare(b));
const signature = names.join("\u0000");
if (targetSelect.dataset.signature !== signature) {
const current = targetSelect.value;
targetSelect.replaceChildren(
...names.map((name) => {
const option = document.createElement("option");
option.value = name;
option.textContent = name;
return option;
}),
);
targetSelect.dataset.signature = signature;
if (names.includes(current)) targetSelect.value = current;
}
updateTradeLimits();
}
function selectedTarget() {
if (!state?.players) return null;
return (
state.players.find((player) => player.name === targetSelect.value) ?? null
);
}
function clampAmount(input, max) {
const limit = Math.max(0, max);
input.max = String(limit);
const value = Number(input.value);
if (input.value.trim() === "" || !Number.isFinite(value)) return;
if (value > limit) input.value = String(limit);
else if (value < 0) input.value = "0";
}
function updateTradeLimits() {
const you = state?.you;
const target = selectedTarget();
clampAmount(giveFishInput, you?.fish ?? 0);
clampAmount(giveWoodInput, you?.wood ?? 0);
clampAmount(wantFishInput, target?.fish ?? 0);
clampAmount(wantWoodInput, target?.wood ?? 0);
}
targetSelect.addEventListener("change", updateTradeLimits);
for (const input of [giveFishInput, giveWoodInput, wantFishInput, wantWoodInput]) {
input.addEventListener("input", updateTradeLimits);
}
function describeItems(fish, wood) {
const parts = [];
if (fish > 0) parts.push(`${fish} fish`);
if (wood > 0) parts.push(`${wood} wood`);
return parts.length > 0 ? parts.join(" and ") : "nothing";
}
function makeOfferCard(offer) {
const card = document.createElement("article");
card.className = "offer-card";
const summary = document.createElement("p");
summary.className = "offer-summary";
if (offer.incoming) {
const who = document.createElement("strong");
who.textContent = offer.from;
summary.append(
who,
document.createTextNode(
` gives ${describeItems(offer.giveFish, offer.giveWood)} and wants ` +
`${describeItems(offer.wantFish, offer.wantWood)} from you.`,
),
);
} else {
summary.append(
document.createTextNode(
`You give ${describeItems(offer.giveFish, offer.giveWood)} to ` +
`${offer.to} and want ` +
`${describeItems(offer.wantFish, offer.wantWood)} in return.`,
),
);
}
const actions = document.createElement("div");
actions.className = "offer-actions";
if (offer.incoming) {
const accept = document.createElement("button");
accept.type = "button";
accept.className = "btn-primary btn-small";
accept.dataset.action = "accept";
accept.dataset.id = offer.id;
accept.textContent = "Accept";
const decline = document.createElement("button");
decline.type = "button";
decline.className = "btn-quiet btn-small";
decline.dataset.action = "decline";
decline.dataset.id = offer.id;
decline.textContent = "Decline";
actions.append(accept, decline);
} else {
const cancel = document.createElement("button");
cancel.type = "button";
cancel.className = "btn-quiet btn-small";
cancel.dataset.action = "cancel";
cancel.dataset.id = offer.id;
cancel.textContent = "Cancel Offer";
actions.append(cancel);
}
card.append(summary, actions);
return card;
}
function renderOffers(offers) {
const incoming = offers.filter((offer) => offer.incoming);
const outgoing = offers.filter((offer) => !offer.incoming);
incomingPanel.hidden = incoming.length === 0;
outgoingPanel.hidden = outgoing.length === 0;
incomingList.replaceChildren(...incoming.map(makeOfferCard));
outgoingList.replaceChildren(...outgoing.map(makeOfferCard));
}
function render(nextState) {
state = nextState;
dayText.textContent = String(nextState.day);
if (nextState.you) {
fishText.textContent = String(nextState.you.fish);
woodText.textContent = String(nextState.you.wood);
renderFound(nextState.you.found ?? []);
}
renderRoster(nextState.players);
renderOffers(Array.isArray(nextState.offers) ? nextState.offers : []);
if (!hasRendered) {
setStatus(
"Trading is open. Make an offer to a castaway you found during the day.",
"good",
);
hasRendered = true;
}
}
function roomProblem(message) {
student.clear();
window.alert(message || "You are no longer in that room.");
window.location.href = "/";
}
function sendAction(message) {
if (!connected) {
setStatus("Not connected yet. Please try again.", "bad");
return false;
}
if (!connection.send(message)) {
setStatus("Not connected yet. Please try again.", "bad");
return false;
}
return true;
}
function amountFrom(input) {
if (input.value.trim() === "") return 0;
const amount = Number(input.value);
return Number.isInteger(amount) && amount >= 0 ? amount : null;
}
offerForm.addEventListener("submit", (event) => {
event.preventDefault();
if (!state?.you) return;
const target = targetSelect.value;
if (!target) {
setOfferStatus("Find a castaway to trade with first.", "bad");
return;
}
const giveFish = amountFrom(giveFishInput);
const giveWood = amountFrom(giveWoodInput);
const wantFish = amountFrom(wantFishInput);
const wantWood = amountFrom(wantWoodInput);
if (
giveFish === null ||
giveWood === null ||
wantFish === null ||
wantWood === null
) {
setOfferStatus("Use whole numbers of 0 or more.", "bad");
return;
}
if (giveFish + giveWood + wantFish + wantWood === 0) {
setOfferStatus("Offer at least one fish or piece of wood.", "bad");
return;
}
const targetPlayer = selectedTarget();
if (giveFish > state.you.fish || giveWood > state.you.wood) {
setOfferStatus("You do not have enough supplies for that offer.", "bad");
return;
}
if (
targetPlayer &&
(wantFish > targetPlayer.fish || wantWood > targetPlayer.wood)
) {
setOfferStatus(
`${target} does not have enough supplies for that offer.`,
"bad",
);
return;
}
if (
sendAction({
type: "TRADE_OFFER",
to: target,
giveFish,
giveWood,
wantFish,
wantWood,
})
) {
setOfferStatus(`Offer sent to ${target}.`);
giveFishInput.value = "0";
giveWoodInput.value = "0";
wantFishInput.value = "0";
wantWoodInput.value = "0";
}
});
function handleOfferAction(event) {
const button = event.target.closest("button[data-action]");
if (!button) return;
const action = button.dataset.action;
const id = button.dataset.id;
const messages = {
accept: { type: "TRADE_ACCEPT", id, label: "Accepting the offer..." },
decline: { type: "TRADE_DECLINE", id, label: "Declining the offer..." },
cancel: { type: "TRADE_CANCEL", id, label: "Cancelling the offer..." },
};
const pending = messages[action];
if (!pending) return;
if (sendAction({ type: pending.type, id: pending.id })) {
button.disabled = true;
setOfferStatus(pending.label);
}
}
incomingList.addEventListener("click", handleOfferAction);
outgoingList.addEventListener("click", handleOfferAction);
if (!identity.name || !identity.code) {
window.location.href = "/";
} else {
connection = createConnection({
onOpen(send) {
joinStudentRoom(send);
},
onStatus(status) {
connected = status === "connected";
if (status === "connecting") {
if (!state) setStatus("Connecting...");
} else if (status === "connected") {
if (!state) setStatus("Connected. Loading the trading post...");
} else if (status === "replaced") {
student.clear();
window.alert(
"This game was opened in another tab. This tab has been disconnected.",
);
window.location.href = "/";
} else if (status === "error") {
setStatus("Connection error. Retrying...", "bad");
} else {
setStatus("Connection lost. Reconnecting...", "bad");
}
},
onMessage(data) {
if (data.type === "SYNC") {
if (data.phase === "day") {
window.location.href = "/game";
return;
}
if (data.phase === "lobby") {
window.location.href = "/waiting";
return;
}
render(data);
return;
}
if (data.type === "NOTICE") {
setStatus(data.message || "", data.tone || "");
setOfferStatus(data.message || "", data.tone || "");
return;
}
if (data.type !== "ERROR") return;
if (
data.code === "ROOM_NOT_FOUND" ||
/already in use/i.test(data.message ?? "")
) {
roomProblem(data.message);
return;
}
setStatus(data.message || "Something went wrong.", "bad");
setOfferStatus(data.message || "Something went wrong.", "bad");
},
});
}