Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions webapp/public/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,24 @@ <h2>Session State</h2>
</div>
<button type="submit">Load session</button>
</form>
<form id="start-session-form">
<div class="field">
<label for="start-session-id">Session ID</label>
<input id="start-session-id" name="start-session-id" type="text" required />
</div>
<div class="field">
<label for="start-player-id">Owner player ID</label>
<input
id="start-player-id"
name="start-player-id"
type="text"
placeholder="Returned when you create the lobby"
required
/>
</div>
<button type="submit">Start run</button>
</form>
<div id="start-result" class="result"></div>
<div id="session"></div>
</section>
</main>
Expand Down
52 changes: 49 additions & 3 deletions webapp/public/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const createRoomResultEl = document.querySelector('#create-room-result');
const joinResultEl = document.querySelector('#join-result');
const difficultyCardsEl = document.querySelector('#difficulty-cards');
const legendEl = document.querySelector('#legend');
const startResultEl = document.querySelector('#start-result');

let difficultyDefinitions = [];

Expand Down Expand Up @@ -153,6 +154,11 @@ const renderSession = (state) => {
).toLocaleString()}`;
wrapper.appendChild(meta);

const ownerMeta = document.createElement('div');
ownerMeta.className = 'muted';
ownerMeta.textContent = `Owner player ID: ${state.ownerId}`;
wrapper.appendChild(ownerMeta);

const players = document.createElement('div');
const list = document.createElement('ul');
state.players.forEach((player) => {
Expand Down Expand Up @@ -238,6 +244,23 @@ const loadDifficulties = async () => {
}
};

const prefillSessionFields = ({ sessionId, playerId }) => {
const joinId = document.querySelector('#join-session-id');
const sessionIdInput = document.querySelector('#session-id');
const startSessionInput = document.querySelector('#start-session-id');
const startPlayerInput = document.querySelector('#start-player-id');

if (sessionId) {
[joinId, sessionIdInput, startSessionInput].forEach((node) => {
if (node) node.value = sessionId;
});
}

if (playerId && startPlayerInput) {
startPlayerInput.value = playerId;
}
};

const createRoomForm = document.querySelector('#create-room-form');
createRoomForm?.addEventListener('submit', async (event) => {
event.preventDefault();
Expand All @@ -252,9 +275,8 @@ createRoomForm?.addEventListener('submit', async (event) => {
method: 'POST',
body: JSON.stringify(payload),
});
createRoomResultEl.textContent = `Lobby created! Session ID: ${result.sessionId}`;
document.querySelector('#join-session-id').value = result.sessionId;
document.querySelector('#session-id').value = result.sessionId;
createRoomResultEl.textContent = `Lobby created! Session ID: ${result.sessionId} • Owner player ID: ${result.ownerPlayerId}`;
prefillSessionFields({ sessionId: result.sessionId, playerId: result.ownerPlayerId });
refreshLobby();
} catch (error) {
createRoomResultEl.textContent = error.message;
Expand Down Expand Up @@ -296,6 +318,7 @@ joinForm?.addEventListener('submit', async (event) => {
body: JSON.stringify(payload),
});
joinResultEl.textContent = `Joined! Player ID: ${response.playerId}`;
prefillSessionFields({ sessionId, playerId: response.playerId });
refreshSession(sessionId);
refreshLobby();
} catch (error) {
Expand All @@ -307,9 +330,32 @@ const sessionForm = document.querySelector('#load-session-form');
sessionForm?.addEventListener('submit', async (event) => {
event.preventDefault();
const sessionId = new FormData(sessionForm).get('session-id');
prefillSessionFields({ sessionId });
refreshSession(sessionId);
});

const startForm = document.querySelector('#start-session-form');
startForm?.addEventListener('submit', async (event) => {
event.preventDefault();
const formData = new FormData(startForm);
const sessionId = formData.get('start-session-id');
const playerId = formData.get('start-player-id');

if (!sessionId || !playerId) return;

try {
const response = await api(`/sessions/${sessionId}/start`, {
method: 'POST',
body: JSON.stringify({ playerId }),
});
startResultEl.textContent = 'Run started!';
renderSession(response.state);
refreshLobby();
} catch (error) {
startResultEl.textContent = error.message;
}
});

const refreshSession = async (sessionId) => {
if (!sessionId) return;
try {
Expand Down
20 changes: 20 additions & 0 deletions webapp/src/routes/sessions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,10 @@ const joinSessionSchema = z.object({
password: z.string().min(1).max(50).optional(),
});

const startSessionSchema = z.object({
playerId: z.string().uuid(),
});

sessionsRouter.post('/sessions/:sessionId/join', (req, res, next) => {
try {
const body = joinSessionSchema.parse(req.body);
Expand All @@ -64,6 +68,22 @@ sessionsRouter.post('/sessions/:sessionId/join', (req, res, next) => {
}
});

sessionsRouter.post('/sessions/:sessionId/start', (req, res, next) => {
try {
const body = startSessionSchema.parse(req.body);
const session = sessionStore.startSession(req.params.sessionId, body.playerId);

lobbyStore.postSystemMessage(
`${session.ownerName} started a ${session.difficulty} run (${session.players.length}/${session.maxPlayers}).`,
session.id,
);

res.json({ state: serializeSession(session) });
} catch (error) {
next(error);
}
});

sessionsRouter.get('/sessions/:sessionId', (req, res, next) => {
try {
const session = sessionStore.getSession(req.params.sessionId);
Expand Down
17 changes: 7 additions & 10 deletions webapp/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,12 @@ const env = getEnv();
const app = createApp();

const startServer = async () => {
try {
await ensureDatabaseSetup();
app.listen(env.port, () => {
logger.info({ port: env.port, nodeEnv: env.nodeEnv }, 'Web app server listening');
});
} catch (error) {
logger.error({ err: error }, 'Failed to start server');
process.exit(1);
}
await ensureDatabaseSetup();
app.listen(env.port, () => {
logger.info({ port: env.port, nodeEnv: env.nodeEnv }, 'Web app server listening');
});
};

startServer();
startServer().catch((error) => {
logger.error({ err: error }, 'Failed to start server');
});
3 changes: 2 additions & 1 deletion webapp/src/services/game-engine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,9 @@ export class GameEngine {
return {
id: sessionId,
difficulty: options.difficulty,
difficultySettings: definition,
ownerName: options.ownerName,
ownerId: owner.id,
createdAt,
players: [owner],
turnOrder: [owner.id],
Expand All @@ -277,7 +279,6 @@ export class GameEngine {
maxPlayers: options.maxPlayers ?? 6,
dungeon,
version: 1,
difficultySettings: definition,
};
}

Expand Down
1 change: 1 addition & 0 deletions webapp/src/services/session-serializer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ export const serializeSession = (session: GameSession) => {
difficulty: session.difficulty,
difficultySettings: session.difficultySettings,
ownerName: session.ownerName,
ownerId: session.ownerId,
createdAt: session.createdAt,
players: session.players.map((player) => ({
id: player.id,
Expand Down
19 changes: 19 additions & 0 deletions webapp/src/services/session-store.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,25 @@ class SessionStore {
return Array.from(this.sessions.values());
}

startSession(sessionId: string, playerId: string): GameSession {
const session = this.getSession(sessionId);

if (session.status !== 'waiting') {
throw new HttpError(409, 'This run has already started');
}

if (session.ownerId !== playerId) {
throw new HttpError(403, 'Only the lobby owner can start the run');
}

session.status = 'in_progress';
session.log.push(`${session.ownerName} rallies the party. The run begins!`);
this.trimLog(session);
session.version += 1;

return session;
}

movePlayer(sessionId: string, playerId: string, direction: 'north' | 'south' | 'east' | 'west'): MoveOutcome {
const session = this.getSession(sessionId);
const result = GameEngine.move(session, playerId, direction);
Expand Down
1 change: 1 addition & 0 deletions webapp/src/services/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@ export interface GameSession {
difficulty: Difficulty;
difficultySettings: DifficultyDefinition;
ownerName: string;
ownerId: string;
createdAt: string;
players: Player[];
turnOrder: string[];
Expand Down
Loading