diff --git a/assets/boat-small.png b/assets/boat-small.png new file mode 100644 index 0000000..aa18569 Binary files /dev/null and b/assets/boat-small.png differ diff --git a/client/game.js b/client/game.js new file mode 100644 index 0000000..eb2aaf4 --- /dev/null +++ b/client/game.js @@ -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; +} diff --git a/client/join.js b/client/join.js new file mode 100644 index 0000000..dcea0c0 --- /dev/null +++ b/client/join.js @@ -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(); diff --git a/client/lobby.js b/client/lobby.js new file mode 100644 index 0000000..ec31da4 --- /dev/null +++ b/client/lobby.js @@ -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(); diff --git a/client/net.js b/client/net.js new file mode 100644 index 0000000..d526cd9 --- /dev/null +++ b/client/net.js @@ -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 }; +} diff --git a/client/trading.js b/client/trading.js new file mode 100644 index 0000000..e632780 --- /dev/null +++ b/client/trading.js @@ -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"); + }, + }); +} diff --git a/client/waiting.js b/client/waiting.js new file mode 100644 index 0000000..35f36cc --- /dev/null +++ b/client/waiting.js @@ -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; +} diff --git a/game.html b/game.html index 979154c..cd256df 100644 --- a/game.html +++ b/game.html @@ -17,7 +17,7 @@

Escape the Island

- +
@@ -84,6 +84,9 @@ +

+ Connecting... +

@@ -115,6 +118,7 @@
+
@@ -123,19 +127,20 @@ -
+

No castaways found yet.

Gamemaker: Mr. J. Walla ~=~ Developer: Andrew H. ~=~ Designer: Logan C.

- + diff --git a/index.html b/index.html index 2a81a9e..4f43d5c 100644 --- a/index.html +++ b/index.html @@ -2,6 +2,7 @@ Escape the Island + @@ -10,61 +11,70 @@ href="https://fonts.googleapis.com/css2?family=Almendra:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" /> - - +

Escape the Island

- +
-
-
- - -
- +
+
+

Join The Expedition

+

Join the crew

+

+ Enter your name and the room code from your teacher. You will wait on + the shore until the game begins. +

+ +
+
+ + +
+ +

+ Connecting... +

+ + + +

+ No downloads needed. Just join from your browser and wait for your + teacher to start the day. +

+
-

+

Gamemaker: Mr. J. Walla ~=~ Developer: Andrew H. ~=~ Designer: Logan C.

