Commit 8a77f86a authored by hewenhao's avatar hewenhao

feat: 联调

parent 7e292b95
...@@ -13,10 +13,12 @@ declare module '*.styl'; ...@@ -13,10 +13,12 @@ declare module '*.styl';
type CountUptime = React.FC<{ maxNum }> type CountUptime = React.FC<{ maxNum }>
type CountUpTime = React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & { 'max-value'?: number, onTimeup?: () => void }, HTMLElement>
declare namespace JSX{ declare namespace JSX{
interface IntrinsicElements{ interface IntrinsicElements {
// 扩展 IntrinsicElements 否则无法识别自定义标签 // 扩展 IntrinsicElements 否则无法识别自定义标签
'count-up-time': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & { 'max-value'?: number, onTimeup?: () => void }, HTMLElement> 'count-up-time': CountUpTime
} }
} }
......
import { requestAfterSilentLogin } from '@/utils/request' import { requestAfterSilentLogin } from '@/utils/request'
import { getStorage, StorageKeys } from '@/utils/storage' import { getStorage, StorageKeys } from '@/utils/storage'
import { type QuestionType } from '@/pages/game/play/types' import { QuestionItem, type QuestionType } from '@/pages/game/play/types'
export const getQuestionList = (stageId: number) => { export const getQuestionList = (stageId: number) => {
return requestAfterSilentLogin<QuestionType[], { stageId: number, userId?: number }>({ return requestAfterSilentLogin<QuestionType[], { stageId: number, userId?: number }>({
...@@ -29,7 +29,7 @@ export const enum StageLevel { ...@@ -29,7 +29,7 @@ export const enum StageLevel {
B = 'B' B = 'B'
} }
export type Stage = { export interface Stage {
content: string; content: string;
gear: number; gear: number;
id: number; id: number;
...@@ -43,6 +43,35 @@ export type Stage = { ...@@ -43,6 +43,35 @@ export type Stage = {
part?: number; part?: number;
} }
type StageRank = {
bestResultTime: number;
firstResultTime: number;
me: boolean;
nickName: string;
no: number;
secondName: string;
userId: number;
}
export interface StageDetail extends Stage {
aTime: number;
bTime: number;
sTime: number;
firstTime: boolean;
content: string;
bestResultTime: number;
ranks?: StageRank[];
}
/** 获取关卡详情 */
export function getStageDetail (stageId: number) {
return requestAfterSilentLogin<StageDetail, { stageId: number, userId?: number }>({
method: 'GET',
url: '/service-idea/stage/stageDetail',
data: { stageId, userId: getStorage(StorageKeys.userInfo)?.userId }
})
}
/** 获取关卡列表 */ /** 获取关卡列表 */
export function getStageList () { export function getStageList () {
return requestAfterSilentLogin<Stage[], { chapter: number; userId?: number }>({ return requestAfterSilentLogin<Stage[], { chapter: number; userId?: number }>({
...@@ -51,3 +80,47 @@ export function getStageList () { ...@@ -51,3 +80,47 @@ export function getStageList () {
data: { chapter: 1, userId: getStorage(StorageKeys.userInfo)?.userId } data: { chapter: 1, userId: getStorage(StorageKeys.userInfo)?.userId }
}) })
} }
export interface CompleteQuestion extends QuestionItem {
userAnswers: string[];
}
export interface CompleteStageParam {
correctNum: number;
level: StageLevel;
num: number;
questions: CompleteQuestion[];
resultTime: number;
stageId: number;
}
interface CompleteStageParamIn extends CompleteStageParam {
userId?: number;
}
export interface CompleteStageOut {
averageTime: number;
gear: number;
level: StageLevel;
nextGear: number;
nextGearTime: number;
pointAfter: number;
pointBefore: number;
ranks: StageRank[];
rate: number;
resultTime: number;
sLevelTime: number;
upGear: boolean;
}
/** 完成 */
export function completeStage (arg: CompleteStageParam) {
return requestAfterSilentLogin<CompleteStageOut, CompleteStageParamIn>({
method: 'POST',
url: '/service-idea/stage/completeStage',
data: {
...arg,
userId: getStorage(StorageKeys.userInfo)?.userId
}
})
}
...@@ -37,6 +37,7 @@ Component({ ...@@ -37,6 +37,7 @@ Component({
attached () { attached () {
this._tick = 0 this._tick = 0
this.startCount() this.startCount()
console.log(this)
}, },
methods: { methods: {
......
import { View, Image } from '@tarojs/components' import { View, Image } from '@tarojs/components'
import { useState, useEffect, useCallback, useMemo } from 'react' import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { createSelectorQuery } from '@tarojs/taro' import { createSelectorQuery, getCurrentInstance } from '@tarojs/taro'
import { useStoreState } from '@/store/hooks' import { useStoreState } from '@/store/hooks'
import { type StageDetail } from '@/api'
import styles from './count-up.module.scss' import styles from './count-up.module.scss'
const speed = 4
const id = '_process__' const id = '_process__'
const CountUp = () => { type CountUpProps = {
stageDetail: StageDetail
}
const CountUp = (props: CountUpProps) => {
const { stageDetail } = props
const currentQuestionIndex = useStoreState(states => states.gameModel.currentQuestionIndex) const currentQuestionIndex = useStoreState(states => states.gameModel.currentQuestionIndex)
const questionList = useStoreState(state => state.gameModel.questionList) const questionList = useStoreState(state => state.gameModel.questionList)
const isSubmit = useStoreState(state => state.gameModel.isSubmit)
const [width, setWidth] = useState(0) const [width, setWidth] = useState(0)
const countUp = useRef<any>(null)
const questionLength = useMemo(() => { const questionLength = useMemo(() => {
return questionList.length return questionList.length
}, [questionList]) }, [questionList])
useEffect(() => { useEffect(() => {
const query = createSelectorQuery() createSelectorQuery().select(`#${id}`)
query.select(`#${id}`)
.boundingClientRect() .boundingClientRect()
.exec((res) => { .exec((res) => {
console.log(res) console.log(res)
...@@ -32,15 +38,29 @@ const CountUp = () => { ...@@ -32,15 +38,29 @@ const CountUp = () => {
const roleStyle = useMemo(() => { const roleStyle = useMemo(() => {
return { return {
transform: `translateX(${width}px)`, transform: `translateX(${width}px)`,
transition: `transform ${questionLength * speed}s linear`, transition: `transform ${stageDetail.bTime}s linear`,
} }
}, [width, questionLength]) }, [width, stageDetail.bTime])
useEffect(() => {
if (isSubmit && countUp.current?.sid) {
console.log(countUp.current)
const comp = getCurrentInstance()?.page?.selectComponent?.(`#${countUp.current?.sid}`) as any
comp?.stop?.()
console.log(comp, 11)
}
}, [isSubmit])
const processInnerStyle = useMemo(() => { const processInnerStyle = useMemo(() => {
if (isSubmit) {
return {
width: '100%'
}
}
return { return {
width: `${currentQuestionIndex * 100 / questionLength}%` width: `${currentQuestionIndex * 100 / questionLength}%`
} }
}, [currentQuestionIndex, questionLength]) }, [currentQuestionIndex, questionLength, isSubmit])
const handleTimeUp = useCallback(() => { const handleTimeUp = useCallback(() => {
console.log('upd1') console.log('upd1')
...@@ -58,7 +78,7 @@ const CountUp = () => { ...@@ -58,7 +78,7 @@ const CountUp = () => {
</View> </View>
<View className={styles.time}> <View className={styles.time}>
<Image src={require('../assets/count-time.png')} className={styles.icon}></Image> <Image src={require('../assets/count-time.png')} className={styles.icon}></Image>
<count-up-time max-value={60 * 60} onTimeup={handleTimeUp} /> <count-up-time max-value={60 * 60} onTimeup={handleTimeUp} ref={countUp} />
</View> </View>
</View> </View>
) )
......
import { View, Image, Text } from '@tarojs/components' import { View, Image, Text } from '@tarojs/components'
import { getMenuButtonBoundingClientRect } from '@tarojs/taro' import { getMenuButtonBoundingClientRect, navigateBack } from '@tarojs/taro'
import { useState, memo } from 'react' import { useState, memo } from 'react'
import { useStoreState } from '@/store/hooks' import { useStoreState } from '@/store/hooks'
...@@ -19,8 +19,11 @@ const PageHead = () => { ...@@ -19,8 +19,11 @@ const PageHead = () => {
}} }}
> >
<View className={styles.inner} style={{ height: `${nav.height + 10}px` }}> <View className={styles.inner} style={{ height: `${nav.height + 10}px` }}>
<Image src={require('../assets/arrow.png')} className={styles.arrow}></Image> <Image src={require('../assets/arrow.png')} className={styles.arrow} onClick={() => navigateBack()}></Image>
<Text>{currentQuestionIndex + 1}/{questionList.length}</Text> {questionList.length > 0
? (<Text>{currentQuestionIndex + 1}/{questionList.length}</Text>)
: (<Text>出错了</Text>)
}
</View> </View>
</View> </View>
</View> </View>
......
...@@ -14,6 +14,7 @@ import styles from './index.module.scss' ...@@ -14,6 +14,7 @@ import styles from './index.module.scss'
const GamePlay = () => { const GamePlay = () => {
const currentQuestion = useStoreState(states => states.gameModel.currentQuestion) const currentQuestion = useStoreState(states => states.gameModel.currentQuestion)
const getQuestionList = useStoreActions(actions => actions.gameModel.getQuestionList) const getQuestionList = useStoreActions(actions => actions.gameModel.getQuestionList)
const stageDetail = useStoreState(state => state.gameModel.stageDetail)
const router = useRouter<{ id: string }>() const router = useRouter<{ id: string }>()
...@@ -23,10 +24,10 @@ const GamePlay = () => { ...@@ -23,10 +24,10 @@ const GamePlay = () => {
return ( return (
<View className={styles.viewport}> <View className={styles.viewport}>
{currentQuestion && ( <PageHead />
{currentQuestion && stageDetail && (
<> <>
<PageHead /> <CountUp stageDetail={stageDetail} />
<CountUp />
</> </>
)} )}
<ScrollView className={styles.body} scrollY> <ScrollView className={styles.body} scrollY>
...@@ -34,11 +35,13 @@ const GamePlay = () => { ...@@ -34,11 +35,13 @@ const GamePlay = () => {
<Question question={currentQuestion} /> <Question question={currentQuestion} />
)} )}
</ScrollView> </ScrollView>
{currentQuestion?.questionType !== '选择题' && (
<NumberKeyboard />
)}
{currentQuestion && ( {currentQuestion && (
<>
{currentQuestion?.questionType !== '选择题' && (
<NumberKeyboard />
)}
<PageFooter /> <PageFooter />
</>
)} )}
</View> </View>
) )
......
import { action, Action, computed, Computed, Thunk, thunk } from 'easy-peasy' import { action, Action, computed, Computed, State, Thunk, thunk } from 'easy-peasy'
import { AppStoreModel } from '@/store/store-model' import { AppStoreModel } from '@/store/store-model'
import { getQuestionList } from '@/api' import { getQuestionList, type StageDetail, getStageDetail, completeStage } from '@/api'
import { showLoading, hideLoading } from '@tarojs/taro' import { showLoading, hideLoading, showModal } from '@tarojs/taro'
import { import {
QuestionType, QuestionType,
QuestionAnswer, QuestionAnswer,
isSelectionQuestion, isSelectionQuestion,
// QuestionOption, // QuestionOption,
} from '../types' } from '../types'
import { buildCompleteStageParam } from './utils'
// import questionListJson from './test.json' // import questionListJson from './test.json'
export interface GameModel { export interface GameModel {
/** 题目列表 */ /** 题目列表 */
questionList: QuestionType[]; questionList: QuestionType[];
stageDetail: StageDetail | null;
gameStartTime: number;
updateState: Action<GameModel, Partial<State<GameModel>>>;
/** 当前题目 */ /** 当前题目 */
currentQuestion: Computed<GameModel, QuestionType | undefined>; currentQuestion: Computed<GameModel, QuestionType | undefined>;
/** 当前题目下标 */ /** 当前题目下标 */
...@@ -40,12 +44,27 @@ export interface GameModel { ...@@ -40,12 +44,27 @@ export interface GameModel {
getQuestionList: Thunk<GameModel, number, void, AppStoreModel>; getQuestionList: Thunk<GameModel, number, void, AppStoreModel>;
handleGoNext: Thunk<GameModel, void, void, AppStoreModel>; handleGoNext: Thunk<GameModel, void, void, AppStoreModel>;
isSubmit: boolean;
submit: Thunk<GameModel, void, void, AppStoreModel>;
} }
const gameModel: GameModel = { const gameModel: GameModel = {
questionList: [], questionList: [],
gameStartTime: 0,
isSubmit: false,
stageDetail: null,
updateState: action((state, obj) => {
for (const key in obj) {
state[key] = obj[key]
}
}),
currentInputIndex: 0, currentInputIndex: 0,
currentQuestionIndex: 0, currentQuestionIndex: 0,
updateCurrentInputIndex: action((state, num) => { updateCurrentInputIndex: action((state, num) => {
state.currentInputIndex = num state.currentInputIndex = num
}), }),
...@@ -68,6 +87,7 @@ const gameModel: GameModel = { ...@@ -68,6 +87,7 @@ const gameModel: GameModel = {
} }
return questionAnswers?.every((c) => !!c.userAnswer) ?? false return questionAnswers?.every((c) => !!c.userAnswer) ?? false
}), }),
updateSelectionAnswer: action((state, index) => { updateSelectionAnswer: action((state, index) => {
const question = state.questionList[state.currentQuestionIndex] const question = state.questionList[state.currentQuestionIndex]
if (isSelectionQuestion(question)) { if (isSelectionQuestion(question)) {
...@@ -122,6 +142,7 @@ const gameModel: GameModel = { ...@@ -122,6 +142,7 @@ const gameModel: GameModel = {
if (!canGoNext) return if (!canGoNext) return
if (questionList.length === currentQuestionIndex + 1) { if (questionList.length === currentQuestionIndex + 1) {
console.log('submit') console.log('submit')
actions.submit()
return return
} }
...@@ -131,10 +152,46 @@ const gameModel: GameModel = { ...@@ -131,10 +152,46 @@ const gameModel: GameModel = {
getQuestionList: thunk(async (actions, round) => { getQuestionList: thunk(async (actions, round) => {
try { try {
showLoading() showLoading()
const { data: questionList } = await getQuestionList(round) const [{ data: questionList }, { data: stageDetail }] = await Promise.all([
actions.updateList(questionList) getQuestionList(round),
getStageDetail(round)
])
actions.updateState({
questionList,
stageDetail,
gameStartTime: Date.now(),
})
} catch (err) {
showModal({
title: '提示',
content: err.message || '出错了',
showCancel: false,
})
actions.updateState({
questionList: [],
stageDetail: null
})
} finally {
hideLoading()
}
}),
submit: thunk(async (actions, __, helpers) => {
try {
showLoading({
mask: true,
title: '提交中'
})
actions.updateState({ isSubmit: true })
const { questionList, gameStartTime, stageDetail } = helpers.getState()
await completeStage(buildCompleteStageParam(questionList, stageDetail!, gameStartTime))
} catch (err) { } catch (err) {
actions.updateList([]) showModal({
title: '提示',
content: err.message || '出错了',
showCancel: false,
})
console.log(err)
} finally { } finally {
hideLoading() hideLoading()
} }
......
import { type CompleteStageParam, type StageDetail, StageLevel, type CompleteQuestion } from '@/api'
import { type QuestionType, isBlankQuestion, isVerticalDivisionQuestion, isSelectionQuestion } from '../types'
export function buildCompleteStageParam (questionList: QuestionType[], stageDetail: StageDetail, gameStartTime: number): CompleteStageParam {
const correctNum = questionList.map(c => determinQuestion(c)).filter(Boolean).length
const resultTime = Math.round((Date.now() - gameStartTime) / 1000)
const { sTime, aTime, bTime } = stageDetail
let level = StageLevel.B
const num = questionList.length
if (correctNum === num) {
if (resultTime <= sTime) {
level = StageLevel.S
} else if (resultTime <= aTime) {
level = StageLevel.A
} else if (resultTime <= bTime) {
level = StageLevel.B
}
}
return {
correctNum,
level,
stageId: stageDetail.id,
questions: questionList.map(convert),
num,
resultTime: Math.round((Date.now() - gameStartTime) / 1000),
}
}
function convert (inQuestion: QuestionType): CompleteQuestion {
if (isBlankQuestion(inQuestion)) {
return {
...inQuestion,
userAnswers: inQuestion.answers.map(c => c.userAnswer!),
}
}
if (isSelectionQuestion(inQuestion)) {
return {
...inQuestion,
userAnswers: inQuestion.options.filter(c => c.userAnswer).map(c => c.index)
}
}
if (isVerticalDivisionQuestion(inQuestion)) {
return {
...inQuestion,
userAnswers: inQuestion.answers.map(c => c.userAnswer!),
}
}
throw new Error('question not supported')
}
/** 判题 */
function determinQuestion (question: QuestionType) {
if (isBlankQuestion(question)) {
return question.answers.every(c => c.userAnswer === c.contentText)
}
if (isSelectionQuestion(question)) {
return question.options.every(c => c.answer === c.userAnswer)
}
if (isVerticalDivisionQuestion(question)) {
return question.answers.every(c => c.userAnswer === c.contentText)
}
throw new Error('question not supported')
}
...@@ -8,6 +8,10 @@ export interface QuestionItem { ...@@ -8,6 +8,10 @@ export interface QuestionItem {
questionType: string; questionType: string;
answers: QuestionAnswer[]; answers: QuestionAnswer[];
simpleType?: boolean; simpleType?: boolean;
contentText: string;
options: QuestionOption[];
questionItems?: RandomQuestionItem[];
sort: number;
} }
export interface BlankQuestion extends QuestionItem { export interface BlankQuestion extends QuestionItem {
...@@ -21,9 +25,9 @@ export interface SelectionQuestion extends QuestionItem { ...@@ -21,9 +25,9 @@ export interface SelectionQuestion extends QuestionItem {
options: QuestionOption[]; options: QuestionOption[];
} }
export interface RandomQuestion extends QuestionItem { // export interface RandomQuestion extends QuestionItem {
questionItems?: RandomQuestionItem[]; // questionItems?: RandomQuestionItem[];
} // }
/** 带余除法 */ /** 带余除法 */
export interface DivisionWithRemainderQuestion extends QuestionItem { export interface DivisionWithRemainderQuestion extends QuestionItem {
...@@ -42,7 +46,7 @@ export interface MultiplicationQuestion extends QuestionItem { ...@@ -42,7 +46,7 @@ export interface MultiplicationQuestion extends QuestionItem {
questionItems: []; questionItems: [];
} }
export type QuestionType = BlankQuestion | SelectionQuestion | RandomQuestion export type QuestionType = BlankQuestion | SelectionQuestion | VerticalDivisionQuestion
export function isBlankQuestion (q: QuestionType): q is BlankQuestion { export function isBlankQuestion (q: QuestionType): q is BlankQuestion {
return q?.questionType === '填空题' || q?.questionType === '随机填空' return q?.questionType === '填空题' || q?.questionType === '随机填空'
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment