classicSequentialRule.ts 20 KB

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