interface WebSocketData { role: "teacher" | "student" | "unknown"; roomCode: string | null; name?: string; } 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", "/lobby": "lobby.html", "/waiting": "waiting.html", "/game": "game.html", "/trading": "trading.html", "/ws-test": "ws-test.html", }; async function serveFile(path: string): Promise { const file = Bun.file(path); 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: 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: "unknown", roomCode: null } })) return; return new Response("WebSocket upgrade failed", { status: 400 }); } const page = pages[url.pathname]; if (page) return serveFile(page); if ( url.pathname.startsWith("/client/") || url.pathname.startsWith("/assets/") ) { if (url.pathname.includes("..")) { return new Response("Bad path", { status: 400 }); } return serveFile("." + url.pathname); } if (url.pathname === "/styles.css") return serveFile("styles.css"); if (url.pathname == "/api/health") { return Response.json({ ok: true, time: Date.now() }); } if (url.pathname == "/hello") { return new Response("Hello from bun"); } return new Response("Not Found", { status: 404 }); }, websocket: { open() { console.log("A client connect via websocket!"); }, message(ws, message) { const text = typeof message === "string" ? message : message.toString(); let data: any; try { data = JSON.parse(text); } catch { sendError(ws, "Invalid JSON"); return; } if (data.type === "PING") { safeSend(ws, { type: "PONG" }); return; } console.log("recv:", text); if (data.type === "ECHO") { safeSend(ws, { type: "ECHO", text: data.text }); return; } if (data.type === "CREATE_ROOM") { if (ws.data.roomCode) { sendError(ws, "Already in a room"); return; } let roomCode = ""; do { roomCode = Math.floor(1000 + Math.random() * 9000).toString(); } while (rooms.has(roomCode)); 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 || !ws.data.roomCode) return; const room = rooms.get(ws.data.roomCode); 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"); }, }, }); console.log(`Listening on ${server.url}`);