- + diff --git a/index.js b/index.js deleted file mode 100644 index 11e318c..0000000 --- a/index.js +++ /dev/null @@ -1,168 +0,0 @@ -function create_player_stats() { - let x = Math.floor(Math.random() * 2) + 1; - let y = 0; - if (x == 1) { - y = 2; - } else { - y = 1; - } - return { x: x, y: y }; -} - -let x, y; -function init() { - if (localStorage.getItem("player_x")) { - x = parseInt(localStorage.getItem("player_x")); - y = parseInt(localStorage.getItem("player_y")); - } else { - let player = create_player_stats(); - x = player.x; - y = player.y; - localStorage.setItem("player_x", x); - localStorage.setItem("player_y", y); - } - return { x: x, y: y }; -} -let player = init(); -let gamedata = { - fishing: { - per_hour: player.x, - preserver: "No", - stored: 0, - }, - foraging: { - per_hour: player.y, - boat: "No", - stored: 0, - }, - hours: 16, - days: 0, -}; - -function updateTable() { - if (document.getElementById("fish_p_hour")) { - document.getElementById("fish_p_hour").innerText = - gamedata.fishing.per_hour; - document.getElementById("wood_p_hour").innerText = - gamedata.foraging.per_hour; - document.getElementById("fish_stored").innerText = gamedata.fishing.stored; - document.getElementById("wood_stored").innerText = gamedata.foraging.stored; - document.getElementById("preserver").innerText = gamedata.fishing.preserver; - document.getElementById("boat").innerText = gamedata.foraging.boat; - document.getElementById("hours").innerText = gamedata.hours; - document.getElementById("days").innerText = gamedata.days; - if (gamedata.hours < 8) { - document.getElementById("improve-fishing").disabled = true; - } else { - document.getElementById("improve-fishing").disabled = false; - } - if (gamedata.hours < 8) { - document.getElementById("improve-forgaing").disabled = true; - } else { - document.getElementById("improve-forgaing").disabled = false; - } - if (gamedata.foraging.stored < 25 || gamedata.hours < 8) { - document.getElementById("build-preserver").disabled = true; - } else { - document.getElementById("build-preserver").disabled = false; - } - if (gamedata.foraging.stored < 100 || gamedata.hours < 16) { - document.getElementById("build-boat").disabled = true; - } else { - document.getElementById("build-boat").disabled = false; - } - } -} - -function go_fishing() { - let prompt = window.prompt("How many hours do you want to fish?"); - if (prompt === null || prompt > gamedata.hours) { - window.alert("You dont have the hours for this or prompt exited"); - console.log("Prompt Exited"); - } else { - gamedata.fishing.stored += prompt * gamedata.fishing.per_hour; - gamedata.hours -= prompt; - if (gamedata.hours === 0) { - gamedata.days++; - gamedata.hours = 16; - } - updateTable(); - } -} - -function go_foraging() { - let prompt = window.prompt("How many hours do you want to foraging?"); - if (prompt === null || prompt > gamedata.hours) { - window.alert("You dont have the hours for this or prompt exited"); - console.log("Prompt Exited"); - } else { - gamedata.foraging.stored += prompt * gamedata.foraging.per_hour; - gamedata.hours -= prompt; - if (gamedata.hours === 0) { - gamedata.days++; - gamedata.hours = 16; - } - updateTable(); - } -} -if (document.getElementById("go-fishing")) { - document.getElementById("go-fishing").onclick = go_fishing; - document.getElementById("go-foraging").onclick = go_foraging; -} - -const ws = new WebSocket(`ws://${window.location.host}/ws`); -let isConnected = false; - -ws.onopen = () => { - console.log("Connected to the game server!"); - isConnected = true; -}; - -ws.onmessage = (event) => { - const data = JSON.parse(event.data); - if (data.type === "ROOM_CREATED") { - document.getElementById("teacher-display").innerText = - `Room Code: ${data.code}`; - hostBtn.disabled = true; - // hostBtn.style.opacity = "0."; - hostBtn.innerText = "Room Active"; - } else if (data.type === "JOIN_SUCCESS") { - window.alert("Joined Room Successfully"); - // TODO: update a player table on the teacher dashboard here - } else if (data.type === "UPDATE_PLAYERS") { - console.log("Current players in room:", data.players); - } else if (data.type === "ERROR") { - window.alert(data.message); - } -}; - -const hostBtn = document.getElementById("host-btn"); -if (hostBtn) { - hostBtn.onclick = () => { - ws.send(JSON.stringify({ type: "CREATE_ROOM" })); - }; -} - -const joinBtn = document.getElementById("join-button"); -if (joinBtn) { - joinBtn.onclick = () => { - const name = document.getElementById("name").value.trim(); - const code = document.getElementById("join-code").value.trim(); - - if (!name || !code) { - window.alert("Please enter both your and a room code!"); - return; - } - localStorage.setItem("playerName", name); - localStorage.setItem("roomCode", code); - window.location.href = "/waiting"; - ws.send( - JSON.stringify({ - type: "JOIN_ROOM", - name: name, - code: code, - }), - ); - }; -} -updateTable(); diff --git a/index.ts b/index.ts index 9d0d971..d95cbb8 100644 --- a/index.ts +++ b/index.ts @@ -1,14 +1,56 @@ interface WebSocketData { - role: "teacher" | "student"; - roomCode: string; -} -interface Player { - name: string; - fish: number; - wood: number; + role: "teacher" | "student" | "unknown"; + roomCode: string | null; + name?: string; } -const rooms = new Map }>(); +type Phase = "lobby" | "day" | "trading"; + +interface Player { + name: string; + clientId: string; + ws: any | null; + fish: number; + wood: number; + fishingPerHour: number; + foragingPerHour: number; + hours: number; + preserver: boolean; + boat: boolean; + pendingFishing: number; + pendingForaging: number; + found: Set; + discoveryDay: number; +} + +interface TradeOffer { + id: string; + from: string; + to: string; + giveFish: number; + giveWood: number; + wantFish: number; + wantWood: number; +} + +type Room = { + code: string; + teacherWs: any | null; + teacherToken: string; + players: Map; + phase: Phase; + day: number; + offers: Map; +}; + +const IMPROVE_HOURS = 8; +const PRESERVER_HOURS = 8; +const PRESERVER_WOOD = 25; +const BOAT_HOURS = 16; +const BOAT_WOOD = 100; + +const rooms = new Map(); + const pages: Record = { "/": "index.html", "/host": "lobby.html", @@ -21,18 +63,483 @@ const pages: Record = { async function serveFile(path: string): Promise { const file = Bun.file(path); - if (await file.exists()) return new Response(file); - return new Response("Not Found", { status: 404 }); + if (!(await file.exists())) return new Response("Not Found", { status: 404 }); + + const headers: Record = { + "Content-Type": file.type || "application/octet-stream", + }; + + // Pages and scripts change while developing, so don't let the browser serve + // a stale copy. Images can still be cached normally. + if (/\.(html|css|js)$/.test(path)) { + headers["Cache-Control"] = "no-store"; + } + + return new Response(file, { headers }); } + +function safeSend(ws: any | null, message: unknown): boolean { + if (!ws) return false; + + try { + ws.send(JSON.stringify(message)); + return true; + } catch { + return false; + } +} + +function sendError(ws: any, message: string, code?: string) { + const payload: Record = { type: "ERROR", message }; + if (code) payload.code = code; + safeSend(ws, payload); +} + +function playerView(player: Player, room: Room) { + return { + name: player.name, + fish: player.fish, + wood: player.wood, + hours: player.hours, + fishingPerHour: player.fishingPerHour, + foragingPerHour: player.foragingPerHour, + preserver: player.preserver, + boat: player.boat, + pendingFishing: player.pendingFishing, + pendingForaging: player.pendingForaging, + found: Array.from(player.found, (key) => room.players.get(key)?.name ?? key), + discoveryDay: player.discoveryDay, + connected: player.ws !== null, + }; +} + +// Trade offers are only sent to the two students involved. The teacher still +// sees the roster but not the private offers. +function offersFor(room: Room, playerKey: string) { + const nameOf = (key: string) => room.players.get(key)?.name ?? key; + + return Array.from(room.offers.values()) + .filter((offer) => offer.from === playerKey || offer.to === playerKey) + .map((offer) => ({ + id: offer.id, + from: nameOf(offer.from), + to: nameOf(offer.to), + giveFish: offer.giveFish, + giveWood: offer.giveWood, + wantFish: offer.wantFish, + wantWood: offer.wantWood, + incoming: offer.to === playerKey, + })); +} + +function notify(ws: any | null, message: string, tone = "") { + safeSend(ws, { type: "NOTICE", message, tone }); +} + +// Send the authoritative room state to the teacher and every student. +// Each student gets the same roster plus their own `you` object and any trade +// offers they are involved in. +function broadcastSync(room: Room) { + const players = Array.from(room.players.values()).map((player) => + playerView(player, room), + ); + const base = { + type: "SYNC", + code: room.code, + phase: room.phase, + day: room.day, + players, + }; + + if ( + room.teacherWs && + !safeSend(room.teacherWs, { ...base, you: null, offers: [] }) + ) { + room.teacherWs = null; + } + + for (const [key, player] of room.players) { + if (!player.ws) continue; + + const payload = { + ...base, + you: playerView(player, room), + offers: offersFor(room, key), + }; + + if (!safeSend(player.ws, payload)) { + player.ws = null; + } + } +} + +function createPlayer( + name: string, + clientId: string, + ws: any, + room: Room, +): Player { + const first = Math.floor(Math.random() * 2) + 1; + + return { + name, + clientId, + ws, + fish: 0, + wood: 0, + fishingPerHour: first, + foragingPerHour: first === 1 ? 2 : 1, + hours: room.phase === "trading" ? 0 : 16, + preserver: false, + boat: false, + pendingFishing: 0, + pendingForaging: 0, + found: new Set(), + discoveryDay: 0, + }; +} + +function teacherRoom(ws: any): Room | null { + if (ws.data.role !== "teacher" || !ws.data.roomCode) return null; + + const room = rooms.get(ws.data.roomCode); + if (!room || room.teacherWs !== ws) return null; + + return room; +} + +function studentInRoom( + ws: any, +): { room: Room; player: Player; key: string } | null { + if (ws.data.role !== "student" || !ws.data.roomCode || !ws.data.name) { + return null; + } + + const room = rooms.get(ws.data.roomCode); + if (!room) return null; + + const key = ws.data.name.toLowerCase(); + const player = room.players.get(key); + if (!player || player.ws !== ws) return null; + + return { room, player, key }; +} + +function startGame(room: Room) { + room.phase = "day"; + room.day = 1; + + for (const player of room.players.values()) { + player.hours = 16; + } + + console.log(`Room ${room.code}: day 1 started`); + broadcastSync(room); +} + +function endDay(room: Room) { + room.phase = "trading"; + console.log(`Room ${room.code}: day ${room.day} ended, trading open`); + broadcastSync(room); +} + +function startNextDay(room: Room) { + room.day += 1; + room.phase = "day"; + room.offers.clear(); + + for (const player of room.players.values()) { + player.hours = 16; + player.fishingPerHour += player.pendingFishing; + player.foragingPerHour += player.pendingForaging; + player.pendingFishing = 0; + player.pendingForaging = 0; + } + + console.log(`Room ${room.code}: day ${room.day} started`); + broadcastSync(room); +} + +// If every connected student has spent all their hours, open trading +// automatically. Returns true when it changed the phase. +function checkAutoEndDay(room: Room): boolean { + if (room.phase !== "day") return false; + + const active = Array.from(room.players.values()).filter( + (player) => player.ws !== null, + ); + + if (active.length === 0) return false; + if (!active.every((player) => player.hours <= 0)) return false; + + room.phase = "trading"; + console.log( + `Room ${room.code}: every connected player is out of hours; trading open`, + ); + broadcastSync(room); + return true; +} + +function finishAction(room: Room) { + if (!checkAutoEndDay(room)) broadcastSync(room); +} + +function parseAmount(value: unknown): number | null { + const amount = Number(value ?? 0); + return Number.isInteger(amount) && amount >= 0 ? amount : null; +} + +function findOfferBetween( + room: Room, + a: string, + b: string, +): TradeOffer | undefined { + for (const offer of room.offers.values()) { + if ( + (offer.from === a && offer.to === b) || + (offer.from === b && offer.to === a) + ) { + return offer; + } + } + return undefined; +} + +function handleDiscover( + ws: any, + room: Room, + player: Player, + key: string, +) { + if (room.phase !== "day") { + sendError(ws, "You can only explore during the day."); + return; + } + + if (player.discoveryDay === room.day) { + sendError(ws, "You already found someone today."); + return; + } + + const candidates = Array.from(room.players.entries()).filter( + ([otherKey, other]) => + otherKey !== key && other.ws !== null && !player.found.has(otherKey), + ); + + if (candidates.length === 0) { + const connectedOthers = Array.from(room.players.entries()).filter( + ([otherKey, other]) => otherKey !== key && other.ws !== null, + ); + + sendError( + ws, + connectedOthers.length === 0 + ? "No other castaways are online right now." + : "You have already found every online castaway.", + ); + return; + } + + const picked = candidates[Math.floor(Math.random() * candidates.length)]; + if (!picked) return; + + const [otherKey, other] = picked; + + player.found.add(otherKey); + other.found.add(key); + player.discoveryDay = room.day; + + broadcastSync(room); + notify(ws, `You found ${other.name}!`, "good"); + notify( + other.ws, + `${player.name} found you. You can now trade with each other.`, + "good", + ); +} + +function handleTradeOffer( + ws: any, + room: Room, + player: Player, + key: string, + data: any, +) { + if (room.phase !== "trading") { + sendError(ws, "Trading is only open after the day ends."); + return; + } + + const targetName = String(data.to || "").trim(); + const targetKey = targetName.toLowerCase(); + const target = room.players.get(targetKey); + + if (!target || targetKey === key) { + sendError(ws, "That castaway is not in this room."); + return; + } + + if (!player.found.has(targetKey)) { + sendError(ws, "You can only trade with a castaway you have found."); + return; + } + + if (!target.ws) { + sendError(ws, `${target.name} is offline right now.`); + return; + } + + const giveFish = parseAmount(data.giveFish); + const giveWood = parseAmount(data.giveWood); + const wantFish = parseAmount(data.wantFish); + const wantWood = parseAmount(data.wantWood); + + if ( + giveFish === null || + giveWood === null || + wantFish === null || + wantWood === null + ) { + sendError(ws, "Trade amounts must be whole numbers of 0 or more."); + return; + } + + if (giveFish + giveWood + wantFish + wantWood === 0) { + sendError(ws, "Offer at least one fish or piece of wood."); + return; + } + + if (player.fish < giveFish || player.wood < giveWood) { + sendError(ws, "You do not have enough supplies for that offer."); + return; + } + + if (target.fish < wantFish || target.wood < wantWood) { + sendError(ws, `${target.name} does not have enough supplies for that offer.`); + return; + } + + if (findOfferBetween(room, key, targetKey)) { + sendError(ws, "There is already a pending offer between you two."); + return; + } + + const offer: TradeOffer = { + id: crypto.randomUUID(), + from: key, + to: targetKey, + giveFish, + giveWood, + wantFish, + wantWood, + }; + + room.offers.set(offer.id, offer); + broadcastSync(room); + notify(ws, `Offer sent to ${target.name}.`); + notify(target.ws, `Offer from ${player.name}. Check the trading post.`); +} + +function handleTradeAccept( + ws: any, + room: Room, + player: Player, + key: string, + data: any, +) { + if (room.phase !== "trading") { + sendError(ws, "Trading is only open after the day ends."); + return; + } + + const offer = room.offers.get(String(data.id || "")); + if (!offer || offer.to !== key) { + sendError(ws, "That offer is no longer available."); + return; + } + + const fromPlayer = room.players.get(offer.from); + if (!fromPlayer) { + room.offers.delete(offer.id); + broadcastSync(room); + sendError(ws, "That castaway is no longer in the room."); + return; + } + + if ( + fromPlayer.fish < offer.giveFish || + fromPlayer.wood < offer.giveWood || + player.fish < offer.wantFish || + player.wood < offer.wantWood + ) { + sendError(ws, "That offer can no longer be completed. Ask for a new one."); + return; + } + + fromPlayer.fish -= offer.giveFish; + fromPlayer.wood -= offer.giveWood; + player.fish += offer.giveFish; + player.wood += offer.giveWood; + player.fish -= offer.wantFish; + player.wood -= offer.wantWood; + fromPlayer.fish += offer.wantFish; + fromPlayer.wood += offer.wantWood; + + room.offers.delete(offer.id); + broadcastSync(room); + notify(ws, `Trade complete with ${fromPlayer.name}.`, "good"); + notify(fromPlayer.ws, `Trade complete with ${player.name}.`, "good"); +} + +function handleTradeDecline( + ws: any, + room: Room, + player: Player, + key: string, + data: any, +) { + const offer = room.offers.get(String(data.id || "")); + if (!offer || offer.to !== key) { + sendError(ws, "That offer is no longer available."); + return; + } + + const fromPlayer = room.players.get(offer.from); + room.offers.delete(offer.id); + broadcastSync(room); + notify(ws, "Offer declined."); + notify(fromPlayer?.ws ?? null, `${player.name} declined your offer.`); +} + +function handleTradeCancel( + ws: any, + room: Room, + player: Player, + key: string, + data: any, +) { + const offer = room.offers.get(String(data.id || "")); + if (!offer || offer.from !== key) { + sendError(ws, "That offer is no longer available."); + return; + } + + const target = room.players.get(offer.to); + room.offers.delete(offer.id); + broadcastSync(room); + notify(ws, "Offer cancelled."); + notify(target?.ws ?? null, `${player.name} cancelled their offer.`); +} + const server = Bun.serve({ - port: 3000, + port: Number(process.env.PORT ?? 3000), async fetch(req, server) { const url = new URL(req.url); console.log(req.method, url.pathname); if (url.pathname === "/ws") { - if (server.upgrade(req, { data: { role: "student", roomCode: "" } })) + if (server.upgrade(req, { data: { role: "unknown", roomCode: null } })) return; return new Response("WebSocket upgrade failed", { status: 400 }); } @@ -50,9 +557,7 @@ const server = Bun.serve({ return serveFile("." + url.pathname); } - if (url.pathname === "/styles.css") - return new Response(Bun.file("styles.css")); - if (url.pathname === "/index.js") return new Response(Bun.file("index.js")); + if (url.pathname === "/styles.css") return serveFile("styles.css"); if (url.pathname == "/api/health") { return Response.json({ ok: true, time: Date.now() }); } @@ -62,84 +567,375 @@ const server = Bun.serve({ return new Response("Not Found", { status: 404 }); }, websocket: { - open(ws) { + open() { console.log("A client connect via websocket!"); }, message(ws, message) { const text = typeof message === "string" ? message : message.toString(); - console.log("recv:", text); let data: any; try { data = JSON.parse(text); } catch { - ws.send(JSON.stringify({ type: "ERROR", messsage: "Invalid JSON" })); + sendError(ws, "Invalid JSON"); return; } + if (data.type === "PING") { + safeSend(ws, { type: "PONG" }); + return; + } + + console.log("recv:", text); + if (data.type === "ECHO") { - ws.send(JSON.stringify({ type: "ECHO", text: data.text })); + safeSend(ws, { type: "ECHO", text: data.text }); return; } - // const data = JSON.parse(message as string); if (data.type === "CREATE_ROOM") { - const roomCode = Math.floor(1000 + Math.random() * 9000).toString(); - - rooms.set(roomCode, { - teacherWs: ws, - players: new Map(), - }); - - ws.data = { role: "teacher", roomCode }; - ws.send(JSON.stringify({ type: "ROOM_CREATED", code: roomCode })); - console.log(`Teacher created room: ${roomCode}`); - } else if (data.type === "JOIN_ROOM") { - const room = rooms.get(data.code); - if (!room) { - ws.send( - JSON.stringify({ type: "ERROR", message: "Room not found!" }), - ); + if (ws.data.roomCode) { + sendError(ws, "Already in a room"); return; } - room.players.set(ws, { name: data.name, fish: 0, wood: 0 }); - ws.data = { role: "student", roomCode: data.code }; + let roomCode = ""; - ws.send(JSON.stringify({ type: "JOIN_SUCCESS" })); + do { + roomCode = Math.floor(1000 + Math.random() * 9000).toString(); + } while (rooms.has(roomCode)); - console.log(`Student ${data.name} joined room ${data.code}`); - updateTeachersDashboard(room); + const teacherToken = crypto.randomUUID(); + const room: Room = { + code: roomCode, + teacherWs: ws, + teacherToken, + players: new Map(), + phase: "lobby", + day: 0, + offers: new Map(), + }; + + rooms.set(roomCode, room); + ws.data = { role: "teacher", roomCode }; + + safeSend(ws, { + type: "ROOM_CREATED", + code: roomCode, + token: teacherToken, + }); + broadcastSync(room); + console.log(`Teacher created room: ${roomCode}`); + return; + } + + if (data.type === "RESUME_TEACHER") { + const code = String(data.code || "").trim(); + const token = String(data.token || "").trim(); + + if (!code || !token) { + sendError(ws, "Code and token required"); + return; + } + + const room = rooms.get(code); + if (!room) { + sendError(ws, "Room not found", "ROOM_NOT_FOUND"); + return; + } + + if (room.teacherToken !== token) { + sendError(ws, "Not allowed to resume that room"); + return; + } + + if (room.teacherWs && room.teacherWs !== ws) { + try { + room.teacherWs.close(4000, "Replaced by newer connection"); + } catch {} + } + + room.teacherWs = ws; + ws.data = { role: "teacher", roomCode: code }; + safeSend(ws, { type: "ROOM_RESUMED", code }); + broadcastSync(room); + console.log(`Teacher resumed room: ${code}`); + return; + } + + if (data.type === "JOIN_ROOM") { + const code = String(data.code || "").trim(); + const name = String(data.name || "").trim(); + const clientId = String(data.clientId || "").trim(); + + if (!code || !name || !clientId) { + sendError(ws, "Name, code and clientId required"); + return; + } + + const room = rooms.get(code); + if (!room) { + sendError(ws, "Room not found!", "ROOM_NOT_FOUND"); + return; + } + + const key = name.toLowerCase(); + const existing = room.players.get(key); + + if (existing) { + if (existing.clientId === clientId) { + if (existing.ws && existing.ws !== ws) { + try { + existing.ws.close(4000, "Replaced by newer connection"); + } catch {} + } + + existing.ws = ws; + ws.data = { role: "student", roomCode: code, name: existing.name }; + safeSend(ws, { type: "JOIN_SUCCESS", rejoined: true }); + console.log(`Student ${existing.name} rejoined room ${code}`); + broadcastSync(room); + return; + } + + if (!existing.ws) { + existing.ws = ws; + existing.clientId = clientId; + ws.data = { role: "student", roomCode: code, name: existing.name }; + safeSend(ws, { type: "JOIN_SUCCESS", rejoined: true }); + console.log(`Student ${existing.name} took over room ${code}`); + broadcastSync(room); + return; + } + + sendError(ws, "That name is already in use in another tab"); + return; + } + + const player = createPlayer(name, clientId, ws, room); + room.players.set(key, player); + ws.data = { role: "student", roomCode: code, name }; + safeSend(ws, { type: "JOIN_SUCCESS" }); + console.log(`Student ${name} joined room ${code}`); + broadcastSync(room); + return; + } + + if ( + data.type === "START_GAME" || + data.type === "END_DAY" || + data.type === "NEXT_DAY" + ) { + const room = teacherRoom(ws); + + if (!room) { + sendError(ws, "Only the teacher can control the game."); + return; + } + + if (data.type === "START_GAME") { + if (room.phase !== "lobby") { + sendError(ws, "The game has already started."); + } else if (room.players.size === 0) { + sendError(ws, "Wait for at least one student to join."); + } else { + startGame(room); + } + return; + } + + if (data.type === "END_DAY") { + if (room.phase !== "day") { + sendError(ws, "The game is not in a day phase."); + } else { + endDay(room); + } + return; + } + + if (room.phase !== "trading") { + sendError(ws, "The game is not in the trading phase."); + } else { + startNextDay(room); + } + return; + } + + if ( + data.type === "FISH" || + data.type === "FORAGE" || + data.type === "IMPROVE_FISHING" || + data.type === "IMPROVE_FORAGING" || + data.type === "BUILD_PRESERVER" || + data.type === "BUILD_BOAT" + ) { + const student = studentInRoom(ws); + + if (!student) { + sendError(ws, "You are not in a room."); + return; + } + + const { room, player } = student; + + if (room.phase !== "day") { + sendError(ws, "The day is not active."); + return; + } + + if (data.type === "FISH" || data.type === "FORAGE") { + if (player.hours <= 0) { + sendError(ws, "You have no hours left today."); + return; + } + + const hours = Number(data.hours); + + if ( + !Number.isInteger(hours) || + hours < 1 || + hours > player.hours + ) { + sendError(ws, `Choose between 1 and ${player.hours} hours.`); + return; + } + + if (data.type === "FISH") { + player.fish += hours * player.fishingPerHour; + } else { + player.wood += hours * player.foragingPerHour; + } + + player.hours -= hours; + finishAction(room); + return; + } + + if ( + data.type === "IMPROVE_FISHING" || + data.type === "IMPROVE_FORAGING" + ) { + if (player.hours < IMPROVE_HOURS) { + sendError( + ws, + `Improving a skill costs ${IMPROVE_HOURS} hours.`, + ); + return; + } + + player.hours -= IMPROVE_HOURS; + + if (data.type === "IMPROVE_FISHING") { + player.pendingFishing += 1; + } else { + player.pendingForaging += 1; + } + + finishAction(room); + return; + } + + if (data.type === "BUILD_PRESERVER") { + if (player.preserver) { + sendError(ws, "You already have a preserver."); + } else if (player.hours < PRESERVER_HOURS) { + sendError( + ws, + `Building a preserver costs ${PRESERVER_HOURS} hours.`, + ); + } else if (player.wood < PRESERVER_WOOD) { + sendError( + ws, + `Building a preserver costs ${PRESERVER_WOOD} wood.`, + ); + } else { + player.hours -= PRESERVER_HOURS; + player.wood -= PRESERVER_WOOD; + player.preserver = true; + finishAction(room); + } + return; + } + + if (data.type === "BUILD_BOAT") { + if (player.boat) { + sendError(ws, "You already have a boat."); + } else if (player.hours < BOAT_HOURS) { + sendError(ws, `Building a boat costs ${BOAT_HOURS} hours.`); + } else if (player.wood < BOAT_WOOD) { + sendError(ws, `Building a boat costs ${BOAT_WOOD} wood.`); + } else { + player.hours -= BOAT_HOURS; + player.wood -= BOAT_WOOD; + player.boat = true; + finishAction(room); + } + return; + } + } + + if ( + data.type === "DISCOVER" || + data.type === "TRADE_OFFER" || + data.type === "TRADE_ACCEPT" || + data.type === "TRADE_DECLINE" || + data.type === "TRADE_CANCEL" + ) { + const student = studentInRoom(ws); + + if (!student) { + sendError(ws, "You are not in a room."); + return; + } + + const { room, player, key } = student; + + if (data.type === "DISCOVER") { + handleDiscover(ws, room, player, key); + } else if (data.type === "TRADE_OFFER") { + handleTradeOffer(ws, room, player, key, data); + } else if (data.type === "TRADE_ACCEPT") { + handleTradeAccept(ws, room, player, key, data); + } else if (data.type === "TRADE_DECLINE") { + handleTradeDecline(ws, room, player, key, data); + } else { + handleTradeCancel(ws, room, player, key, data); + } + return; } }, close(ws) { - if (!ws.data) return; + if (!ws.data || !ws.data.roomCode) return; + const room = rooms.get(ws.data.roomCode); - if (room) { - if (ws.data.role === "teacher") { - rooms.delete(ws.data.roomCode); - console.log(`Room ${ws.data.roomCode} closed by teacher.`); - } else if (ws.data.role === "student") { - room.players.delete(ws); - updateTeachersDashboard(room); + if (!room) return; + + if (ws.data.role === "teacher") { + if (room.teacherWs === ws) { + room.teacherWs = null; + console.log(`Teacher disconnected from room ${ws.data.roomCode}`); } + return; } + + if (ws.data.role === "student" && ws.data.name) { + const key = ws.data.name.toLowerCase(); + const player = room.players.get(key); + + if (player && player.ws === ws) { + player.ws = null; + console.log( + `Student ${player.name} disconnected from room ${ws.data.roomCode}`, + ); + + if (!checkAutoEndDay(room)) broadcastSync(room); + } + return; + } + console.log("A client disconnected"); }, }, }); -function updateTeachersDashboard(room: { - teacherWs: any; - players: Map; -}) { - const playerList = Array.from(room.players.values()); - room.teacherWs.send( - JSON.stringify({ - type: "UPDATES_PLAYERS", - players: playerList, - }), - ); -} - console.log(`Listening on ${server.url}`); diff --git a/lobby.html b/lobby.html index ab4e074..6a95b01 100644 --- a/lobby.html +++ b/lobby.html @@ -2,6 +2,7 @@ Escape the Island + @@ -11,22 +12,91 @@ rel="stylesheet" /> - +

Escape the Island

- +
+
+
+

Teacher Console

+

Room Code

+

----

+

+ Connecting... +

+ +

+ Students open this same address, enter a name, and use the code + above. +

+
+ + +
+ + + + + + + + + + + + + + +
NameFishWoodHoursStatus
+ No students have joined yet. +
+
+ +
+ diff --git a/styles.css b/styles.css index 412f72f..2dd5b09 100644 --- a/styles.css +++ b/styles.css @@ -167,3 +167,730 @@ footer { text-align: center; border-top: 2px dashed gray; } + +/* ---- Page shell: join, waiting, lobby, trading ---- */ + +body.page { + display: flex; + flex-direction: column; + min-height: calc(100vh - 40px); + background: + radial-gradient( + circle at 15% 0%, + rgba(255, 228, 181, 0.22), + transparent 38% + ), + cadetblue; +} + +body.page .Content { + flex: 1; + width: 100%; + max-width: 1024px; + margin: 0 auto; + padding: clamp(12px, 2vw, 20px) 10px 0; + box-sizing: border-box; +} + +body.page-join .Content, +body.page-waiting .Content { + max-width: 760px; +} + +.panel { + position: relative; + margin: 0 0 16px; + padding: clamp(16px, 2.6vw, 24px); + background-color: moccasin; + background-image: radial-gradient( + circle at top left, + rgba(255, 255, 255, 0.35), + transparent 55% + ); + border: 2px dashed gray; + border-radius: 14px; + box-shadow: 0 6px 0 rgba(0, 0, 0, 0.18); + color: #2b2b2b; +} + +.panel::before { + content: ""; + position: absolute; + inset: 8px; + border: 1px solid rgba(105, 105, 105, 0.22); + border-radius: 9px; + pointer-events: none; +} + +.eyebrow { + margin: 0 0 6px; + font-size: 13px; + font-weight: 700; + letter-spacing: 0.18em; + text-transform: uppercase; + color: #7a6242; +} + +.panel h2 { + margin: 0 0 8px; + font-size: clamp(26px, 3.4vw, 34px); + line-height: 1.05; + color: #2f4f4f; +} + +.panel-subtitle { + margin: 0 0 16px; + font-size: clamp(16px, 1.9vw, 18px); + line-height: 1.45; + color: #4d4d4d; +} + +.panel-footnote { + margin: 14px 0 0; + padding-top: 10px; + border-top: 1px dashed rgba(105, 105, 105, 0.45); + font-size: 15px; + line-height: 1.4; + color: #6b5a3e; +} + +.room-code { + margin: 4px 0 14px; + padding: 6px 0; + font-size: clamp(42px, 9vw, 64px); + font-weight: 700; + line-height: 1; + letter-spacing: 0.16em; + text-align: center; + color: cornflowerblue; + text-shadow: 2px 2px 0 rgba(47, 79, 79, 0.18); + word-break: break-word; +} + +.lobby-status { + margin: 0 0 12px; + font-size: 18px; + min-height: 1.5em; + line-height: 1.4; +} + +.lobby-status[data-tone="good"] { + color: darkgreen; +} + +.lobby-status[data-tone="bad"] { + color: darkred; +} + +/* ---- Join page ---- */ + +.join-form { + margin: 0; +} + +.form-grid { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 16px; + margin-bottom: 18px; +} + +.field { + display: flex; + flex-direction: column; + gap: 6px; + text-align: left; +} + +.field-label { + font-size: 14px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: #6b5a3e; +} + +.field input { + width: 100%; + box-sizing: border-box; + padding: 13px 14px; + border: 2px solid #b9a887; + border-radius: 9px; + background-color: #fff8e7; + color: #2b2b2b; + font-family: "Almendra", serif; + font-size: 22px; + transition: + border-color 0.15s ease, + box-shadow 0.15s ease; +} + +.field input:focus { + outline: none; + border-color: cornflowerblue; + box-shadow: 0 0 0 3px rgba(100, 149, 237, 0.25); +} + +#join-code { + letter-spacing: 0.22em; + text-align: center; + font-weight: 700; +} + +/* ---- Buttons and links ---- */ + +.Content .btn-primary, +.Content .btn-link { + display: block; + width: 100%; + min-height: 56px; + height: auto; + box-sizing: border-box; + padding: 12px 20px; + border: 2px solid #2f4f4f; + border-radius: 10px; + background-color: cornflowerblue; + color: white; + font-family: "Almendra", serif; + font-size: 22px; + font-weight: 700; + letter-spacing: 0.04em; + text-align: center; + text-decoration: none; + cursor: pointer; + box-shadow: 0 5px 0 #2f4f4f; + transition: + transform 0.12s ease, + background-color 0.15s ease, + box-shadow 0.12s ease; +} + +.Content .btn-primary:hover:not(:disabled), +.Content .btn-link:hover { + background-color: darkseagreen; + color: black; + border-color: #2f4f4f; + box-shadow: 0 5px 0 #2f4f4f; +} + +.Content .btn-primary:active:not(:disabled), +.Content .btn-link:active { + transform: translateY(3px); + box-shadow: 0 2px 0 #2f4f4f; +} + +.Content .btn-primary:disabled { + cursor: not-allowed; + opacity: 0.55; + box-shadow: none; +} + +/* ---- Waiting page ---- */ + +.waiting-panel { + text-align: center; +} + +.waiting-panel .panel-subtitle { + margin-bottom: 0; +} + +.waiting-details { + display: grid; + grid-template-columns: 1fr 1fr; + gap: 14px; + margin: 22px 0; + padding: 16px 0; + border-top: 1px dashed rgba(105, 105, 105, 0.45); + border-bottom: 1px dashed rgba(105, 105, 105, 0.45); +} + +.waiting-details .detail { + display: flex; + flex-direction: column; + gap: 4px; + padding: 12px 14px; + border: 2px dashed #b9a887; + border-radius: 12px; + background-color: rgba(255, 248, 231, 0.75); +} + +.detail-value { + font-size: clamp(24px, 4vw, 32px); + line-height: 1.1; + color: #2f4f4f; +} + +.room-code-inline { + color: cornflowerblue; + letter-spacing: 0.14em; +} + +.waiting-indicator { + display: flex; + justify-content: center; + gap: 8px; + margin: 8px 0 14px; +} + +.waiting-indicator span { + width: 11px; + height: 11px; + border-radius: 50%; + background-color: cornflowerblue; + animation: waiting-pulse 1.2s ease-in-out infinite; +} + +.waiting-indicator span:nth-child(2) { + animation-delay: 0.18s; +} + +.waiting-indicator span:nth-child(3) { + animation-delay: 0.36s; +} + +@keyframes waiting-pulse { + 0%, + 80%, + 100% { + transform: scale(0.7); + opacity: 0.45; + } + + 40% { + transform: scale(1); + opacity: 1; + } +} + +/* ---- Teacher lobby ---- */ + +.room-panel { + text-align: center; +} + +.roster-heading { + display: flex; + align-items: flex-end; + justify-content: space-between; + gap: 16px; + margin-bottom: 16px; + text-align: left; +} + +.roster-heading h2 { + display: flex; + align-items: center; + gap: 10px; + margin-bottom: 0; +} + +.roster-heading .panel-subtitle { + max-width: 280px; + margin: 0; + font-size: 16px; + text-align: right; +} + +.count-badge { + display: inline-flex; + align-items: center; + justify-content: center; + min-width: 34px; + height: 34px; + padding: 0 10px; + border-radius: 999px; + background-color: cornflowerblue; + color: white; + font-size: 19px; + line-height: 1; +} + +.page-lobby .table-container { + overflow-x: auto; + background-color: rgba(95, 158, 160, 0.18); + border-radius: 10px; +} + +.roster-table { + min-width: 480px; +} + +.roster-table th { + letter-spacing: 0.06em; +} + +.roster-table td.online { + color: darkgreen; + font-weight: 700; +} + +.roster-table td.offline { + color: #5a5a5a; +} + +.roster-table td.empty { + padding: 22px 10px; + font-style: italic; + text-align: center; +} + +/* ---- Card grid: trading and teacher lobby ---- */ + +.card-grid { + display: flex; + flex-wrap: wrap; + gap: 14px; + align-items: stretch; +} + +.card-grid > .panel { + flex: 1 1 380px; + min-width: 0; + margin: 0; + box-sizing: border-box; +} + +.trading-panel { + text-align: center; +} + +.trade-preview { + display: flex; + align-items: center; + justify-content: center; + gap: 16px; + margin: 18px 0; +} + +.trade-chip { + flex: 0 1 140px; + padding: 14px 10px; + border: 2px dashed #b9a887; + border-radius: 12px; + background-color: rgba(255, 248, 231, 0.75); +} + +.trade-chip span { + display: block; + font-size: 14px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: #6b5a3e; +} + +.trade-chip strong { + display: block; + font-size: 30px; + line-height: 1.1; + color: #2f4f4f; +} + +.trade-arrow { + font-size: 34px; + line-height: 1; + color: cornflowerblue; +} + +/* ---- Game status banner ---- */ + +.game-status { + margin: 0 0 12px; + padding: 10px 14px; + border: 2px dashed gray; + border-radius: 10px; + background-color: moccasin; + color: #2f4f4f; + font-size: 20px; + line-height: 1.35; +} + +.game-status[data-tone="good"] { + color: darkgreen; +} + +.game-status[data-tone="bad"] { + color: darkred; +} + +/* ---- Teacher phase controls ---- */ + +.phase-controls { + display: flex; + flex-direction: column; + gap: 12px; +} + +#phase-status { + margin: 16px 0 0; + font-size: 17px; +} + +/* ---- Trading roster ---- */ + +#trade-roster-panel .table-container { + overflow-x: auto; + border-radius: 10px; +} + +#trade-roster-panel .roster-table { + min-width: 100%; + border-collapse: collapse; + width: 100%; +} + +#trade-roster-panel .roster-table th, +#trade-roster-panel .roster-table td { + padding: 10px; + border: 1px solid black; + text-align: center; +} + +#trade-roster-panel .roster-table th { + background-color: darkseagreen; +} + +.roster-table tr.offline-player td { + color: #5a5a5a; + font-style: italic; +} + +/* ---- Discovery and trading ---- */ + +.found-list { + margin: 12px 0 0; + padding: 10px 14px; + border: 2px dashed gray; + border-radius: 10px; + background-color: moccasin; + color: #2f4f4f; + font-size: 18px; + line-height: 1.4; +} + +.found-block { + margin-top: 14px; + padding-top: 12px; + border-top: 1px dashed rgba(105, 105, 105, 0.45); + text-align: left; +} + +.trade-found-list { + margin: 4px 0 0; + font-size: 19px; + line-height: 1.4; + color: #2f4f4f; +} + +.trade-offer-form { + margin: 0; + text-align: left; +} + +.trade-offer-form .field { + margin-bottom: 16px; +} + +.trade-offer-form select, +.trade-amount input { + width: 100%; + box-sizing: border-box; + padding: 11px 12px; + border: 2px solid #b9a887; + border-radius: 9px; + background-color: #fff8e7; + color: #2b2b2b; + font-family: "Almendra", serif; + font-size: 20px; +} + +.trade-offer-form select:focus, +.trade-amount input:focus { + outline: none; + border-color: cornflowerblue; + box-shadow: 0 0 0 3px rgba(100, 149, 237, 0.25); +} + +.trade-columns { + display: flex; + align-items: stretch; + gap: 14px; + margin-bottom: 18px; +} + +.trade-side { + flex: 1; + min-width: 0; + margin: 0; + padding: 12px 14px 14px; + border: 2px dashed #b9a887; + border-radius: 12px; + background-color: rgba(255, 248, 231, 0.75); +} + +.trade-side legend { + padding: 0 6px; + font-size: 14px; + font-weight: 700; + letter-spacing: 0.12em; + text-transform: uppercase; + color: #6b5a3e; +} + +.trade-amount { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12px; + margin-top: 10px; +} + +.trade-amount span { + font-size: 18px; + color: #2f4f4f; +} + +.trade-amount input { + width: 92px; + flex: 0 0 auto; + text-align: center; +} + +.offer-list { + display: flex; + flex-direction: column; + gap: 12px; + text-align: left; +} + +.offer-card { + padding: 16px; + border: 2px dashed #b9a887; + border-radius: 12px; + background-color: rgba(255, 248, 231, 0.75); +} + +.offer-summary { + margin: 0 0 12px; + font-size: 19px; + line-height: 1.45; + color: #2f4f4f; +} + +.offer-actions { + display: flex; + flex-wrap: wrap; + gap: 10px; +} + +.Content .offer-actions .btn-small { + display: inline-block; + width: auto; + min-height: 44px; + height: auto; + padding: 8px 18px; + font-size: 18px; + box-shadow: 0 4px 0 #2f4f4f; +} + +.Content .offer-actions .btn-small:active { + transform: translateY(2px); + box-shadow: 0 2px 0 #2f4f4f; +} + +.Content .btn-quiet { + display: inline-block; + width: auto; + min-height: 44px; + height: auto; + padding: 8px 18px; + border: 2px solid #8b7a5c; + border-radius: 10px; + background-color: transparent; + color: #5a4a30; + font-family: "Almendra", serif; + font-size: 18px; + font-weight: 700; + cursor: pointer; + box-shadow: 0 4px 0 rgba(90, 74, 48, 0.35); +} + +.Content .btn-quiet:hover { + background-color: rgba(255, 248, 231, 0.9); + color: #2b2b2b; +} + +/* ---- Small screens ---- */ + +@media (min-width: 1440px) { + body.page-lobby .Content, + body.page-trading .Content { + max-width: 1120px; + } +} + +@media (max-width: 560px) { + body.page { + margin: 10px; + min-height: calc(100vh - 20px); + } + + body.page .Content { + padding-left: 0; + padding-right: 0; + } + + .form-grid, + .waiting-details { + grid-template-columns: 1fr; + } + + .roster-heading { + flex-direction: column; + align-items: flex-start; + } + + .roster-heading .panel-subtitle { + text-align: left; + } + + .trade-preview { + gap: 8px; + } + + .trade-chip { + flex: 1; + } + + .trade-columns { + flex-direction: column; + } + + .trade-columns > .trade-arrow { + align-self: center; + transform: rotate(90deg); + } + + .trade-amount input { + width: 110px; + } + + .panel::before { + inset: 6px; + } + + .room-code { + letter-spacing: 0.1em; + } +} + +@media (prefers-reduced-motion: reduce) { + .waiting-indicator span { + animation: none; + } +} + +[hidden] { + display: none !important; +} diff --git a/trading.html b/trading.html new file mode 100644 index 0000000..c0ad82c --- /dev/null +++ b/trading.html @@ -0,0 +1,179 @@ + + + + Escape the Island + + + + + + + + +
+
+

Escape the Island

+
+ +
+
+
+
+
+

The Trading Post

+

Day - trading

+

+ The day has ended. Compare supplies with the castaways you found + during the day and make an offer. Trading does not cost any daily + hours. +

+ +
+
+ Your Fish + - +
+
⇄
+
+ Your Wood + - +
+
+ +

+ Connecting... +

+ +
+

Castaways You Know

+

+ No one yet. You can only trade with castaways you found during the + day. +

+
+
+ +
+ + + + + + + +
+
+ + + + diff --git a/waiting.html b/waiting.html index b672345..6b8258a 100644 --- a/waiting.html +++ b/waiting.html @@ -2,6 +2,7 @@ Escape the Island + @@ -10,40 +11,56 @@ href="https://fonts.googleapis.com/css2?family=Almendra:ital,wght@0,400;0,700;1,400;1,700&display=swap" rel="stylesheet" /> - - +

Escape the Island

- +
-
+
+
+

Waiting On The Shore

+

You made it to the island

+

+ Your teacher will start the first day once the whole class has + joined. Keep this tab open. +

+ +
+
+ Castaway + ---- +
+
+ Room Code + + ---- + +
+
+ + +

+ Connecting... +

+

+ If your connection drops, this page will reconnect automatically. +

+
+
- + diff --git a/ws-test.html b/ws-test.html index 507b999..8d2f6e9 100644 --- a/ws-test.html +++ b/ws-test.html @@ -17,6 +17,7 @@ ws.onmessage = (event) => log("recv: " + event.data); ws.onclose = (event) => log(`close ${event.code}`); + ws.onerror = () => log("error"); document.getElementById("send").onclick = () => { ws.send(JSON.stringify({ type: "ECHO", text: "button " }));