major changes, leaving it at that
This commit is contained in:
1 parent
8cb4c3556b
commit
b55251cfc5
16 files changed
+3280
-302
No files matched your search
+271
@@ -0,0 +1,271 @@
|
||||
import { createConnection, joinStudentRoom, student } from "./net.js";
|
||||
|
||||
const statusText = document.getElementById("game-status");
|
||||
|
||||
const fishPerHour = document.getElementById("fish_p_hour");
|
||||
const woodPerHour = document.getElementById("wood_p_hour");
|
||||
const fishStored = document.getElementById("fish_stored");
|
||||
const woodStored = document.getElementById("wood_stored");
|
||||
const preserverText = document.getElementById("preserver");
|
||||
const boatText = document.getElementById("boat");
|
||||
const hoursText = document.getElementById("hours");
|
||||
const daysText = document.getElementById("days");
|
||||
const foundText = document.getElementById("found");
|
||||
|
||||
const fishButton = document.getElementById("go-fishing");
|
||||
const forageButton = document.getElementById("go-foraging");
|
||||
const discoverButton = document.getElementById("discover");
|
||||
const foundList = document.getElementById("found-list");
|
||||
const improveFishingButton = document.getElementById("improve-fishing");
|
||||
const improveForagingButton = document.getElementById("improve-foraging");
|
||||
const buildPreserverButton = document.getElementById("build-preserver");
|
||||
const buildBoatButton = document.getElementById("build-boat");
|
||||
|
||||
const identity = student.get();
|
||||
let state = null;
|
||||
let connected = false;
|
||||
let connection = null;
|
||||
|
||||
function setText(element, value) {
|
||||
if (element) element.textContent = String(value);
|
||||
}
|
||||
|
||||
function setStatus(text, tone = "") {
|
||||
if (!statusText) return;
|
||||
statusText.textContent = text;
|
||||
statusText.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function roomProblem(message) {
|
||||
student.clear();
|
||||
window.alert(message || "You are no longer in that room.");
|
||||
window.location.href = "/";
|
||||
}
|
||||
|
||||
function render(nextState) {
|
||||
state = nextState;
|
||||
|
||||
const you = nextState.you;
|
||||
setText(daysText, nextState.day);
|
||||
|
||||
if (you) {
|
||||
setText(foundText, you.found.length);
|
||||
setText(fishPerHour, you.fishingPerHour);
|
||||
setText(woodPerHour, you.foragingPerHour);
|
||||
setText(fishStored, you.fish);
|
||||
setText(woodStored, you.wood);
|
||||
setText(preserverText, you.preserver ? "Yes" : "No");
|
||||
setText(boatText, you.boat ? "Yes" : "No");
|
||||
setText(hoursText, you.hours);
|
||||
|
||||
if (foundList) {
|
||||
foundList.textContent =
|
||||
you.found.length === 0
|
||||
? "No castaways found yet. Use Discover a Castaway."
|
||||
: `Castaways you know: ${you.found.join(", ")}.`;
|
||||
}
|
||||
}
|
||||
|
||||
const active = nextState.phase === "day";
|
||||
const hours = you?.hours ?? 0;
|
||||
|
||||
if (fishButton) fishButton.disabled = !active || hours <= 0;
|
||||
if (forageButton) forageButton.disabled = !active || hours <= 0;
|
||||
|
||||
if (discoverButton) {
|
||||
const usedToday = you?.discoveryDay === nextState.day;
|
||||
const known = you?.found ?? [];
|
||||
const undiscovered = nextState.players.filter(
|
||||
(player) =>
|
||||
player.name !== you?.name && player.connected && !known.includes(player.name),
|
||||
);
|
||||
|
||||
discoverButton.disabled = !active || usedToday || undiscovered.length === 0;
|
||||
discoverButton.textContent = usedToday
|
||||
? "Found Someone Today"
|
||||
: undiscovered.length === 0
|
||||
? "No New Castaways"
|
||||
: "Discover a Castaway";
|
||||
}
|
||||
|
||||
if (improveFishingButton) improveFishingButton.disabled = !active || hours < 8;
|
||||
if (improveForagingButton)
|
||||
improveForagingButton.disabled = !active || hours < 8;
|
||||
if (buildPreserverButton) {
|
||||
buildPreserverButton.disabled =
|
||||
!active || !!you?.preserver || hours < 8 || (you?.wood ?? 0) < 25;
|
||||
}
|
||||
if (buildBoatButton) {
|
||||
buildBoatButton.disabled =
|
||||
!active || !!you?.boat || hours < 16 || (you?.wood ?? 0) < 100;
|
||||
}
|
||||
|
||||
if (!active) return;
|
||||
|
||||
if (hours <= 0) {
|
||||
setStatus(
|
||||
"You are out of hours. Waiting for the rest of the crew to finish.",
|
||||
);
|
||||
} else {
|
||||
setStatus(`Day ${nextState.day}: ${hours} hours left.`, "good");
|
||||
}
|
||||
}
|
||||
|
||||
function askHours(verb) {
|
||||
if (!state?.you) return null;
|
||||
|
||||
const hours = state.you.hours;
|
||||
|
||||
if (hours <= 0) {
|
||||
setStatus("You have no hours left today.");
|
||||
return null;
|
||||
}
|
||||
|
||||
const answer = window.prompt(
|
||||
`How many hours do you want to ${verb}? (1-${hours})`,
|
||||
);
|
||||
if (answer === null) return null;
|
||||
|
||||
const value = Number(answer);
|
||||
|
||||
if (!Number.isInteger(value) || value < 1 || value > hours) {
|
||||
setStatus(`Enter a whole number of hours between 1 and ${hours}.`, "bad");
|
||||
return null;
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
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 goFishing() {
|
||||
const hours = askHours("fish");
|
||||
if (hours === null) return;
|
||||
|
||||
if (sendAction({ type: "FISH", hours })) {
|
||||
setStatus(`Spending ${hours} hours fishing...`);
|
||||
}
|
||||
}
|
||||
|
||||
function goForaging() {
|
||||
const hours = askHours("forage");
|
||||
if (hours === null) return;
|
||||
|
||||
if (sendAction({ type: "FORAGE", hours })) {
|
||||
setStatus(`Spending ${hours} hours foraging...`);
|
||||
}
|
||||
}
|
||||
|
||||
fishButton?.addEventListener("click", goFishing);
|
||||
forageButton?.addEventListener("click", goForaging);
|
||||
|
||||
discoverButton?.addEventListener("click", () => {
|
||||
if (sendAction({ type: "DISCOVER" })) {
|
||||
discoverButton.disabled = true;
|
||||
setStatus("Searching the island for another castaway...");
|
||||
}
|
||||
});
|
||||
|
||||
improveFishingButton?.addEventListener("click", () => {
|
||||
if (sendAction({ type: "IMPROVE_FISHING" })) {
|
||||
setStatus("Spending 8 hours improving fishing...");
|
||||
}
|
||||
});
|
||||
|
||||
improveForagingButton?.addEventListener("click", () => {
|
||||
if (sendAction({ type: "IMPROVE_FORAGING" })) {
|
||||
setStatus("Spending 8 hours improving foraging...");
|
||||
}
|
||||
});
|
||||
|
||||
buildPreserverButton?.addEventListener("click", () => {
|
||||
if (sendAction({ type: "BUILD_PRESERVER" })) {
|
||||
setStatus("Spending 8 hours and 25 wood on a preserver...");
|
||||
}
|
||||
});
|
||||
|
||||
buildBoatButton?.addEventListener("click", () => {
|
||||
if (sendAction({ type: "BUILD_BOAT" })) {
|
||||
setStatus("Spending 16 hours and 100 wood on a boat...");
|
||||
}
|
||||
});
|
||||
|
||||
if (!identity.name || !identity.code) {
|
||||
window.location.href = "/";
|
||||
} else {
|
||||
setStatus("Connecting...");
|
||||
|
||||
const created = createConnection({
|
||||
onOpen(send) {
|
||||
joinStudentRoom(send);
|
||||
},
|
||||
|
||||
onStatus(status) {
|
||||
connected = status === "connected";
|
||||
|
||||
if (status === "connecting") {
|
||||
setStatus("Connecting...");
|
||||
} else if (status === "connected") {
|
||||
if (!state) setStatus("Connected. Loading the day...");
|
||||
} 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 === "lobby") {
|
||||
window.location.href = "/waiting";
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.phase === "trading") {
|
||||
window.location.href = "/trading";
|
||||
return;
|
||||
}
|
||||
|
||||
render(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "NOTICE") {
|
||||
setStatus(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");
|
||||
},
|
||||
});
|
||||
|
||||
connection = created;
|
||||
}
|
||||
+110
@@ -0,0 +1,110 @@
|
||||
import { createConnection, getClientId, student } from "./net.js";
|
||||
|
||||
const nameInput = document.getElementById("name");
|
||||
const codeInput = document.getElementById("join-code");
|
||||
const joinForm = document.getElementById("join-form");
|
||||
const joinButton = document.getElementById("join-button");
|
||||
const statusText = document.getElementById("join-status");
|
||||
|
||||
let connected = false;
|
||||
let pendingJoin = null;
|
||||
|
||||
function setStatus(text) {
|
||||
if (statusText) statusText.textContent = text;
|
||||
}
|
||||
|
||||
function updateButton() {
|
||||
joinButton.disabled = !connected || pendingJoin !== null;
|
||||
joinButton.textContent = pendingJoin
|
||||
? "Joining..."
|
||||
: connected
|
||||
? "Join as Student"
|
||||
: "Connecting...";
|
||||
}
|
||||
|
||||
function sendJoin(send) {
|
||||
if (!pendingJoin) return;
|
||||
|
||||
const sent = send({
|
||||
type: "JOIN_ROOM",
|
||||
name: pendingJoin.name,
|
||||
code: pendingJoin.code,
|
||||
clientId: getClientId(),
|
||||
});
|
||||
|
||||
if (!sent) {
|
||||
pendingJoin = null;
|
||||
updateButton();
|
||||
setStatus("Not connected yet. Please try again.");
|
||||
}
|
||||
}
|
||||
|
||||
const connection = createConnection({
|
||||
onOpen(send) {
|
||||
// If the connection dropped while joining, try again automatically.
|
||||
sendJoin(send);
|
||||
},
|
||||
|
||||
onStatus(status) {
|
||||
connected = status === "connected";
|
||||
|
||||
if (status === "connected") {
|
||||
setStatus("Connected. Enter your name and room code.");
|
||||
} else if (status === "connecting") {
|
||||
setStatus("Connecting to the game server...");
|
||||
} else if (status === "replaced") {
|
||||
setStatus("This page was replaced by another tab. Close this tab.");
|
||||
joinButton.disabled = true;
|
||||
return;
|
||||
} else if (status === "error") {
|
||||
setStatus("Connection error. Retrying...");
|
||||
} else {
|
||||
setStatus("Connection lost. Reconnecting...");
|
||||
}
|
||||
|
||||
updateButton();
|
||||
},
|
||||
|
||||
onMessage(data) {
|
||||
if (data.type === "JOIN_SUCCESS") {
|
||||
if (!pendingJoin) return;
|
||||
|
||||
student.save(pendingJoin.name, pendingJoin.code);
|
||||
window.location.href = "/waiting";
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "ERROR") {
|
||||
const message =
|
||||
data.code === "ROOM_NOT_FOUND"
|
||||
? "No room has that code. Check the code with your teacher."
|
||||
: data.message || "Could not join the room.";
|
||||
|
||||
pendingJoin = null;
|
||||
setStatus(message);
|
||||
updateButton();
|
||||
window.alert(message);
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
joinForm.addEventListener("submit", (event) => {
|
||||
event.preventDefault();
|
||||
if (!connected || pendingJoin) return;
|
||||
|
||||
const name = nameInput.value.trim();
|
||||
const code = codeInput.value.trim();
|
||||
|
||||
if (!name || !code) {
|
||||
window.alert("Please enter both your name and a room code!");
|
||||
return;
|
||||
}
|
||||
|
||||
pendingJoin = { name, code };
|
||||
updateButton();
|
||||
setStatus("Joining room " + code + "...");
|
||||
|
||||
sendJoin(connection.send);
|
||||
});
|
||||
|
||||
updateButton();
|
||||
+272
@@ -0,0 +1,272 @@
|
||||
import { createConnection, resumeTeacherRoom, teacher } from "./net.js";
|
||||
|
||||
const hostButton = document.getElementById("host-btn");
|
||||
const roomCodeText = document.getElementById("room-code");
|
||||
const statusText = document.getElementById("lobby-status");
|
||||
const rosterPanel = document.getElementById("roster-panel");
|
||||
const rosterBody = document.getElementById("roster-body");
|
||||
const playerCount = document.getElementById("player-count");
|
||||
|
||||
const phasePanel = document.getElementById("phase-panel");
|
||||
const phaseText = document.getElementById("phase-text");
|
||||
const dayText = document.getElementById("day-text");
|
||||
const phaseStatus = document.getElementById("phase-status");
|
||||
const startGameButton = document.getElementById("start-game-btn");
|
||||
const endDayButton = document.getElementById("end-day-btn");
|
||||
const nextDayButton = document.getElementById("next-day-btn");
|
||||
|
||||
let connected = false;
|
||||
let roomOpen = false;
|
||||
let creating = false;
|
||||
let resuming = false;
|
||||
let room = null;
|
||||
|
||||
const PHASE_LABELS = {
|
||||
lobby: "Lobby",
|
||||
day: "Day",
|
||||
trading: "Trading",
|
||||
};
|
||||
|
||||
function setStatus(text, tone = "") {
|
||||
statusText.textContent = text;
|
||||
statusText.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function setPhaseStatus(text, tone = "") {
|
||||
phaseStatus.textContent = text;
|
||||
phaseStatus.dataset.tone = tone;
|
||||
}
|
||||
|
||||
function updateControls() {
|
||||
if (roomOpen) {
|
||||
hostButton.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
hostButton.hidden = false;
|
||||
hostButton.disabled = !connected || creating || resuming;
|
||||
|
||||
if (resuming) {
|
||||
hostButton.textContent = "Reconnecting...";
|
||||
} else if (creating) {
|
||||
hostButton.textContent = "Creating room...";
|
||||
} else if (connected) {
|
||||
hostButton.textContent = "Create Room";
|
||||
} else {
|
||||
hostButton.textContent = "Connecting...";
|
||||
}
|
||||
}
|
||||
|
||||
function updatePhaseControls() {
|
||||
if (!room) {
|
||||
phasePanel.hidden = true;
|
||||
return;
|
||||
}
|
||||
|
||||
phasePanel.hidden = false;
|
||||
phaseText.textContent = PHASE_LABELS[room.phase] ?? room.phase;
|
||||
dayText.textContent = String(room.day);
|
||||
|
||||
const hasPlayers = room.players.length > 0;
|
||||
|
||||
startGameButton.hidden = room.phase !== "lobby";
|
||||
startGameButton.disabled = !connected || !hasPlayers;
|
||||
|
||||
endDayButton.hidden = room.phase !== "day";
|
||||
endDayButton.disabled = !connected;
|
||||
|
||||
nextDayButton.hidden = room.phase !== "trading";
|
||||
nextDayButton.disabled = !connected;
|
||||
|
||||
if (!hasPlayers && room.phase === "lobby") {
|
||||
setPhaseStatus("Waiting for at least one student before you can start.");
|
||||
} else if (room.phase === "lobby") {
|
||||
setPhaseStatus("The crew is ready when you are.");
|
||||
} else if (room.phase === "day") {
|
||||
setPhaseStatus("Students are spending their hours.");
|
||||
} else if (room.phase === "trading") {
|
||||
setPhaseStatus("Trading is open. Start the next day when ready.");
|
||||
} else {
|
||||
setPhaseStatus("");
|
||||
}
|
||||
}
|
||||
|
||||
function showRoom(code) {
|
||||
roomOpen = true;
|
||||
roomCodeText.textContent = code;
|
||||
rosterPanel.hidden = false;
|
||||
updateControls();
|
||||
}
|
||||
|
||||
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(String(player.hours)),
|
||||
makeCell(
|
||||
player.connected ? "Connected" : "Offline",
|
||||
player.connected ? "online" : "offline",
|
||||
),
|
||||
);
|
||||
return row;
|
||||
}
|
||||
|
||||
function renderRoster(players) {
|
||||
playerCount.textContent = String(players.length);
|
||||
|
||||
if (players.length === 0) {
|
||||
const row = document.createElement("tr");
|
||||
const cell = makeCell("No students have joined yet.", "empty");
|
||||
cell.colSpan = 5;
|
||||
row.append(cell);
|
||||
rosterBody.replaceChildren(row);
|
||||
return;
|
||||
}
|
||||
|
||||
rosterBody.replaceChildren(...players.map(makePlayerRow));
|
||||
}
|
||||
|
||||
function handleSync(data) {
|
||||
room = {
|
||||
phase: data.phase,
|
||||
day: data.day,
|
||||
players: Array.isArray(data.players) ? data.players : [],
|
||||
};
|
||||
|
||||
showRoom(data.code);
|
||||
renderRoster(room.players);
|
||||
updatePhaseControls();
|
||||
}
|
||||
|
||||
const connection = createConnection({
|
||||
onOpen(send) {
|
||||
const saved = teacher.get();
|
||||
|
||||
if (saved.code && saved.token) {
|
||||
resuming = true;
|
||||
updateControls();
|
||||
setStatus("Restoring your room...");
|
||||
resumeTeacherRoom(send);
|
||||
}
|
||||
},
|
||||
|
||||
onStatus(status) {
|
||||
connected = status === "connected";
|
||||
|
||||
if (status === "connected") {
|
||||
if (!roomOpen) {
|
||||
setStatus(
|
||||
resuming
|
||||
? "Restoring your room..."
|
||||
: "Connected. Create a room to begin.",
|
||||
);
|
||||
}
|
||||
} else if (status === "connecting") {
|
||||
setStatus("Connecting to the game server...");
|
||||
} else if (status === "replaced") {
|
||||
setStatus("This lobby was opened in another tab. Close this tab.");
|
||||
hostButton.disabled = true;
|
||||
return;
|
||||
} else if (status === "error") {
|
||||
setStatus("Connection error. Retrying...");
|
||||
} else {
|
||||
setStatus("Connection lost. Reconnecting...");
|
||||
}
|
||||
|
||||
updateControls();
|
||||
updatePhaseControls();
|
||||
},
|
||||
|
||||
onMessage(data) {
|
||||
if (data.type === "ROOM_CREATED") {
|
||||
teacher.save(data.code, data.token);
|
||||
creating = false;
|
||||
resuming = false;
|
||||
showRoom(data.code);
|
||||
setStatus("Room open. Share the code with your students.", "good");
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "ROOM_RESUMED") {
|
||||
creating = false;
|
||||
resuming = false;
|
||||
showRoom(data.code);
|
||||
setStatus("Room restored. Students can keep joining.", "good");
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "SYNC") {
|
||||
handleSync(data);
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "ERROR") {
|
||||
creating = false;
|
||||
resuming = false;
|
||||
|
||||
if (data.code === "ROOM_NOT_FOUND") {
|
||||
teacher.clear();
|
||||
roomOpen = false;
|
||||
room = null;
|
||||
roomCodeText.textContent = "----";
|
||||
rosterPanel.hidden = true;
|
||||
phasePanel.hidden = true;
|
||||
setStatus("That room no longer exists. Create a new one.", "bad");
|
||||
} else if (roomOpen) {
|
||||
setPhaseStatus(data.message || "Something went wrong.", "bad");
|
||||
} else {
|
||||
setStatus(data.message || "Something went wrong.", "bad");
|
||||
}
|
||||
|
||||
updateControls();
|
||||
updatePhaseControls();
|
||||
}
|
||||
},
|
||||
});
|
||||
|
||||
function sendAction(type) {
|
||||
if (!connected) return;
|
||||
|
||||
setPhaseStatus(
|
||||
type === "START_GAME"
|
||||
? "Starting the game..."
|
||||
: type === "END_DAY"
|
||||
? "Ending the day..."
|
||||
: "Starting the next day...",
|
||||
);
|
||||
|
||||
if (!connection.send({ type })) {
|
||||
setPhaseStatus("Not connected yet. Please try again.", "bad");
|
||||
}
|
||||
}
|
||||
|
||||
hostButton.addEventListener("click", () => {
|
||||
if (!connected || creating || resuming) return;
|
||||
|
||||
creating = true;
|
||||
updateControls();
|
||||
setStatus("Creating room...");
|
||||
|
||||
if (!connection.send({ type: "CREATE_ROOM" })) {
|
||||
creating = false;
|
||||
updateControls();
|
||||
setStatus("Not connected yet. Please try again.", "bad");
|
||||
}
|
||||
});
|
||||
|
||||
startGameButton.addEventListener("click", () => sendAction("START_GAME"));
|
||||
endDayButton.addEventListener("click", () => sendAction("END_DAY"));
|
||||
nextDayButton.addEventListener("click", () => sendAction("NEXT_DAY"));
|
||||
|
||||
roomCodeText.textContent = teacher.get().code || "----";
|
||||
updateControls();
|
||||
updatePhaseControls();
|
||||
+182
@@ -0,0 +1,182 @@
|
||||
// Shared browser networking for every page.
|
||||
//
|
||||
// The server is authoritative. Pages send intents (JOIN_ROOM, CREATE_ROOM,
|
||||
// PING, ...) and render what the server sends back. This file only knows about
|
||||
// transport: connection, reconnection, heartbeat, and per-tab identity.
|
||||
|
||||
const wsProtocol = location.protocol === "https:" ? "wss:" : "ws:";
|
||||
export const WS_URL = `${wsProtocol}//${location.host}/ws`;
|
||||
|
||||
export function getClientId() {
|
||||
let clientId = sessionStorage.getItem("clientId");
|
||||
|
||||
if (!clientId) {
|
||||
clientId =
|
||||
crypto.randomUUID?.() ??
|
||||
Math.random().toString(36).slice(2) + Date.now().toString(36);
|
||||
sessionStorage.setItem("clientId", clientId);
|
||||
}
|
||||
|
||||
return clientId;
|
||||
}
|
||||
|
||||
export const student = {
|
||||
get() {
|
||||
return {
|
||||
name: sessionStorage.getItem("playerName") ?? "",
|
||||
code: sessionStorage.getItem("roomCode") ?? "",
|
||||
clientId: getClientId(),
|
||||
};
|
||||
},
|
||||
|
||||
save(name, code) {
|
||||
sessionStorage.setItem("playerName", name);
|
||||
sessionStorage.setItem("roomCode", code);
|
||||
},
|
||||
|
||||
clear() {
|
||||
sessionStorage.removeItem("playerName");
|
||||
sessionStorage.removeItem("roomCode");
|
||||
},
|
||||
};
|
||||
|
||||
export const teacher = {
|
||||
get() {
|
||||
return {
|
||||
code: sessionStorage.getItem("teacherCode") ?? "",
|
||||
token: sessionStorage.getItem("teacherToken") ?? "",
|
||||
};
|
||||
},
|
||||
|
||||
save(code, token) {
|
||||
sessionStorage.setItem("teacherCode", code);
|
||||
sessionStorage.setItem("teacherToken", token);
|
||||
},
|
||||
|
||||
clear() {
|
||||
sessionStorage.removeItem("teacherCode");
|
||||
sessionStorage.removeItem("teacherToken");
|
||||
},
|
||||
};
|
||||
|
||||
// Tell the server which student this tab belongs to.
|
||||
export function joinStudentRoom(send) {
|
||||
const { name, code, clientId } = student.get();
|
||||
|
||||
if (!name || !code) {
|
||||
location.href = "/";
|
||||
return false;
|
||||
}
|
||||
|
||||
return send({ type: "JOIN_ROOM", name, code, clientId });
|
||||
}
|
||||
|
||||
// Reclaim a room the teacher already created in this tab.
|
||||
export function resumeTeacherRoom(send) {
|
||||
const { code, token } = teacher.get();
|
||||
|
||||
if (!code || !token) return false;
|
||||
|
||||
return send({ type: "RESUME_TEACHER", code, token });
|
||||
}
|
||||
|
||||
/**
|
||||
* Open a WebSocket and keep it open.
|
||||
*
|
||||
* Options:
|
||||
* onMessage(data) called for every non-PONG server message
|
||||
* onStatus(status) "connecting" | "connected" | "disconnected" |
|
||||
* "error" | "replaced"
|
||||
* onOpen(send) called after each successful (re)connection, so the page
|
||||
* can re-announce who it is
|
||||
*
|
||||
* Returns { send, close } where send() returns false when the socket is not
|
||||
* ready instead of throwing.
|
||||
*/
|
||||
export function createConnection({ onMessage, onStatus = () => {}, onOpen } = {}) {
|
||||
let socket = null;
|
||||
let heartbeat = null;
|
||||
let reconnectTimer = null;
|
||||
let reconnectDelay = 1000;
|
||||
let unloading = false;
|
||||
|
||||
window.addEventListener("beforeunload", () => {
|
||||
unloading = true;
|
||||
});
|
||||
|
||||
function send(message) {
|
||||
if (!socket || socket.readyState !== WebSocket.OPEN) return false;
|
||||
socket.send(JSON.stringify(message));
|
||||
return true;
|
||||
}
|
||||
|
||||
function connect() {
|
||||
onStatus("connecting");
|
||||
|
||||
const ws = new WebSocket(WS_URL);
|
||||
socket = ws;
|
||||
|
||||
ws.onopen = () => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
clearTimeout(reconnectTimer);
|
||||
reconnectTimer = null;
|
||||
reconnectDelay = 1000;
|
||||
|
||||
clearInterval(heartbeat);
|
||||
heartbeat = setInterval(() => {
|
||||
if (socket?.readyState === WebSocket.OPEN) {
|
||||
socket.send(JSON.stringify({ type: "PING" }));
|
||||
}
|
||||
}, 25000);
|
||||
|
||||
onStatus("connected");
|
||||
onOpen?.(send);
|
||||
};
|
||||
|
||||
ws.onmessage = (event) => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = JSON.parse(event.data);
|
||||
} catch {
|
||||
console.warn("Ignored a non-JSON server message");
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "PONG") return;
|
||||
onMessage?.(data);
|
||||
};
|
||||
|
||||
ws.onclose = (event) => {
|
||||
if (socket !== ws) return;
|
||||
|
||||
socket = null;
|
||||
clearInterval(heartbeat);
|
||||
heartbeat = null;
|
||||
|
||||
// 4000 = the server found a newer connection for this identity. Do not
|
||||
// reconnect, or two tabs will keep taking the room from each other.
|
||||
if (event.code === 4000) {
|
||||
onStatus("replaced");
|
||||
return;
|
||||
}
|
||||
|
||||
onStatus("disconnected");
|
||||
|
||||
if (unloading) return;
|
||||
|
||||
reconnectTimer = setTimeout(connect, reconnectDelay);
|
||||
reconnectDelay = Math.min(reconnectDelay * 2, 10000);
|
||||
};
|
||||
|
||||
ws.onerror = () => {
|
||||
if (socket === ws) onStatus("error");
|
||||
};
|
||||
}
|
||||
|
||||
connect();
|
||||
|
||||
return { send };
|
||||
}
|
||||
@@ -0,0 +1,438 @@
|
||||
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");
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { createConnection, joinStudentRoom, student } from "./net.js";
|
||||
|
||||
const nameText = document.getElementById("waiting-name");
|
||||
const codeText = document.getElementById("waiting-code");
|
||||
const statusText = document.getElementById("waiting-status");
|
||||
|
||||
const identity = student.get();
|
||||
|
||||
if (!identity.name || !identity.code) {
|
||||
window.location.href = "/";
|
||||
} else {
|
||||
nameText.textContent = identity.name;
|
||||
codeText.textContent = identity.code;
|
||||
|
||||
createConnection({
|
||||
onOpen(send) {
|
||||
joinStudentRoom(send);
|
||||
},
|
||||
|
||||
onStatus(status) {
|
||||
if (status === "connected") {
|
||||
setStatus("Connected. Waiting for the teacher to start...");
|
||||
} else if (status === "connecting") {
|
||||
setStatus("Connecting...");
|
||||
} else if (status === "replaced") {
|
||||
setStatus("This room was opened in another tab. You can close this tab.");
|
||||
} else if (status === "error") {
|
||||
setStatus("Connection error. Retrying...");
|
||||
} else {
|
||||
setStatus("Connection lost. Reconnecting...");
|
||||
}
|
||||
},
|
||||
|
||||
onMessage(data) {
|
||||
if (data.type === "JOIN_SUCCESS") {
|
||||
setStatus("You're in! Waiting for the teacher to start the game...");
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type === "SYNC") {
|
||||
if (data.phase === "day") {
|
||||
window.location.href = "/game";
|
||||
} else if (data.phase === "trading") {
|
||||
window.location.href = "/trading";
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (data.type !== "ERROR") return;
|
||||
|
||||
if (
|
||||
data.code === "ROOM_NOT_FOUND" ||
|
||||
/already in use/i.test(data.message ?? "")
|
||||
) {
|
||||
student.clear();
|
||||
window.alert(data.message || "You could not rejoin that room.");
|
||||
window.location.href = "/";
|
||||
return;
|
||||
}
|
||||
|
||||
setStatus(data.message || "Something went wrong.");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
function setStatus(text) {
|
||||
statusText.textContent = text;
|
||||
}
|
||||
Reference in new issue
Block a user