feat(hunting): show cleared encounters and resume interrupted fights
The hunt screen kept whatever roll was last in memory, so a player coming back from a fight saw every encounter as fresh. Encounters now carry their own status, which the combat module advances as fights start and end. - hunt_encounters.status replaces consumed_at, which only recorded that a fight had begun and could not distinguish a win from a loss - a lost fight hands the encounter back as AVAILABLE, so it can be retried; the unique index tying one combat to one encounter goes with it - GET /hunts/active serves the resumable hunt, which the hunt page adopts on entry rather than trusting its in-memory roll - defeated encounters are crossed out and lose their hover and attack action - a fresh page load rejoins a combat the server still holds open Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
@@ -7,6 +7,7 @@ import {
|
||||
PrimaryGeneratedColumn,
|
||||
} from 'typeorm';
|
||||
import { MonsterDefinition } from '../../monsters/entities/monster-definition.entity';
|
||||
import { HuntEncounterStatus } from '../hunt-encounter-status.enum';
|
||||
import { Hunt } from './hunt.entity';
|
||||
|
||||
@Entity({ name: 'hunt_encounters' })
|
||||
@@ -23,10 +24,16 @@ export class HuntEncounter {
|
||||
@Column({ name: 'position', type: 'integer' })
|
||||
position!: number;
|
||||
|
||||
// Set when a Combat is successfully created from this encounter. Prevents
|
||||
// one HuntEncounter from spawning more than one Combat (spec §7).
|
||||
@Column({ name: 'consumed_at', type: 'timestamptz', nullable: true })
|
||||
consumedAt!: Date | null;
|
||||
// Owned by the combat module, which advances it as fights start and end.
|
||||
// DEFEATED and IN_PROGRESS both bar a new fight; a lost fight resets the
|
||||
// encounter to AVAILABLE so the player can try again.
|
||||
@Column({
|
||||
name: 'status',
|
||||
type: 'enum',
|
||||
enum: HuntEncounterStatus,
|
||||
enumName: 'hunt_encounter_status_enum',
|
||||
})
|
||||
status!: HuntEncounterStatus;
|
||||
|
||||
@CreateDateColumn({ name: 'created_at', type: 'timestamptz' })
|
||||
createdAt!: Date;
|
||||
|
||||
5
apps/api/src/hunting/hunt-encounter-status.enum.ts
Normal file
5
apps/api/src/hunting/hunt-encounter-status.enum.ts
Normal file
@@ -0,0 +1,5 @@
|
||||
export enum HuntEncounterStatus {
|
||||
AVAILABLE = 'AVAILABLE',
|
||||
IN_PROGRESS = 'IN_PROGRESS',
|
||||
DEFEATED = 'DEFEATED',
|
||||
}
|
||||
@@ -10,15 +10,17 @@ import { HuntingService } from './hunting.service';
|
||||
describe('HuntingController', () => {
|
||||
let app: INestApplication<App>;
|
||||
const startHunt = jest.fn();
|
||||
const getActiveHunt = jest.fn();
|
||||
|
||||
beforeEach(async () => {
|
||||
startHunt.mockReset();
|
||||
getActiveHunt.mockReset();
|
||||
const module = await Test.createTestingModule({
|
||||
controllers: [HuntingController],
|
||||
providers: [
|
||||
{
|
||||
provide: HuntingService,
|
||||
useValue: { startHunt },
|
||||
useValue: { startHunt, getActiveHunt },
|
||||
},
|
||||
],
|
||||
}).compile();
|
||||
@@ -47,4 +49,42 @@ describe('HuntingController', () => {
|
||||
expect(startHunt).toHaveBeenCalledWith(DEMO_CHARACTER_ID);
|
||||
expect(response.body).toEqual(huntResult);
|
||||
});
|
||||
|
||||
it('serves the resumable hunt with its encounter statuses', async () => {
|
||||
const huntResult = {
|
||||
id: 'hunt-1',
|
||||
location: { id: 'loc-1', key: 'burned-road', name: 'Verbrannte Strasse' },
|
||||
encounters: [
|
||||
{
|
||||
id: 'encounter-1',
|
||||
monster: {
|
||||
key: 'ash-rat',
|
||||
name: 'Aschenratte',
|
||||
level: 1,
|
||||
artworkPath: '/images/monsters/ash-rat.png',
|
||||
},
|
||||
dangerRating: 'WEAK',
|
||||
status: 'DEFEATED',
|
||||
},
|
||||
],
|
||||
};
|
||||
getActiveHunt.mockResolvedValue(huntResult);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/hunts/active')
|
||||
.expect(200);
|
||||
|
||||
expect(getActiveHunt).toHaveBeenCalledWith(DEMO_CHARACTER_ID);
|
||||
expect(response.body).toEqual(huntResult);
|
||||
});
|
||||
|
||||
it('serves an empty body when there is no resumable hunt', async () => {
|
||||
getActiveHunt.mockResolvedValue(null);
|
||||
|
||||
const response = await request(app.getHttpServer())
|
||||
.get('/api/hunts/active')
|
||||
.expect(200);
|
||||
|
||||
expect(response.body).toEqual({});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Controller, Post } from '@nestjs/common';
|
||||
import { Controller, Get, Post } from '@nestjs/common';
|
||||
import { DEMO_CHARACTER_ID } from '../demo/demo-character.constants';
|
||||
import { HuntResultDto, HuntingService } from './hunting.service';
|
||||
|
||||
@@ -10,4 +10,9 @@ export class HuntingController {
|
||||
startHunt(): Promise<HuntResultDto> {
|
||||
return this.huntingService.startHunt(DEMO_CHARACTER_ID);
|
||||
}
|
||||
|
||||
@Get('active')
|
||||
getActiveHunt(): Promise<HuntResultDto | null> {
|
||||
return this.huntingService.getActiveHunt(DEMO_CHARACTER_ID);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,6 +9,7 @@ import { LocationDefinition } from '../world/entities/location-definition.entity
|
||||
import { DangerRating } from './danger-rating';
|
||||
import { Hunt } from './entities/hunt.entity';
|
||||
import { HuntEncounter } from './entities/hunt-encounter.entity';
|
||||
import { HuntEncounterStatus } from './hunt-encounter-status.enum';
|
||||
import { HuntStatus } from './hunt-status.enum';
|
||||
import { HuntingDomainError } from './hunting.errors';
|
||||
import { HuntingService } from './hunting.service';
|
||||
@@ -29,6 +30,15 @@ interface FakeState {
|
||||
huntEncounters: HuntEncounter[];
|
||||
}
|
||||
|
||||
// `find` in the fake ignores `relations`, so fixtures attach the joined
|
||||
// monster the way TypeORM would have hydrated it.
|
||||
function withMonster(
|
||||
encounter: HuntEncounter,
|
||||
monster: MonsterDefinition,
|
||||
): HuntEncounter {
|
||||
return { ...encounter, monster } as HuntEncounter;
|
||||
}
|
||||
|
||||
class FakeRepository<T extends { id: string }> {
|
||||
constructor(
|
||||
private readonly state: FakeState,
|
||||
@@ -56,10 +66,24 @@ class FakeRepository<T extends { id: string }> {
|
||||
);
|
||||
}
|
||||
|
||||
find(options: { where: Partial<T> }): Promise<T[]> {
|
||||
return Promise.resolve(
|
||||
this.rows().filter((row) => this.matches(row, options.where)),
|
||||
find(options: {
|
||||
where: Partial<T>;
|
||||
order?: Partial<Record<keyof T, 'ASC' | 'DESC'>>;
|
||||
}): Promise<T[]> {
|
||||
const matched = this.rows().filter((row) =>
|
||||
this.matches(row, options.where),
|
||||
);
|
||||
const orderKey = options.order
|
||||
? (Object.keys(options.order)[0] as keyof T)
|
||||
: undefined;
|
||||
if (orderKey) {
|
||||
const direction = options.order![orderKey] === 'DESC' ? -1 : 1;
|
||||
matched.sort((a, b) => {
|
||||
if (a[orderKey] === b[orderKey]) return 0;
|
||||
return a[orderKey] > b[orderKey] ? direction : -direction;
|
||||
});
|
||||
}
|
||||
return Promise.resolve(matched);
|
||||
}
|
||||
|
||||
create(values: Partial<T>): T {
|
||||
@@ -567,4 +591,135 @@ describe('HuntingService', () => {
|
||||
expect(encounter.dangerRating).toBe(DangerRating.WEAK);
|
||||
}
|
||||
});
|
||||
|
||||
it('marks every freshly rolled encounter as AVAILABLE', async () => {
|
||||
const monsterA = monsterDefinition(
|
||||
MONSTER_A_ID,
|
||||
'aschenratte',
|
||||
'Aschenratte',
|
||||
);
|
||||
const state = createState();
|
||||
state.characters[0].currentLocationId = HUNTING_LOCATION_ID;
|
||||
state.characters[0].currentLocation = huntingLocation();
|
||||
state.locationMonsters = [
|
||||
locationMonster(
|
||||
LOCATION_MONSTER_A_ID,
|
||||
HUNTING_LOCATION_ID,
|
||||
monsterA,
|
||||
100,
|
||||
),
|
||||
];
|
||||
const { dataSource, service } = createService({
|
||||
state,
|
||||
randomSource: fakeRandomSource([0.1, 0.1, 0.1]),
|
||||
});
|
||||
|
||||
const result = await service.startHunt(CHARACTER_ID);
|
||||
|
||||
expect(result.encounters.map((encounter) => encounter.status)).toEqual([
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
]);
|
||||
expect(
|
||||
dataSource.state.huntEncounters.map((encounter) => encounter.status),
|
||||
).toEqual([
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
]);
|
||||
});
|
||||
|
||||
describe('getActiveHunt', () => {
|
||||
function activeHuntState(
|
||||
statuses: HuntEncounterStatus[],
|
||||
overrides: { huntStatus?: HuntStatus; huntLocationId?: string } = {},
|
||||
) {
|
||||
const monsterA = monsterDefinition(
|
||||
MONSTER_A_ID,
|
||||
'aschenratte',
|
||||
'Aschenratte',
|
||||
);
|
||||
const state = createState();
|
||||
state.characters[0].currentLocationId = HUNTING_LOCATION_ID;
|
||||
state.characters[0].currentLocation = huntingLocation();
|
||||
state.hunts = [
|
||||
{
|
||||
id: 'hunt-1',
|
||||
characterId: CHARACTER_ID,
|
||||
locationId: overrides.huntLocationId ?? HUNTING_LOCATION_ID,
|
||||
status: overrides.huntStatus ?? HuntStatus.ACTIVE,
|
||||
createdAt: new Date('2026-08-18T09:00:00.000Z'),
|
||||
} as Hunt,
|
||||
];
|
||||
state.huntEncounters = statuses.map((status, position) =>
|
||||
withMonster(
|
||||
{
|
||||
id: `encounter-${position}`,
|
||||
huntId: 'hunt-1',
|
||||
monsterDefinitionId: MONSTER_A_ID,
|
||||
position,
|
||||
status,
|
||||
createdAt: new Date('2026-08-18T09:00:00.000Z'),
|
||||
} as HuntEncounter,
|
||||
monsterA,
|
||||
),
|
||||
);
|
||||
return state;
|
||||
}
|
||||
|
||||
it('returns null when the character has no active hunt', async () => {
|
||||
const { service } = createService();
|
||||
|
||||
await expect(service.getActiveHunt(CHARACTER_ID)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns null when the only hunt has been superseded', async () => {
|
||||
const state = activeHuntState([HuntEncounterStatus.AVAILABLE], {
|
||||
huntStatus: HuntStatus.SUPERSEDED,
|
||||
});
|
||||
const { service } = createService({ state });
|
||||
|
||||
await expect(service.getActiveHunt(CHARACTER_ID)).resolves.toBeNull();
|
||||
});
|
||||
|
||||
it('returns the active hunt with the persisted status of each encounter', async () => {
|
||||
const state = activeHuntState([
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.DEFEATED,
|
||||
HuntEncounterStatus.IN_PROGRESS,
|
||||
]);
|
||||
const { service } = createService({ state });
|
||||
|
||||
const result = await service.getActiveHunt(CHARACTER_ID);
|
||||
|
||||
expect(result?.id).toBe('hunt-1');
|
||||
expect(result?.location).toEqual({
|
||||
id: HUNTING_LOCATION_ID,
|
||||
key: 'burned-road',
|
||||
name: 'Verbrannte Strasse',
|
||||
});
|
||||
expect(result?.encounters.map((encounter) => encounter.status)).toEqual([
|
||||
HuntEncounterStatus.AVAILABLE,
|
||||
HuntEncounterStatus.DEFEATED,
|
||||
HuntEncounterStatus.IN_PROGRESS,
|
||||
]);
|
||||
expect(result?.encounters.map((encounter) => encounter.id)).toEqual([
|
||||
'encounter-0',
|
||||
'encounter-1',
|
||||
'encounter-2',
|
||||
]);
|
||||
expect(result?.encounters[0].monster.key).toBe('aschenratte');
|
||||
expect(result?.encounters[0].dangerRating).toBeDefined();
|
||||
});
|
||||
|
||||
it('returns null once the character has left the hunt location', async () => {
|
||||
const state = activeHuntState([HuntEncounterStatus.AVAILABLE], {
|
||||
huntLocationId: SAFE_LOCATION_ID,
|
||||
});
|
||||
const { service } = createService({ state });
|
||||
|
||||
await expect(service.getActiveHunt(CHARACTER_ID)).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -9,6 +9,7 @@ import { TravelStatus } from '../travel/travel-status.enum';
|
||||
import { calculateDangerRating, DangerRating } from './danger-rating';
|
||||
import { Hunt } from './entities/hunt.entity';
|
||||
import { HuntEncounter } from './entities/hunt-encounter.entity';
|
||||
import { HuntEncounterStatus } from './hunt-encounter-status.enum';
|
||||
import { HuntStatus } from './hunt-status.enum';
|
||||
import {
|
||||
characterNotFound,
|
||||
@@ -30,6 +31,7 @@ export interface HuntEncounterDto {
|
||||
id: string;
|
||||
monster: MonsterSummary;
|
||||
dangerRating: DangerRating;
|
||||
status: HuntEncounterStatus;
|
||||
}
|
||||
|
||||
export interface HuntResultDto {
|
||||
@@ -110,28 +112,11 @@ export class HuntingService {
|
||||
huntId: hunt.id,
|
||||
monsterDefinitionId: monster.id,
|
||||
position,
|
||||
status: HuntEncounterStatus.AVAILABLE,
|
||||
});
|
||||
await txEncounters.save(encounter);
|
||||
|
||||
const dangerRating = calculateDangerRating(
|
||||
{ attack: character.baseAttack, armor: 0, hp: character.baseHp },
|
||||
{
|
||||
attack: monster.attack,
|
||||
armor: monster.armor,
|
||||
hp: monster.maxHp,
|
||||
},
|
||||
);
|
||||
|
||||
encounterDtos.push({
|
||||
id: encounter.id,
|
||||
monster: {
|
||||
key: monster.key,
|
||||
name: monster.name,
|
||||
level: monster.level,
|
||||
artworkPath: monster.artworkPath,
|
||||
},
|
||||
dangerRating,
|
||||
});
|
||||
encounterDtos.push(this.toEncounterDto(encounter, monster, character));
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -142,6 +127,70 @@ export class HuntingService {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The hunt the player can still act on, or null if there is none. A hunt
|
||||
* is only resumable where it was rolled, so travelling away retires it and
|
||||
* the player has to search the new area instead.
|
||||
*/
|
||||
async getActiveHunt(characterId: string): Promise<HuntResultDto | null> {
|
||||
const characters = this.dataSource.getRepository(Character);
|
||||
const character = await characters.findOne({
|
||||
where: { id: characterId },
|
||||
relations: { currentLocation: true },
|
||||
});
|
||||
if (!character) {
|
||||
throw characterNotFound();
|
||||
}
|
||||
|
||||
const hunts = this.dataSource.getRepository(Hunt);
|
||||
const hunt = await hunts.findOne({
|
||||
where: {
|
||||
characterId,
|
||||
status: HuntStatus.ACTIVE,
|
||||
locationId: character.currentLocationId,
|
||||
},
|
||||
});
|
||||
if (!hunt) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const huntEncounters = this.dataSource.getRepository(HuntEncounter);
|
||||
const encounters = await huntEncounters.find({
|
||||
where: { huntId: hunt.id },
|
||||
relations: { monster: true },
|
||||
order: { position: 'ASC' },
|
||||
});
|
||||
|
||||
return {
|
||||
id: hunt.id,
|
||||
location: this.toLocationSummary(character.currentLocation),
|
||||
encounters: encounters.map((encounter) =>
|
||||
this.toEncounterDto(encounter, encounter.monster, character),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
private toEncounterDto(
|
||||
encounter: HuntEncounter,
|
||||
monster: MonsterDefinition,
|
||||
character: Character,
|
||||
): HuntEncounterDto {
|
||||
return {
|
||||
id: encounter.id,
|
||||
monster: {
|
||||
key: monster.key,
|
||||
name: monster.name,
|
||||
level: monster.level,
|
||||
artworkPath: monster.artworkPath,
|
||||
},
|
||||
dangerRating: calculateDangerRating(
|
||||
{ attack: character.baseAttack, armor: 0, hp: character.baseHp },
|
||||
{ attack: monster.attack, armor: monster.armor, hp: monster.maxHp },
|
||||
),
|
||||
status: encounter.status,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls `count` independent weighted picks from `pool`. Each slot walks
|
||||
* the pool in the order it was supplied, accumulating weight, and picks
|
||||
|
||||
Reference in New Issue
Block a user