classicSequentialRule.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  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): GameEffect {
  243. if (control.kind === 'start') {
  244. return {
  245. type: 'control_completed',
  246. controlId: control.id,
  247. controlKind: 'start',
  248. sequence: null,
  249. label: control.label,
  250. displayTitle: '比赛开始',
  251. displayBody: '已完成开始点打卡,前往 1 号点。',
  252. }
  253. }
  254. if (control.kind === 'finish') {
  255. return {
  256. type: 'control_completed',
  257. controlId: control.id,
  258. controlKind: 'finish',
  259. sequence: null,
  260. label: control.label,
  261. displayTitle: '比赛结束',
  262. displayBody: '已完成终点打卡,本局结束。',
  263. }
  264. }
  265. const sequenceText = typeof control.sequence === 'number' ? String(control.sequence) : control.label
  266. const displayTitle = control.displayContent ? control.displayContent.title : `完成 ${sequenceText}`
  267. const displayBody = control.displayContent ? control.displayContent.body : control.label
  268. return {
  269. type: 'control_completed',
  270. controlId: control.id,
  271. controlKind: 'control',
  272. sequence: control.sequence,
  273. label: control.label,
  274. displayTitle,
  275. displayBody,
  276. }
  277. }
  278. function applyCompletion(definition: GameDefinition, state: GameSessionState, currentTarget: GameControl, at: number): GameResult {
  279. const completedControlIds = state.completedControlIds.includes(currentTarget.id)
  280. ? state.completedControlIds
  281. : [...state.completedControlIds, currentTarget.id]
  282. const nextTarget = getNextTarget(definition, currentTarget)
  283. const completedFinish = currentTarget.kind === 'finish'
  284. const finished = completedFinish || (!nextTarget && definition.autoFinishOnLastControl)
  285. const nextState: GameSessionState = {
  286. ...state,
  287. startedAt: currentTarget.kind === 'start' && state.startedAt === null ? at : state.startedAt,
  288. completedControlIds,
  289. skippedControlIds: currentTarget.id === state.currentTargetControlId
  290. ? state.skippedControlIds.filter((controlId) => controlId !== currentTarget.id)
  291. : state.skippedControlIds,
  292. currentTargetControlId: nextTarget ? nextTarget.id : null,
  293. inRangeControlId: null,
  294. score: getScoringControls(definition).filter((control) => completedControlIds.includes(control.id)).length,
  295. status: finished ? 'finished' : state.status,
  296. endedAt: finished ? at : state.endedAt,
  297. guidanceState: nextTarget ? 'searching' : 'searching',
  298. modeState: {
  299. mode: 'classic-sequential',
  300. phase: resolveClassicPhase(nextTarget, currentTarget, finished),
  301. },
  302. }
  303. const effects: GameEffect[] = [buildCompletedEffect(currentTarget)]
  304. if (finished) {
  305. effects.push({ type: 'session_finished' })
  306. }
  307. return {
  308. nextState,
  309. presentation: buildPresentation(definition, nextState),
  310. effects,
  311. }
  312. }
  313. function applySkip(
  314. definition: GameDefinition,
  315. state: GameSessionState,
  316. currentTarget: GameControl,
  317. location: LonLatPoint | null,
  318. ): GameResult {
  319. const nextTarget = getNextTarget(definition, currentTarget)
  320. const nextPhase = nextTarget && nextTarget.kind === 'finish' ? 'finish' : 'course'
  321. const nextGuidance = resolveGuidanceForTarget(definition, state, nextTarget, location)
  322. const nextState: GameSessionState = {
  323. ...state,
  324. skippedControlIds: state.skippedControlIds.includes(currentTarget.id)
  325. ? state.skippedControlIds
  326. : [...state.skippedControlIds, currentTarget.id],
  327. currentTargetControlId: nextTarget ? nextTarget.id : null,
  328. inRangeControlId: nextGuidance.inRangeControlId,
  329. guidanceState: nextGuidance.guidanceState,
  330. modeState: {
  331. mode: 'classic-sequential',
  332. phase: nextTarget ? nextPhase : 'done',
  333. },
  334. }
  335. return {
  336. nextState,
  337. presentation: buildPresentation(definition, nextState),
  338. effects: [
  339. ...nextGuidance.effects,
  340. { type: 'punch_feedback', text: buildSkipFeedbackText(currentTarget), tone: 'neutral' },
  341. ],
  342. }
  343. }
  344. export class ClassicSequentialRule implements RulePlugin {
  345. get mode(): 'classic-sequential' {
  346. return 'classic-sequential'
  347. }
  348. initialize(definition: GameDefinition): GameSessionState {
  349. return {
  350. status: 'idle',
  351. startedAt: null,
  352. endedAt: null,
  353. completedControlIds: [],
  354. skippedControlIds: [],
  355. currentTargetControlId: getInitialTargetId(definition),
  356. inRangeControlId: null,
  357. score: 0,
  358. guidanceState: 'searching',
  359. modeState: {
  360. mode: 'classic-sequential',
  361. phase: 'start',
  362. },
  363. }
  364. }
  365. buildPresentation(definition: GameDefinition, state: GameSessionState): GamePresentationState {
  366. return buildPresentation(definition, state)
  367. }
  368. reduce(definition: GameDefinition, state: GameSessionState, event: GameEvent): GameResult {
  369. if (event.type === 'session_started') {
  370. const nextState: GameSessionState = {
  371. ...state,
  372. status: 'running',
  373. startedAt: null,
  374. endedAt: null,
  375. inRangeControlId: null,
  376. guidanceState: 'searching',
  377. modeState: {
  378. mode: 'classic-sequential',
  379. phase: 'start',
  380. },
  381. }
  382. return {
  383. nextState,
  384. presentation: buildPresentation(definition, nextState),
  385. effects: [{ type: 'session_started' }],
  386. }
  387. }
  388. if (event.type === 'session_ended') {
  389. const nextState: GameSessionState = {
  390. ...state,
  391. status: 'finished',
  392. endedAt: event.at,
  393. guidanceState: 'searching',
  394. modeState: {
  395. mode: 'classic-sequential',
  396. phase: 'done',
  397. },
  398. }
  399. return {
  400. nextState,
  401. presentation: buildPresentation(definition, nextState),
  402. effects: [{ type: 'session_finished' }],
  403. }
  404. }
  405. if (state.status !== 'running' || !state.currentTargetControlId) {
  406. return {
  407. nextState: state,
  408. presentation: buildPresentation(definition, state),
  409. effects: [],
  410. }
  411. }
  412. const currentTarget = getCurrentTarget(definition, state)
  413. if (!currentTarget) {
  414. return {
  415. nextState: state,
  416. presentation: buildPresentation(definition, state),
  417. effects: [],
  418. }
  419. }
  420. if (event.type === 'gps_updated') {
  421. const distanceMeters = getApproxDistanceMeters(currentTarget.point, { lon: event.lon, lat: event.lat })
  422. const inRangeControlId = distanceMeters <= definition.punchRadiusMeters ? currentTarget.id : null
  423. const guidanceState = getGuidanceState(definition, distanceMeters)
  424. const nextState: GameSessionState = {
  425. ...state,
  426. inRangeControlId,
  427. guidanceState,
  428. }
  429. const guidanceEffects = getGuidanceEffects(state.guidanceState, guidanceState, currentTarget.id)
  430. if (definition.punchPolicy === 'enter' && inRangeControlId === currentTarget.id) {
  431. const completionResult = applyCompletion(definition, nextState, currentTarget, event.at)
  432. return {
  433. ...completionResult,
  434. effects: [...guidanceEffects, ...completionResult.effects],
  435. }
  436. }
  437. return {
  438. nextState,
  439. presentation: buildPresentation(definition, nextState),
  440. effects: guidanceEffects,
  441. }
  442. }
  443. if (event.type === 'punch_requested') {
  444. if (state.inRangeControlId !== currentTarget.id) {
  445. return {
  446. nextState: state,
  447. presentation: buildPresentation(definition, state),
  448. effects: [{ type: 'punch_feedback', text: currentTarget.kind === 'start' ? '未进入开始点打卡范围' : currentTarget.kind === 'finish' ? '未进入终点打卡范围' : '未进入目标打点范围', tone: 'warning' }],
  449. }
  450. }
  451. return applyCompletion(definition, state, currentTarget, event.at)
  452. }
  453. if (event.type === 'skip_requested') {
  454. if (!definition.skipEnabled) {
  455. return {
  456. nextState: state,
  457. presentation: buildPresentation(definition, state),
  458. effects: [{ type: 'punch_feedback', text: '当前配置未开启跳点', tone: 'warning' }],
  459. }
  460. }
  461. if (currentTarget.kind !== 'control') {
  462. return {
  463. nextState: state,
  464. presentation: buildPresentation(definition, state),
  465. effects: [{ type: 'punch_feedback', text: currentTarget.kind === 'start' ? '开始点不可跳过' : '终点不可跳过', tone: 'warning' }],
  466. }
  467. }
  468. if (event.lon === null || event.lat === null) {
  469. return {
  470. nextState: state,
  471. presentation: buildPresentation(definition, state),
  472. effects: [{ type: 'punch_feedback', text: '当前无定位,无法跳点', tone: 'warning' }],
  473. }
  474. }
  475. const distanceMeters = getApproxDistanceMeters(currentTarget.point, { lon: event.lon, lat: event.lat })
  476. if (distanceMeters > definition.skipRadiusMeters) {
  477. return {
  478. nextState: state,
  479. presentation: buildPresentation(definition, state),
  480. effects: [{ type: 'punch_feedback', text: `未进入跳点范围 (${Math.round(definition.skipRadiusMeters)}m)`, tone: 'warning' }],
  481. }
  482. }
  483. return applySkip(
  484. definition,
  485. state,
  486. currentTarget,
  487. { lon: event.lon, lat: event.lat },
  488. )
  489. }
  490. return {
  491. nextState: state,
  492. presentation: buildPresentation(definition, state),
  493. effects: [],
  494. }
  495. }
  496. }