classicSequentialRule.ts 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576
  1. import { type LonLatPoint } from '../../utils/projection'
  2. import { DEFAULT_GAME_AUDIO_CONFIG } from '../audio/audioConfig'
  3. import { type GameControl, type GameDefinition } from '../core/gameDefinition'
  4. import { type GameEvent } from '../core/gameEvent'
  5. import { type GameEffect, type GameResult } from '../core/gameResult'
  6. import { type GameSessionState } from '../core/gameSessionState'
  7. import { EMPTY_GAME_PRESENTATION_STATE, type GamePresentationState } from '../presentation/presentationState'
  8. import { type HudPresentationState } from '../presentation/hudPresentationState'
  9. import { type MapPresentationState } from '../presentation/mapPresentationState'
  10. import { type RulePlugin } from './rulePlugin'
  11. type ClassicSequentialModeState = {
  12. mode: 'classic-sequential'
  13. phase: 'start' | 'course' | 'finish' | 'done'
  14. }
  15. function getApproxDistanceMeters(a: LonLatPoint, b: LonLatPoint): number {
  16. const avgLatRad = ((a.lat + b.lat) / 2) * Math.PI / 180
  17. const dx = (b.lon - a.lon) * 111320 * Math.cos(avgLatRad)
  18. const dy = (b.lat - a.lat) * 110540
  19. return Math.sqrt(dx * dx + dy * dy)
  20. }
  21. function getScoringControls(definition: GameDefinition): GameControl[] {
  22. return definition.controls.filter((control) => control.kind === 'control')
  23. }
  24. function getSequentialTargets(definition: GameDefinition): GameControl[] {
  25. return definition.controls
  26. }
  27. function getCompletedControlSequences(definition: GameDefinition, state: GameSessionState): number[] {
  28. return getScoringControls(definition)
  29. .filter((control) => state.completedControlIds.includes(control.id) && typeof control.sequence === 'number')
  30. .map((control) => control.sequence as number)
  31. }
  32. function getSkippedControlSequences(definition: GameDefinition, state: GameSessionState): number[] {
  33. return getScoringControls(definition)
  34. .filter((control) => state.skippedControlIds.includes(control.id) && typeof control.sequence === 'number')
  35. .map((control) => control.sequence as number)
  36. }
  37. function getCurrentTarget(definition: GameDefinition, state: GameSessionState): GameControl | null {
  38. return getSequentialTargets(definition).find((control) => control.id === state.currentTargetControlId) || null
  39. }
  40. function getNextTarget(definition: GameDefinition, currentTarget: GameControl): GameControl | null {
  41. const targets = getSequentialTargets(definition)
  42. const currentIndex = targets.findIndex((control) => control.id === currentTarget.id)
  43. return currentIndex >= 0 && currentIndex < targets.length - 1
  44. ? targets[currentIndex + 1]
  45. : null
  46. }
  47. function getCompletedLegIndices(definition: GameDefinition, state: GameSessionState): number[] {
  48. const targets = getSequentialTargets(definition)
  49. const completedLegIndices: number[] = []
  50. for (let index = 1; index < targets.length; index += 1) {
  51. if (state.completedControlIds.includes(targets[index].id)) {
  52. completedLegIndices.push(index - 1)
  53. }
  54. }
  55. return completedLegIndices
  56. }
  57. function getTargetText(control: GameControl): string {
  58. if (control.kind === 'start') {
  59. return '开始点'
  60. }
  61. if (control.kind === 'finish') {
  62. return '终点'
  63. }
  64. return '目标圈'
  65. }
  66. function getGuidanceState(definition: GameDefinition, distanceMeters: number): GameSessionState['guidanceState'] {
  67. if (distanceMeters <= definition.punchRadiusMeters) {
  68. return 'ready'
  69. }
  70. const approachDistanceMeters = definition.audioConfig ? definition.audioConfig.approachDistanceMeters : DEFAULT_GAME_AUDIO_CONFIG.approachDistanceMeters
  71. if (distanceMeters <= approachDistanceMeters) {
  72. return 'approaching'
  73. }
  74. return 'searching'
  75. }
  76. function getGuidanceEffects(
  77. previousState: GameSessionState['guidanceState'],
  78. nextState: GameSessionState['guidanceState'],
  79. controlId: string | null,
  80. ): GameEffect[] {
  81. if (previousState === nextState) {
  82. return []
  83. }
  84. return [{ type: 'guidance_state_changed', guidanceState: nextState, controlId }]
  85. }
  86. function buildPunchHintText(definition: GameDefinition, state: GameSessionState, currentTarget: GameControl | null): string {
  87. if (state.status === 'idle') {
  88. return '点击开始后先打开始点'
  89. }
  90. if (state.status === 'finished') {
  91. return '本局已完成'
  92. }
  93. if (!currentTarget) {
  94. return '本局已完成'
  95. }
  96. const targetText = getTargetText(currentTarget)
  97. if (state.inRangeControlId !== currentTarget.id) {
  98. return definition.punchPolicy === 'enter'
  99. ? `进入${targetText}自动打点`
  100. : `进入${targetText}后点击打点`
  101. }
  102. return definition.punchPolicy === 'enter'
  103. ? `${targetText}内,自动打点中`
  104. : `${targetText}内,可点击打点`
  105. }
  106. function buildSkipFeedbackText(currentTarget: GameControl): string {
  107. if (currentTarget.kind === 'start') {
  108. return '开始点不可跳过'
  109. }
  110. if (currentTarget.kind === 'finish') {
  111. return '终点不可跳过'
  112. }
  113. return `已跳过检查点 ${typeof currentTarget.sequence === 'number' ? currentTarget.sequence : currentTarget.label}`
  114. }
  115. function resolveGuidanceForTarget(
  116. definition: GameDefinition,
  117. previousState: GameSessionState,
  118. target: GameControl | null,
  119. location: LonLatPoint | null,
  120. ): { guidanceState: GameSessionState['guidanceState']; inRangeControlId: string | null; effects: GameEffect[] } {
  121. if (!target || !location) {
  122. const guidanceState: GameSessionState['guidanceState'] = 'searching'
  123. return {
  124. guidanceState,
  125. inRangeControlId: null,
  126. effects: getGuidanceEffects(previousState.guidanceState, guidanceState, target ? target.id : null),
  127. }
  128. }
  129. const distanceMeters = getApproxDistanceMeters(target.point, location)
  130. const guidanceState = getGuidanceState(definition, distanceMeters)
  131. const inRangeControlId = distanceMeters <= definition.punchRadiusMeters ? target.id : null
  132. return {
  133. guidanceState,
  134. inRangeControlId,
  135. effects: getGuidanceEffects(previousState.guidanceState, guidanceState, target.id),
  136. }
  137. }
  138. function buildPresentation(definition: GameDefinition, state: GameSessionState): GamePresentationState {
  139. const scoringControls = getScoringControls(definition)
  140. const sequentialTargets = getSequentialTargets(definition)
  141. const currentTarget = getCurrentTarget(definition, state)
  142. const currentTargetIndex = currentTarget ? sequentialTargets.findIndex((control) => control.id === currentTarget.id) : -1
  143. const completedControls = scoringControls.filter((control) => state.completedControlIds.includes(control.id))
  144. const running = state.status === 'running'
  145. const activeLegIndices = running && currentTargetIndex > 0
  146. ? [currentTargetIndex - 1]
  147. : []
  148. const completedLegIndices = getCompletedLegIndices(definition, state)
  149. const punchButtonEnabled = running && !!currentTarget && state.inRangeControlId === currentTarget.id && definition.punchPolicy === 'enter-confirm'
  150. const activeStart = running && !!currentTarget && currentTarget.kind === 'start'
  151. const completedStart = definition.controls.some((control) => control.kind === 'start' && state.completedControlIds.includes(control.id))
  152. const activeFinish = running && !!currentTarget && currentTarget.kind === 'finish'
  153. const completedFinish = definition.controls.some((control) => control.kind === 'finish' && state.completedControlIds.includes(control.id))
  154. const punchButtonText = currentTarget
  155. ? currentTarget.kind === 'start'
  156. ? '开始打卡'
  157. : currentTarget.kind === 'finish'
  158. ? '结束打卡'
  159. : '打点'
  160. : '打点'
  161. const revealFullCourse = completedStart
  162. const hudPresentation: HudPresentationState = {
  163. actionTagText: '目标',
  164. distanceTagText: '点距',
  165. hudTargetControlId: currentTarget ? currentTarget.id : null,
  166. progressText: '0/0',
  167. punchButtonText,
  168. punchableControlId: punchButtonEnabled && currentTarget ? currentTarget.id : null,
  169. punchButtonEnabled,
  170. punchHintText: buildPunchHintText(definition, state, currentTarget),
  171. }
  172. if (!scoringControls.length) {
  173. return {
  174. map: {
  175. ...EMPTY_GAME_PRESENTATION_STATE.map,
  176. controlVisualMode: 'single-target',
  177. showCourseLegs: true,
  178. guidanceLegAnimationEnabled: true,
  179. focusableControlIds: [],
  180. focusedControlId: null,
  181. focusedControlSequences: [],
  182. activeStart,
  183. completedStart,
  184. activeFinish,
  185. focusedFinish: false,
  186. completedFinish,
  187. revealFullCourse,
  188. activeLegIndices,
  189. completedLegIndices,
  190. skippedControlIds: [],
  191. skippedControlSequences: [],
  192. },
  193. hud: hudPresentation,
  194. }
  195. }
  196. const mapPresentation: MapPresentationState = {
  197. controlVisualMode: 'single-target',
  198. showCourseLegs: true,
  199. guidanceLegAnimationEnabled: true,
  200. focusableControlIds: [],
  201. focusedControlId: null,
  202. focusedControlSequences: [],
  203. activeControlIds: running && currentTarget ? [currentTarget.id] : [],
  204. activeControlSequences: running && currentTarget && currentTarget.kind === 'control' && typeof currentTarget.sequence === 'number' ? [currentTarget.sequence] : [],
  205. activeStart,
  206. completedStart,
  207. activeFinish,
  208. focusedFinish: false,
  209. completedFinish,
  210. revealFullCourse,
  211. activeLegIndices,
  212. completedLegIndices,
  213. completedControlIds: completedControls.map((control) => control.id),
  214. completedControlSequences: getCompletedControlSequences(definition, state),
  215. skippedControlIds: state.skippedControlIds,
  216. skippedControlSequences: getSkippedControlSequences(definition, state),
  217. }
  218. return {
  219. map: mapPresentation,
  220. hud: {
  221. ...hudPresentation,
  222. progressText: `${completedControls.length}/${scoringControls.length}`,
  223. },
  224. }
  225. }
  226. function resolveClassicPhase(nextTarget: GameControl | null, currentTarget: GameControl, finished: boolean): ClassicSequentialModeState['phase'] {
  227. if (finished || currentTarget.kind === 'finish') {
  228. return 'done'
  229. }
  230. if (currentTarget.kind === 'start') {
  231. return nextTarget && nextTarget.kind === 'finish' ? 'finish' : 'course'
  232. }
  233. if (nextTarget && nextTarget.kind === 'finish') {
  234. return 'finish'
  235. }
  236. return 'course'
  237. }
  238. function getInitialTargetId(definition: GameDefinition): string | null {
  239. const firstTarget = getSequentialTargets(definition)[0]
  240. return firstTarget ? firstTarget.id : null
  241. }
  242. function buildCompletedEffect(control: GameControl, punchPolicy: GameDefinition['punchPolicy']): GameEffect {
  243. const allowAutoPopup = punchPolicy === 'enter'
  244. ? false
  245. : (control.displayContent ? control.displayContent.autoPopup : true)
  246. if (control.kind === 'start') {
  247. return {
  248. type: 'control_completed',
  249. controlId: control.id,
  250. controlKind: 'start',
  251. sequence: null,
  252. label: control.label,
  253. displayTitle: control.displayContent ? control.displayContent.title : '比赛开始',
  254. displayBody: control.displayContent ? control.displayContent.body : '已完成开始点打卡,前往 1 号点。',
  255. displayAutoPopup: allowAutoPopup,
  256. displayOnce: control.displayContent ? control.displayContent.once : false,
  257. displayPriority: control.displayContent ? control.displayContent.priority : 1,
  258. }
  259. }
  260. if (control.kind === 'finish') {
  261. return {
  262. type: 'control_completed',
  263. controlId: control.id,
  264. controlKind: 'finish',
  265. sequence: null,
  266. label: control.label,
  267. displayTitle: control.displayContent ? control.displayContent.title : '比赛结束',
  268. displayBody: control.displayContent ? control.displayContent.body : '已完成终点打卡,本局结束。',
  269. displayAutoPopup: allowAutoPopup,
  270. displayOnce: control.displayContent ? control.displayContent.once : false,
  271. displayPriority: control.displayContent ? control.displayContent.priority : 2,
  272. }
  273. }
  274. const sequenceText = typeof control.sequence === 'number' ? String(control.sequence) : control.label
  275. const displayTitle = control.displayContent ? control.displayContent.title : `完成 ${sequenceText}`
  276. const displayBody = control.displayContent ? control.displayContent.body : control.label
  277. return {
  278. type: 'control_completed',
  279. controlId: control.id,
  280. controlKind: 'control',
  281. sequence: control.sequence,
  282. label: control.label,
  283. displayTitle,
  284. displayBody,
  285. displayAutoPopup: allowAutoPopup,
  286. displayOnce: control.displayContent ? control.displayContent.once : false,
  287. displayPriority: control.displayContent ? control.displayContent.priority : 1,
  288. }
  289. }
  290. function applyCompletion(definition: GameDefinition, state: GameSessionState, currentTarget: GameControl, at: number): GameResult {
  291. const completedControlIds = state.completedControlIds.includes(currentTarget.id)
  292. ? state.completedControlIds
  293. : [...state.completedControlIds, currentTarget.id]
  294. const nextTarget = getNextTarget(definition, currentTarget)
  295. const completedFinish = currentTarget.kind === 'finish'
  296. const finished = completedFinish || (!nextTarget && definition.autoFinishOnLastControl)
  297. const nextState: GameSessionState = {
  298. ...state,
  299. startedAt: currentTarget.kind === 'start' && state.startedAt === null ? at : state.startedAt,
  300. completedControlIds,
  301. skippedControlIds: currentTarget.id === state.currentTargetControlId
  302. ? state.skippedControlIds.filter((controlId) => controlId !== currentTarget.id)
  303. : state.skippedControlIds,
  304. currentTargetControlId: nextTarget ? nextTarget.id : null,
  305. inRangeControlId: null,
  306. score: getScoringControls(definition).filter((control) => completedControlIds.includes(control.id)).length,
  307. status: finished ? 'finished' : state.status,
  308. endedAt: finished ? at : state.endedAt,
  309. guidanceState: nextTarget ? 'searching' : 'searching',
  310. modeState: {
  311. mode: 'classic-sequential',
  312. phase: resolveClassicPhase(nextTarget, currentTarget, finished),
  313. },
  314. }
  315. const effects: GameEffect[] = [buildCompletedEffect(currentTarget, definition.punchPolicy)]
  316. if (finished) {
  317. effects.push({ type: 'session_finished' })
  318. }
  319. return {
  320. nextState,
  321. presentation: buildPresentation(definition, nextState),
  322. effects,
  323. }
  324. }
  325. function applySkip(
  326. definition: GameDefinition,
  327. state: GameSessionState,
  328. currentTarget: GameControl,
  329. location: LonLatPoint | null,
  330. ): GameResult {
  331. const nextTarget = getNextTarget(definition, currentTarget)
  332. const nextPhase = nextTarget && nextTarget.kind === 'finish' ? 'finish' : 'course'
  333. const nextGuidance = resolveGuidanceForTarget(definition, state, nextTarget, location)
  334. const nextState: GameSessionState = {
  335. ...state,
  336. skippedControlIds: state.skippedControlIds.includes(currentTarget.id)
  337. ? state.skippedControlIds
  338. : [...state.skippedControlIds, currentTarget.id],
  339. currentTargetControlId: nextTarget ? nextTarget.id : null,
  340. inRangeControlId: nextGuidance.inRangeControlId,
  341. guidanceState: nextGuidance.guidanceState,
  342. modeState: {
  343. mode: 'classic-sequential',
  344. phase: nextTarget ? nextPhase : 'done',
  345. },
  346. }
  347. return {
  348. nextState,
  349. presentation: buildPresentation(definition, nextState),
  350. effects: [
  351. ...nextGuidance.effects,
  352. { type: 'punch_feedback', text: buildSkipFeedbackText(currentTarget), tone: 'neutral' },
  353. ],
  354. }
  355. }
  356. export class ClassicSequentialRule implements RulePlugin {
  357. get mode(): 'classic-sequential' {
  358. return 'classic-sequential'
  359. }
  360. initialize(definition: GameDefinition): GameSessionState {
  361. return {
  362. status: 'idle',
  363. startedAt: null,
  364. endedAt: null,
  365. completedControlIds: [],
  366. skippedControlIds: [],
  367. currentTargetControlId: getInitialTargetId(definition),
  368. inRangeControlId: null,
  369. score: 0,
  370. guidanceState: 'searching',
  371. modeState: {
  372. mode: 'classic-sequential',
  373. phase: 'start',
  374. },
  375. }
  376. }
  377. buildPresentation(definition: GameDefinition, state: GameSessionState): GamePresentationState {
  378. return buildPresentation(definition, state)
  379. }
  380. reduce(definition: GameDefinition, state: GameSessionState, event: GameEvent): GameResult {
  381. if (event.type === 'session_started') {
  382. const nextState: GameSessionState = {
  383. ...state,
  384. status: 'running',
  385. startedAt: null,
  386. endedAt: null,
  387. inRangeControlId: null,
  388. guidanceState: 'searching',
  389. modeState: {
  390. mode: 'classic-sequential',
  391. phase: 'start',
  392. },
  393. }
  394. return {
  395. nextState,
  396. presentation: buildPresentation(definition, nextState),
  397. effects: [{ type: 'session_started' }],
  398. }
  399. }
  400. if (event.type === 'session_ended') {
  401. const nextState: GameSessionState = {
  402. ...state,
  403. status: 'finished',
  404. endedAt: event.at,
  405. guidanceState: 'searching',
  406. modeState: {
  407. mode: 'classic-sequential',
  408. phase: 'done',
  409. },
  410. }
  411. return {
  412. nextState,
  413. presentation: buildPresentation(definition, nextState),
  414. effects: [{ type: 'session_finished' }],
  415. }
  416. }
  417. if (state.status !== 'running' || !state.currentTargetControlId) {
  418. return {
  419. nextState: state,
  420. presentation: buildPresentation(definition, state),
  421. effects: [],
  422. }
  423. }
  424. const currentTarget = getCurrentTarget(definition, state)
  425. if (!currentTarget) {
  426. return {
  427. nextState: state,
  428. presentation: buildPresentation(definition, state),
  429. effects: [],
  430. }
  431. }
  432. if (event.type === 'gps_updated') {
  433. const distanceMeters = getApproxDistanceMeters(currentTarget.point, { lon: event.lon, lat: event.lat })
  434. const inRangeControlId = distanceMeters <= definition.punchRadiusMeters ? currentTarget.id : null
  435. const guidanceState = getGuidanceState(definition, distanceMeters)
  436. const nextState: GameSessionState = {
  437. ...state,
  438. inRangeControlId,
  439. guidanceState,
  440. }
  441. const guidanceEffects = getGuidanceEffects(state.guidanceState, guidanceState, currentTarget.id)
  442. if (definition.punchPolicy === 'enter' && inRangeControlId === currentTarget.id) {
  443. const completionResult = applyCompletion(definition, nextState, currentTarget, event.at)
  444. return {
  445. ...completionResult,
  446. effects: [...guidanceEffects, ...completionResult.effects],
  447. }
  448. }
  449. return {
  450. nextState,
  451. presentation: buildPresentation(definition, nextState),
  452. effects: guidanceEffects,
  453. }
  454. }
  455. if (event.type === 'punch_requested') {
  456. if (state.inRangeControlId !== currentTarget.id) {
  457. return {
  458. nextState: state,
  459. presentation: buildPresentation(definition, state),
  460. effects: [{ type: 'punch_feedback', text: currentTarget.kind === 'start' ? '未进入开始点打卡范围' : currentTarget.kind === 'finish' ? '未进入终点打卡范围' : '未进入目标打点范围', tone: 'warning' }],
  461. }
  462. }
  463. return applyCompletion(definition, state, currentTarget, event.at)
  464. }
  465. if (event.type === 'skip_requested') {
  466. if (!definition.skipEnabled) {
  467. return {
  468. nextState: state,
  469. presentation: buildPresentation(definition, state),
  470. effects: [{ type: 'punch_feedback', text: '当前配置未开启跳点', tone: 'warning' }],
  471. }
  472. }
  473. if (currentTarget.kind !== 'control') {
  474. return {
  475. nextState: state,
  476. presentation: buildPresentation(definition, state),
  477. effects: [{ type: 'punch_feedback', text: currentTarget.kind === 'start' ? '开始点不可跳过' : '终点不可跳过', tone: 'warning' }],
  478. }
  479. }
  480. if (event.lon === null || event.lat === null) {
  481. return {
  482. nextState: state,
  483. presentation: buildPresentation(definition, state),
  484. effects: [{ type: 'punch_feedback', text: '当前无定位,无法跳点', tone: 'warning' }],
  485. }
  486. }
  487. const distanceMeters = getApproxDistanceMeters(currentTarget.point, { lon: event.lon, lat: event.lat })
  488. if (distanceMeters > definition.skipRadiusMeters) {
  489. return {
  490. nextState: state,
  491. presentation: buildPresentation(definition, state),
  492. effects: [{ type: 'punch_feedback', text: `未进入跳点范围 (${Math.round(definition.skipRadiusMeters)}m)`, tone: 'warning' }],
  493. }
  494. }
  495. return applySkip(
  496. definition,
  497. state,
  498. currentTarget,
  499. { lon: event.lon, lat: event.lat },
  500. )
  501. }
  502. return {
  503. nextState: state,
  504. presentation: buildPresentation(definition, state),
  505. effects: [],
  506. }
  507. }
  508. }