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
23 changes: 23 additions & 0 deletions src/migrations/AddTimeAttackMode1792512000000.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { MigrationInterface, QueryRunner } from 'typeorm';

export class AddTimeAttackMode1792512000000 implements MigrationInterface {
name = 'AddTimeAttackMode1792512000000';

async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_quest_chain_progress" ADD COLUMN "mode" varchar(20) NOT NULL DEFAULT 'standard'`,
);
await queryRunner.query(
`ALTER TABLE "user_quest_chain_progress" ADD COLUMN "deadlineAt" TIMESTAMP WITH TIME ZONE`,
);
}

async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(
`ALTER TABLE "user_quest_chain_progress" DROP COLUMN "deadlineAt"`,
);
await queryRunner.query(
`ALTER TABLE "user_quest_chain_progress" DROP COLUMN "mode"`,
);
}
}
12 changes: 12 additions & 0 deletions src/quests/controllers/quest-chain-leaderboard.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,18 @@ export class QuestChainLeaderboardController {
return await this.leaderboardService.getSpeedRunLeaderboard(chainId, limit);
}

@Get(':id/leaderboard/time-attack')
@ApiOperation({ summary: 'Get verified time attack completions for a quest chain' })
@ApiParam({ name: 'id', description: 'Quest chain ID' })
@ApiQuery({ name: 'limit', required: false, type: Number })
@ApiResponse({ status: 200, description: 'Time attack leaderboard retrieved successfully' })
async getTimeAttackLeaderboard(
@Param('id') chainId: string,
@Query('limit', new ValidationPipe({ transform: true })) limit = 10,
) {
return this.leaderboardService.getTimeAttackLeaderboard(chainId, limit);
}

@Get(':id/leaderboard/score')
@ApiOperation({ summary: 'Get score leaderboard for a quest chain' })
@ApiParam({ name: 'id', description: 'Quest chain ID' })
Expand Down
4 changes: 3 additions & 1 deletion src/quests/controllers/quest-chain-progress.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,10 @@ export class QuestChainProgressController {
async startChain(
@Param('id') chainId: string,
@Body('userId') userId: string,
@Body('mode') mode: 'standard' | 'time_attack' = 'standard',
@Body('timeLimitSeconds') timeLimitSeconds = 300,
): Promise<UserQuestChainProgress> {
return this.progressionService.startChain(userId, chainId);
return this.progressionService.startChain(userId, chainId, mode, timeLimitSeconds);
}

@Get(':id/progress')
Expand Down
7 changes: 7 additions & 0 deletions src/quests/entities/user-quest-chain-progress.entity.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,13 @@ export class UserQuestChainProgress {
@Column({ type: 'int', default: 0 })
totalHintsUsed: number;

/** The server-owned timed variant; normal play remains unchanged. */
@Column({ type: 'varchar', length: 20, default: 'standard' })
mode: 'standard' | 'time_attack';

@Column({ type: 'timestamp with time zone', nullable: true })
deadlineAt?: Date;

@Column({ type: 'timestamp with time zone', nullable: true })
startedAt?: Date;

Expand Down
22 changes: 22 additions & 0 deletions src/quests/services/quest-chain-leaderboard.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,28 @@ export class QuestChainLeaderboardService {
}));
}

async getTimeAttackLeaderboard(chainId: string, limit = 10): Promise<LeaderboardEntry[]> {
const safeLimit = Math.min(100, Math.max(1, Math.trunc(limit) || 10));
const rows = await this.userProgressRepository
.createQueryBuilder('progress')
.select(['progress.userId', 'progress.totalTime', 'progress.completedAt'])
.where('progress.questChainId = :chainId', { chainId })
.andWhere('progress.status = :status', { status: 'completed' })
.andWhere('progress.mode = :mode', { mode: 'time_attack' })
.orderBy('progress.totalTime', 'ASC')
.limit(safeLimit)
.getRawMany();

return rows.map((row, index) => ({
rank: index + 1,
userId: row.progress_userId,
username: `User ${row.progress_userId}`,
value: Number(row.progress_totalTime),
completedAt: row.progress_completedAt,
chainName: undefined,
}));
}

async getScoreLeaderboard(
chainId: string,
limit = 10,
Expand Down
27 changes: 25 additions & 2 deletions src/quests/services/quest-chain-progression.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,15 @@ export class QuestChainProgressionService {
async startChain(
userId: string,
chainId: string,
mode: 'standard' | 'time_attack' = 'standard',
timeLimitSeconds = 300,
): Promise<UserQuestChainProgress> {
if (mode !== 'standard' && mode !== 'time_attack') {
throw new BadRequestException('Unsupported quest mode');
}
if (!Number.isInteger(timeLimitSeconds) || timeLimitSeconds < 30 || timeLimitSeconds > 3600) {
throw new BadRequestException('Time attack limit must be between 30 and 3600 seconds');
}
// Check if user already has progress for this chain
const existingProgress = await this.userProgressRepository.findOne({
where: { userId, questChainId: chainId },
Expand All @@ -50,7 +58,11 @@ export class QuestChainProgressionService {
totalScore: 0,
totalTime: 0,
totalHintsUsed: 0,
mode,
startedAt: new Date(),
deadlineAt: mode === 'time_attack'
? new Date(Date.now() + timeLimitSeconds * 1000)
: null,
lastPlayedAt: new Date(),
});

Expand Down Expand Up @@ -140,6 +152,11 @@ export class QuestChainProgressionService {
);
}

const now = new Date();
if (progress.mode === 'time_attack' && progress.deadlineAt && now >= progress.deadlineAt) {
throw new BadRequestException('Time attack has expired');
}

try {
// Update progress
progress.completedPuzzleIds = [...progress.completedPuzzleIds, puzzleId];
Expand All @@ -148,7 +165,9 @@ export class QuestChainProgressionService {
chainPuzzle.sequenceOrder,
);
progress.totalScore += completionData.score;
progress.totalTime += completionData.timeTaken;
progress.totalTime = progress.mode === 'time_attack' && progress.startedAt
? Math.max(0, Math.ceil((now.getTime() - progress.startedAt.getTime()) / 1000))
: progress.totalTime + completionData.timeTaken;
progress.totalHintsUsed += completionData.hintsUsed;
progress.lastPlayedAt = new Date();

Expand Down Expand Up @@ -185,7 +204,11 @@ export class QuestChainProgressionService {

if (allPuzzlesCompleted) {
progress.status = 'completed';
progress.completedAt = new Date();
progress.completedAt = now;
if (progress.mode === 'time_attack' && progress.deadlineAt) {
const remainingSeconds = Math.max(0, Math.floor((progress.deadlineAt.getTime() - now.getTime()) / 1000));
progress.totalScore += Math.min(remainingSeconds, Math.floor(progress.totalScore * 0.2));
}

// Award completion rewards
await this.awardCompletionRewards(userId, chainId);
Expand Down