Files
Escape-the-Island/index.ts
T

130 lines
3.6 KiB
TypeScript

interface WebSocketData {
role: "teacher" | "student";
roomCode: string;
}
interface Player {
name: string;
fish: number;
wood: number;
}
const rooms = new Map<string, { teacherWs: any; players: Map<any, Player> }>();
const pages: Record<string, string> = {
"/": "index.html",
"/host": "lobby.html",
"/lobby": "lobby.html",
"/waiting": "waiting.html",
"/game": "game.html",
"/trading": "trading.html",
"/ws-test": "ws-test.html",
};
const server = Bun.serve<WebSocketData>({
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: "" } }))
return;
return new Response("WebSocket upgrade failed", { status: 400 });
}
const page = pages[url.pathname];
if (page) {
const file = Bun.file(page);
if (!(await file.exists())) {
return new Response("Not Found", { status: 404 });
}
return new Response(Bun.file(page));
}
if (
url.pathname.startsWith("/client/") ||
url.pathname.startsWith("/assets/")
) {
if (url.pathname.includes("..")) {
return new Response("Bad path", { status: 400 });
}
return new Response(Bun.file("." + 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 == "/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(ws) {
console.log("A client connect via websocket!");
},
message(ws, message) {
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!" }),
);
return;
}
room.players.set(ws, { name: data.name, fish: 0, wood: 0 });
ws.data = { role: "student", roomCode: data.code };
ws.send(JSON.stringify({ type: "JOIN_SUCCESS" }));
console.log(`Student ${data.name} joined room ${data.code}`);
updateTeachersDashboard(room);
}
},
close(ws) {
if (!ws.data) 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);
}
}
console.log("A client disconnected");
},
},
});
function updateTeachersDashboard(room: {
teacherWs: any;
players: Map<any, Player>;
}) {
const playerList = Array.from(room.players.values());
room.teacherWs.send(
JSON.stringify({
type: "UPDATES_PLAYERS",
players: playerList,
}),
);
}
console.log(`Listening on ${server.url}`);