Commit 100bfa5b authored by raca's avatar raca

Merge branch 'feature/2023-06-12-v1.1' of…

Merge branch 'feature/2023-06-12-v1.1' of https://118.24.71.244/hewenhao/GeekLearnMathWeapp into feature/2023-06-12-v1.1
parents d973bc39 91b790cb
...@@ -106,5 +106,17 @@ ...@@ -106,5 +106,17 @@
"w": 48, "w": 48,
"h": 48, "h": 48,
"ossName": "/pk-math/4ZHYpvj1KLEypcgoBmhjEsN2bvC4/48x48" "ossName": "/pk-math/4ZHYpvj1KLEypcgoBmhjEsN2bvC4/48x48"
},
"star-off.png": {
"u": "https://cdn.jkwljy.com/pk-math/4M6xW7oJhoEaafotmy3eY6xzBkw3/84x84",
"w": 84,
"h": 84,
"ossName": "/pk-math/4M6xW7oJhoEaafotmy3eY6xzBkw3/84x84"
},
"star-on.png": {
"u": "https://cdn.jkwljy.com/pk-math/3ETqmvyv7NrmaXkwoLSqPQ35kqUi/84x84",
"w": 84,
"h": 84,
"ossName": "/pk-math/3ETqmvyv7NrmaXkwoLSqPQ35kqUi/84x84"
} }
} }
...@@ -10,6 +10,14 @@ export const getQuestionList = (stageId: number, normal: boolean = true) => { ...@@ -10,6 +10,14 @@ export const getQuestionList = (stageId: number, normal: boolean = true) => {
})) }))
} }
export const getPkQuestionList = (stageId: number) => {
return requestAfterSilentLogin<QuestionType[], { stageId: number }>(() => ({
url: '/service-idea//pk/personal/stage/generateQuestion',
method: 'GET',
data: { stageId }
}))
}
export const resumeGame = (stageId: number) => { export const resumeGame = (stageId: number) => {
return requestAfterSilentLogin<null, { stageId: number, userId?: number }>(userInfo => ({ return requestAfterSilentLogin<null, { stageId: number, userId?: number }>(userInfo => ({
method: 'GET', method: 'GET',
......
...@@ -63,3 +63,42 @@ export function fetchUserRecords (data: PkParams) { ...@@ -63,3 +63,42 @@ export function fetchUserRecords (data: PkParams) {
} }
})) }))
} }
export type SubmitPkResultParams = {
initiator: number;
initiatorErrNum: number;
initiatorResultTime: number;
recipient: number;
recipientErrNum: number;
recipientResultTime: number;
}
export async function submitPkResult (params: SubmitPkResultParams) {
const result1 = await requestAfterSilentLogin<number, SubmitPkResultParams>(() => ({
url: '/service-idea/pk/personal/stage/complete',
method: 'POST',
data: params
}))
return await getPkResult(result1.data)
}
export type PkResult = SubmitPkResultParams & {
initiatorLevel: string;
initiatorName: string;
initiatorStar: number;
recipientLevel: string;
recipientName: string;
recipientStar: number;
result: string;
stageName: string;
}
export function getPkResult (params: number) {
return requestAfterSilentLogin<PkResult, { id: number }>(() => ({
url: '/service-idea/pk/personal/pkDetail',
method: 'GET',
data: { id: params }
}))
}
...@@ -90,5 +90,15 @@ export default { ...@@ -90,5 +90,15 @@ export default {
"u": "https://cdn.jkwljy.com/pk-math/4ZHYpvj1KLEypcgoBmhjEsN2bvC4/48x48", "u": "https://cdn.jkwljy.com/pk-math/4ZHYpvj1KLEypcgoBmhjEsN2bvC4/48x48",
"w": 48, "w": 48,
"h": 48 "h": 48
},
"star-off.png": {
"u": "https://cdn.jkwljy.com/pk-math/4M6xW7oJhoEaafotmy3eY6xzBkw3/84x84",
"w": 84,
"h": 84
},
"star-on.png": {
"u": "https://cdn.jkwljy.com/pk-math/3ETqmvyv7NrmaXkwoLSqPQ35kqUi/84x84",
"w": 84,
"h": 84
} }
} as const } as const
...@@ -5,3 +5,4 @@ export * from './use-request' ...@@ -5,3 +5,4 @@ export * from './use-request'
export * from './use-toggle' export * from './use-toggle'
export * from './use-focus' export * from './use-focus'
export * from './use-share' export * from './use-share'
export * from './use-fetch'
import {
useRef, useReducer, useCallback, Reducer,
} from 'react'
import { BizError } from '@/utils/request'
import { RequestResult } from '@/types'
import Taro from '@tarojs/taro'
export type RequestFn<T = unknown, P = unknown> = (arg: P, task?: (arg: Taro.RequestTask<RequestResult<T>>) => void) => Promise<RequestResult<T>>;
export type RequestParamsFn<P = unknown> = () => P;
export type FormatFn<T = unknown> = (arg: T, sysTime: number) => T;
export type RequestState<T> = {
detail: T | null;
isLoading: boolean;
isLoad: boolean;
error: string | null;
}
export type UseRequestRet<T, P> = [
RequestState<T>,
(arg?: (result: T | null, error?: BizError<T>) => void) => void,
(arg: Partial<T>) => void
]
enum ActionType {
Error = '1',
Load = '2',
Loading = '3'
}
function getInitState<T> (): RequestState<T> {
return {
detail: null,
error: null,
isLoad: false,
isLoading: false,
}
}
type Action<T> =
| {
type: ActionType.Error,
payload: RequestState<T>['error']
}
| {
type: ActionType.Loading
}
| {
type: ActionType.Load,
payload: Partial<RequestState<T>>
}
function reducer<T> (state: RequestState<T>, action: Action<T>): RequestState<T> {
switch (action.type) {
case ActionType.Loading: {
return { ...state, error: null, isLoading: true }
}
case ActionType.Error: {
return {
...state, error: action.payload, isLoad: true, isLoading: false,
}
}
case ActionType.Load: {
return {
...state, ...action.payload, error: null, isLoad: true, isLoading: false,
}
}
}
}
function defaultFormatFn<T = unknown> (data: T, sysTime: number) {
return data
}
export function useFetch<T = unknown, P = unknown> (
requestFn: RequestFn<T, P>,
paramsFn?: () => P,
formatFn?: FormatFn<T>,
): UseRequestRet<T, P> {
const requestTaskRef = useRef<Taro.RequestTask<RequestResult<T>> | null>(null)
const [dataSource, dispatch] = useReducer<Reducer<RequestState<T>, Action<T>>>(reducer, getInitState<T>())
const loadData = useCallback((callback: (result: T | null, error?: BizError<T>) => void) => {
if (requestTaskRef.current) {
requestTaskRef.current.abort()
requestTaskRef.current = null
}
dispatch({ type: ActionType.Loading })
let params: P = undefined as unknown as P
if (paramsFn) {
params = paramsFn()
}
return requestFn(params, (task) => {
requestTaskRef.current = task
})
.then(({ data: detail, sysTime }) => {
const formattedDetail = (formatFn ?? defaultFormatFn)(detail, sysTime)
dispatch({
type: ActionType.Load,
payload: { detail: formattedDetail },
})
if (typeof callback === 'function') {
callback(formattedDetail)
}
})
.catch((error: BizError<T>) => {
dispatch({ type: ActionType.Error, payload: error.message })
if (typeof callback === 'function') {
callback(null, error)
}
})
.finally(() => {
requestTaskRef.current = null
})
}, [requestFn, formatFn, paramsFn])
const updateData = useCallback((data: T) => {
dispatch({
type: ActionType.Load,
payload: { detail: data },
})
}, [])
return [dataSource, loadData, updateData]
}
...@@ -19,9 +19,11 @@ const randomPick = (arr: string[]) => { ...@@ -19,9 +19,11 @@ const randomPick = (arr: string[]) => {
const ModalName = ({ const ModalName = ({
isVisible, isVisible,
onClose, onClose,
onFinish,
}: { }: {
isVisible: boolean isVisible: boolean
onClose: () => void onClose: () => void;
onFinish: () => void;
}) => { }) => {
const [name, setName] = useState('小明') const [name, setName] = useState('小明')
const [generating, { setTrue, setFalse }] = useBoolean(false) const [generating, { setTrue, setFalse }] = useBoolean(false)
...@@ -89,6 +91,7 @@ const ModalName = ({ ...@@ -89,6 +91,7 @@ const ModalName = ({
size="large" size="large"
image={styles.footerButton} image={styles.footerButton}
hoverImage={styles.footerHoverButton} hoverImage={styles.footerHoverButton}
onClick={onFinish}
> >
确定 确定
</Button> </Button>
......
import { useDidShow, useRouter } from '@tarojs/taro' import { useDidShow, useRouter, navigateTo } from '@tarojs/taro'
import { View, Image, Text } from '@tarojs/components' import { View, Image, Text } from '@tarojs/components'
import { useBoolean } from '@/hooks' import { useBoolean } from '@/hooks'
import { useStoreState, useStoreActions } from '@/store/hooks' import { useStoreState, useStoreActions } from '@/store/hooks'
import assetsPk from '@/assets/oss/assets-pk' import assetsPk from '@/assets/oss/assets-pk'
import assetsMainNext from '@/assets/oss/assets-main-next' import assetsMainNext from '@/assets/oss/assets-main-next'
import { useRef } from 'react'
import { badgeImages } from '../battles/const' import { badgeImages } from '../battles/const'
import styles from './index.module.scss' import styles from './index.module.scss'
import TopHeader from './components/top-header' import TopHeader from './components/top-header'
...@@ -14,6 +15,10 @@ const AcceptPk = () => { ...@@ -14,6 +15,10 @@ const AcceptPk = () => {
const router = useRouter<{ initiator?: string; stageId?: string }>() const router = useRouter<{ initiator?: string; stageId?: string }>()
const details = useStoreState((state) => state.battlesModel.details) const details = useStoreState((state) => state.battlesModel.details)
const userInfo = useStoreState((state) => state.userModel.userInfo)
const getQuestionList = useStoreActions(actions => actions.gameModel.getQuestionList)
const getStageDetail = useStoreActions(actions => actions.gameModel.getStageDetail)
const fetchUserDetails = useStoreActions( const fetchUserDetails = useStoreActions(
(actions) => actions.battlesModel.fetchUserDetails (actions) => actions.battlesModel.fetchUserDetails
) )
...@@ -27,6 +32,32 @@ const AcceptPk = () => { ...@@ -27,6 +32,32 @@ const AcceptPk = () => {
} }
}) })
const isClickRef = useRef(false)
const toGame = () => {
if (isClickRef.current) return
isClickRef.current = true
const stageId = +(router.params.stageId ?? -1)
Promise.all([
getQuestionList({ stageId, isBattle: true }),
getStageDetail(stageId)
])
.then(() => {
isClickRef.current = false
navigateTo({
url: `/pages/game/play/index?id=${stageId}&isBattle=true`
})
})
}
const handleClick = () => {
if (!userInfo.nickName) {
setTrue()
} else {
toGame()
}
}
return ( return (
<View className={styles.container}> <View className={styles.container}>
<TopHeader /> <TopHeader />
...@@ -94,13 +125,13 @@ const AcceptPk = () => { ...@@ -94,13 +125,13 @@ const AcceptPk = () => {
<View className={styles.bottom}> <View className={styles.bottom}>
<Image <Image
className={styles.clickImage} className={styles.clickImage}
onClick={setTrue} onClick={handleClick}
src={assetsPk['accept-click.png'].u} src={assetsPk['accept-click.png'].u}
/> />
</View> </View>
</View> </View>
<ModalName isVisible={isVisible} onClose={setFalse} /> <ModalName isVisible={isVisible} onClose={setFalse} onFinish={toGame} />
</View> </View>
) )
} }
......
...@@ -32,10 +32,7 @@ const battlesModel: BattlesModel = { ...@@ -32,10 +32,7 @@ const battlesModel: BattlesModel = {
fetchUserDetails: thunk(async (actions, payload) => { fetchUserDetails: thunk(async (actions, payload) => {
try { try {
const res = await fetchUserDetails(payload) const res = await fetchUserDetails(payload)
if (res.code === 200) { actions.setUserDetails(res.data)
console.log('res', res)
actions.setUserDetails(res.data)
}
} catch (err) { } catch (err) {
} }
}), }),
...@@ -43,10 +40,7 @@ const battlesModel: BattlesModel = { ...@@ -43,10 +40,7 @@ const battlesModel: BattlesModel = {
fetchUserRecords: thunk(async (actions, payload) => { fetchUserRecords: thunk(async (actions, payload) => {
try { try {
const res = await fetchUserRecords(payload) const res = await fetchUserRecords(payload)
if (res.code === 200) { actions.setUserRecords(res.data.records)
console.log('res', res)
actions.setUserRecords(res.data.records)
}
} catch (err) { } catch (err) {
} }
}), }),
......
...@@ -16,6 +16,52 @@ ...@@ -16,6 +16,52 @@
} }
} }
.top_level {
position: relative;
}
.star_1 {
position: absolute;
left: 230px;
top: 60px;
z-index: 30;
width: 84px;
height: 84px;
animation: zoomIn .5s ease-in-out 0s backwards;
}
.star_2 {
position: absolute;
left: 334px;
top: 40px;
z-index: 30;
width: 84px;
height: 84px;
animation: zoomIn .5s ease-in-out 0.3s backwards;
}
.star_3 {
position: absolute;
right: 228px;
top: 60px;
z-index: 30;
width: 84px;
height: 84px;
animation: zoomIn .5s ease-in-out 0.6s backwards;
}
@keyframes zoomIn {
0% {
transform: scale3d(2, 2, 1);
opacity: 0;
}
100% {
transform: scale3d(1, 1, 1);
opacity: 1;
}
}
.bg { .bg {
width: 600px; width: 600px;
display: block; display: block;
......
...@@ -8,6 +8,7 @@ import { StageLevel } from '@/api' ...@@ -8,6 +8,7 @@ import { StageLevel } from '@/api'
import { useStoreState, useStoreActions } from '@/store/hooks' import { useStoreState, useStoreActions } from '@/store/hooks'
import { palyAudio } from '@/utils/play-audio' import { palyAudio } from '@/utils/play-audio'
import audio from '@/assets/oss/assets-audio' import audio from '@/assets/oss/assets-audio'
import assetsGame from '@/assets/oss/assets-game'
import tutorialAssets from '@/assets/oss/assets-tutorial' import tutorialAssets from '@/assets/oss/assets-tutorial'
import { UserGuideView } from '@/components' import { UserGuideView } from '@/components'
...@@ -29,21 +30,28 @@ const getLevelBigBg = (s?: StageLevel | null): string => { ...@@ -29,21 +30,28 @@ const getLevelBigBg = (s?: StageLevel | null): string => {
return assets['level-big-fail.png'].u return assets['level-big-fail.png'].u
} }
// const getWeight = (s?: StageLevel | null) => { const getStarNum = (s?: StageLevel | null): number => {
// switch (s) { switch (s) {
// case StageLevel.S: { case StageLevel.S: {
// return 100 return 3
// } }
// case StageLevel.A: { case StageLevel.A: {
// return 50 return 2
// } }
// case StageLevel.B: { case StageLevel.B: {
// return 25 return 1
// } }
// } }
// return 0 return 0
// } }
const getStarImg = (s1: number, s2: number): string => {
if (s2 >= s1) {
return assetsGame['star-on.png'].u
}
return assetsGame['star-off.png'].u
}
const getAudioSrc = (s?: StageLevel | null) => { const getAudioSrc = (s?: StageLevel | null) => {
if (!s) { if (!s) {
...@@ -191,13 +199,20 @@ const GameCompleteHead = () => { ...@@ -191,13 +199,20 @@ const GameCompleteHead = () => {
} }
}, [isErrQuestionGuideComplete, gameResult]) }, [isErrQuestionGuideComplete, gameResult])
const starNum = useMemo(() => getStarNum(gameResult?.level), [gameResult])
if (!gameResult) { if (!gameResult) {
return null return null
} }
return ( return (
<View style={style} className={classNames(styles.head, linearGradient)}> <View style={style} className={classNames(styles.head, linearGradient)}>
<Image src={bg} className={styles.bg}></Image> <View className={styles.top_level}>
<Image src={bg} className={styles.bg}></Image>
<Image src={getStarImg(1, starNum)} className={styles.star_1}></Image>
<Image src={getStarImg(2, starNum)} className={styles.star_2}></Image>
<Image src={getStarImg(3, starNum)} className={styles.star_3}></Image>
</View>
<View style={{ color: text.color }} className={styles.tips}>{text.text}</View> <View style={{ color: text.color }} className={styles.tips}>{text.text}</View>
<View className={styles.item_wrap}> <View className={styles.item_wrap}>
<View className={styles.item}> <View className={styles.item}>
......
...@@ -3,16 +3,17 @@ import assetsGame from '@/assets/oss/assets-game' ...@@ -3,16 +3,17 @@ import assetsGame from '@/assets/oss/assets-game'
import assetsPrepare from '@/assets/oss/assets-prepare' import assetsPrepare from '@/assets/oss/assets-prepare'
import assetsPk from '@/assets/oss/assets-pk' import assetsPk from '@/assets/oss/assets-pk'
import classNames from 'classnames' import classNames from 'classnames'
import { useStoreState } from '@/store/hooks'
import styles from './battle-complete.module.scss' import styles from './battle-complete.module.scss'
type BattleCompleteProps = { type BattleCompleteProps = {
data?: {}
} }
const BattleComplete = (props: BattleCompleteProps) => { const BattleComplete = (props: BattleCompleteProps) => {
const { data } = props const pkResult = useStoreState(states => states.gameModel.pkResult)
if (!data) {
if (!pkResult) {
return null return null
} }
......
...@@ -23,6 +23,8 @@ const CountUp = (props: CountUpProps) => { ...@@ -23,6 +23,8 @@ const CountUp = (props: CountUpProps) => {
const questionList = useStoreState(state => state.gameModel.questionList) const questionList = useStoreState(state => state.gameModel.questionList)
const isSubmit = useStoreState(state => state.gameModel.isSubmit) const isSubmit = useStoreState(state => state.gameModel.isSubmit)
const submit = useStoreActions(actions => actions.gameModel.submit) const submit = useStoreActions(actions => actions.gameModel.submit)
const pkDetail = useStoreState(state => state.battlesModel.details)
const [isExceed, exceedActions] = useBoolean(false) const [isExceed, exceedActions] = useBoolean(false)
const [isStarted, startActions] = useBoolean(false) const [isStarted, startActions] = useBoolean(false)
...@@ -48,17 +50,25 @@ const CountUp = (props: CountUpProps) => { ...@@ -48,17 +50,25 @@ const CountUp = (props: CountUpProps) => {
}) })
const roleStyle = useMemo(() => { const roleStyle = useMemo(() => {
const getTime = () => {
if (isBattle) {
return pkDetail?.resultTime ?? stageDetail.bTime
}
return stageDetail.bTime
}
if (isStarted) { if (isStarted) {
return { return {
transform: 'translateX(100%)', transform: 'translateX(100%)',
transition: `transform ${stageDetail.bTime}s linear`, transition: `transform ${getTime()}s linear`,
} }
} }
return { return {
transform: 'translateX(0)', transform: 'translateX(0)',
transition: `transform ${stageDetail.bTime}s linear`, transition: `transform ${getTime()}s linear`,
} }
}, [stageDetail, isStarted]) }, [stageDetail, isStarted, isBattle, pkDetail])
const processInnerStyle = useMemo(() => { const processInnerStyle = useMemo(() => {
if (isSubmit) { if (isSubmit) {
......
import { action, Action, computed, Computed, Thunk, thunk } from 'easy-peasy' import { action, computed, thunk } from 'easy-peasy'
import { AppStoreModel } from '@/store/store-model' import {
import { getQuestionList, StageLevel, type StageDetail, getStageDetail, completeStage, StageType, type CompleteStageOut, resumeGame } from '@/api' getQuestionList, StageLevel,
import { showLoading, hideLoading, showModal, redirectTo, vibrateShort, getCurrentInstance, disableAlertBeforeUnload } from '@tarojs/taro' getStageDetail, completeStage, StageType,
resumeGame, getPkQuestionList, submitPkResult
} from '@/api'
import {
showLoading, hideLoading, showModal, redirectTo,
vibrateShort, getCurrentInstance, disableAlertBeforeUnload
} from '@tarojs/taro'
import assets from '@/assets/oss/assets-complete' import assets from '@/assets/oss/assets-complete'
import { palyAudio } from '@/utils/play-audio' import { palyAudio } from '@/utils/play-audio'
import audio from '@/assets/oss/assets-audio' import audio from '@/assets/oss/assets-audio'
import { import {
QuestionType,
QuestionAnswer,
isSelectionQuestion, isSelectionQuestion,
// QuestionOption, // QuestionOption,
} from '../types' } from '../types'
import { buildCompleteStageParam, convertQuestion, determinQuestion } from './utils' import { buildCompleteStageParam, convertQuestion, determinQuestion, buildSubmitPkParams } from './utils'
interface CompleteStageDetail extends CompleteStageOut { import { GameModel } from './types'
errNum: number;
levelTime: number;
isTimeout: boolean;
}
const COUNTER_ID = 'z__countdown__' const COUNTER_ID = 'z__countdown__'
...@@ -34,65 +34,11 @@ const getCounter = () => { ...@@ -34,65 +34,11 @@ const getCounter = () => {
const stopCounter = () => getCounter()?.stop() const stopCounter = () => getCounter()?.stop()
const startCounter = () => getCounter()?.start() const startCounter = () => getCounter()?.start()
interface GameModelState {
/** 题目列表 */
questionList: QuestionType[];
/** 错题列表 */
errList: QuestionType[];
stageDetailPre: StageDetail | null;
stageDetail: StageDetail | null;
gameResult: CompleteStageDetail | null;
gameStartTime: number;
/** 当前题目下标 */
currentQuestionIndex: number;
/** 当前输入框下标 */
currentInputIndex: number;
isSubmit: boolean;
modalContinueVisible: boolean;
/** 是否复活过 */
bornTimes: number;
/** 计时器id */
counterId: string;
rightIcon: string | null;
}
export interface GameModel extends GameModelState {
updateState: Action<GameModel, Partial<GameModelState>>;
/** 当前题目 */
currentQuestion: Computed<GameModel, QuestionType | undefined>;
/** 题目答案和用户答案 */
questionAnswers: Computed<GameModel, QuestionAnswer[] | undefined>;
/** 更新当前题目下标 */
updateCurrentIndex: Action<GameModel, number>;
/** 更新当前输入框下标 */
updateCurrentInputIndex: Action<GameModel, number>;
/** 更新用户输入 */
updateUserAnswer: Action<GameModel, { detail: string }>;
/** 清空所有输入 */
clearUserAnswer: Action<GameModel, void>;
updateSelectionAnswer: Action<GameModel, number>;
/** 可以跳转下一题 */
canGoNext: Computed<GameModel, boolean>;
updateList: Action<GameModel, QuestionType[]>;
getQuestionList: Thunk<GameModel, number, void, AppStoreModel>;
getStageDetail: Thunk<GameModel, number, void, AppStoreModel>;
handleGoNext: Thunk<GameModel, void, void, AppStoreModel>;
submit: Thunk<GameModel, void, void, AppStoreModel>;
reborn: Thunk<GameModel, void, void, AppStoreModel>;
}
const gameModel: GameModel = { const gameModel: GameModel = {
counterId: COUNTER_ID, counterId: COUNTER_ID,
questionList: [], questionList: [],
errList: [], errList: [],
isBattle: false,
gameResult: { gameResult: {
/** 排名档位 */ /** 排名档位 */
gear: 10, gear: 10,
...@@ -112,6 +58,7 @@ const gameModel: GameModel = { ...@@ -112,6 +58,7 @@ const gameModel: GameModel = {
/** 是否升档奖励 */ /** 是否升档奖励 */
upGear: true upGear: true
}, },
bornTimes: 3, bornTimes: 3,
modalContinueVisible: false, modalContinueVisible: false,
gameStartTime: 0, gameStartTime: 0,
...@@ -120,6 +67,7 @@ const gameModel: GameModel = { ...@@ -120,6 +67,7 @@ const gameModel: GameModel = {
stageDetail: null, stageDetail: null,
stageDetailPre: null, stageDetailPre: null,
pkResult: null,
updateState: action((state, obj) => { updateState: action((state, obj) => {
for (const key in obj) { for (const key in obj) {
...@@ -283,19 +231,28 @@ const gameModel: GameModel = { ...@@ -283,19 +231,28 @@ const gameModel: GameModel = {
} }
}), }),
getQuestionList: thunk(async (actions, round, helpers) => { getQuestionList: thunk(async (actions, { isBattle = false, stageId }, helpers) => {
try { try {
// showLoading() // showLoading()
const stageList = helpers.getStoreState().mainModel.stageList let questionList
const isFirstStage = stageList.findIndex(c => String(c.id) === String(round)) === 0 if (!isBattle) {
const stageDetail = helpers.getState().stageDetail const stageList = helpers.getStoreState().mainModel.stageList
const isNormal = !isFirstStage || !!stageDetail?.level const isFirstStage = stageList.findIndex(c => String(c.id) === String(stageId)) === 0
const { data: questionList } = await getQuestionList(round, isNormal) const stageDetail = helpers.getState().stageDetail
const isNormal = !isFirstStage || !!stageDetail?.level
const { data: list } = await getQuestionList(stageId, isNormal)
questionList = list
} else {
const { data: list } = await getPkQuestionList(stageId)
questionList = list
}
actions.updateState({ actions.updateState({
questionList: questionList.map(convertQuestion), questionList: questionList.map(convertQuestion),
currentInputIndex: 0, currentInputIndex: 0,
currentQuestionIndex: 0, currentQuestionIndex: 0,
errList: [], errList: [],
isBattle,
pkResult: null,
modalContinueVisible: false, modalContinueVisible: false,
bornTimes: 3, bornTimes: 3,
gameStartTime: Date.now(), gameStartTime: Date.now(),
...@@ -327,22 +284,36 @@ const gameModel: GameModel = { ...@@ -327,22 +284,36 @@ const gameModel: GameModel = {
disableAlertBeforeUnload() disableAlertBeforeUnload()
actions.updateState({ isSubmit: true }) actions.updateState({ isSubmit: true })
stopCounter() stopCounter()
const { questionList, stageDetail } = helpers.getState() const { questionList, stageDetail, isBattle } = helpers.getState()
const { errList, errNum, ...rest } = buildCompleteStageParam(questionList, stageDetail!, getCounter()?.getCount() ?? 0) const out = buildCompleteStageParam(questionList, stageDetail!, getCounter()?.getCount() ?? 0)
const { data: gameResult } = await completeStage(rest) const { errList, errNum, ...rest } = out
actions.updateState({ if (!isBattle) {
errList, const { data: gameResult } = await completeStage(rest)
gameResult: { actions.updateState({
...gameResult, errList,
isTimeout: rest.isTimeout, gameResult: {
errNum, ...gameResult,
levelTime: rest.levelTime isTimeout: rest.isTimeout,
errNum,
levelTime: rest.levelTime
}
})
hideLoading()
redirectTo({
url: '/pages/game/complete/index',
})
} else {
const pkDetails = helpers.getStoreState().battlesModel.details
const userInfo = helpers.getStoreState().userModel.userInfo
if (!pkDetails) {
throw new Error('提交出错')
} }
}) const result = await submitPkResult(buildSubmitPkParams(pkDetails, out, userInfo))
hideLoading()
redirectTo({ actions.updateState({
url: '/pages/game/complete/index', pkResult: result.data,
}) })
}
} catch (err) { } catch (err) {
hideLoading() hideLoading()
showModal({ showModal({
......
import { Action, Computed, Thunk } from 'easy-peasy'
import { AppStoreModel } from '@/store/store-model'
import {
type StageDetail,
type CompleteStageOut
} from '@/api'
import {
QuestionType,
QuestionAnswer,
// QuestionOption,
} from '../types'
export interface CompleteStageDetail extends CompleteStageOut {
errNum: number;
levelTime: number;
isTimeout: boolean;
}
export interface GameModelState {
/** 题目列表 */
questionList: QuestionType[];
/** 错题列表 */
errList: QuestionType[];
stageDetailPre: StageDetail | null;
stageDetail: StageDetail | null;
gameResult: CompleteStageDetail | null;
gameStartTime: number;
/** 当前题目下标 */
currentQuestionIndex: number;
/** 当前输入框下标 */
currentInputIndex: number;
isSubmit: boolean;
modalContinueVisible: boolean;
/** 是否复活过 */
bornTimes: number;
/** 计时器id */
counterId: string;
rightIcon: string | null;
isBattle: boolean;
}
export interface GameModel extends GameModelState {
updateState: Action<GameModel, Partial<GameModelState>>;
/** 当前题目 */
currentQuestion: Computed<GameModel, QuestionType | undefined>;
/** 题目答案和用户答案 */
questionAnswers: Computed<GameModel, QuestionAnswer[] | undefined>;
/** 更新当前题目下标 */
updateCurrentIndex: Action<GameModel, number>;
/** 更新当前输入框下标 */
updateCurrentInputIndex: Action<GameModel, number>;
/** 更新用户输入 */
updateUserAnswer: Action<GameModel, { detail: string }>;
/** 清空所有输入 */
clearUserAnswer: Action<GameModel, void>;
updateSelectionAnswer: Action<GameModel, number>;
/** 可以跳转下一题 */
canGoNext: Computed<GameModel, boolean>;
updateList: Action<GameModel, QuestionType[]>;
getQuestionList: Thunk<GameModel, { stageId: number; isBattle?: boolean }, void, AppStoreModel>;
getStageDetail: Thunk<GameModel, number, void, AppStoreModel>;
handleGoNext: Thunk<GameModel, void, void, AppStoreModel>;
submit: Thunk<GameModel, void, void, AppStoreModel>;
reborn: Thunk<GameModel, void, void, AppStoreModel>;
}
import { type CompleteStageParam, type StageDetail, StageLevel, type CompleteQuestion } from '@/api' import { type CompleteStageParam, type StageDetail, StageLevel, type CompleteQuestion, SubmitPkResultParams, PkDetails } from '@/api'
import { getLogManager } from '@tarojs/taro' import { getLogManager } from '@tarojs/taro'
import { getStorage, StorageKeys } from '@/utils/storage' import { getStorage, StorageKeys } from '@/utils/storage'
import { UserInfo } from '@/types'
import { type QuestionType, isBlankQuestion, isVerticalDivisionQuestion, isSelectionQuestion } from '../types' import { type QuestionType, isBlankQuestion, isVerticalDivisionQuestion, isSelectionQuestion } from '../types'
const logger = getLogManager({ level: 1 }) const logger = getLogManager({ level: 1 })
...@@ -155,3 +156,15 @@ export function determinQuestion (question: QuestionType) { ...@@ -155,3 +156,15 @@ export function determinQuestion (question: QuestionType) {
throw new Error('question type not supported') throw new Error('question type not supported')
} }
export function buildSubmitPkParams (pkDetail: PkDetails, out: BuildParamsOut, userInfo: UserInfo): SubmitPkResultParams {
return {
initiator: pkDetail.userId,
initiatorErrNum: 0,
initiatorResultTime: pkDetail.resultTime,
recipient: userInfo.userId!,
recipientErrNum: out.errNum,
recipientResultTime: out.resultTime,
}
}
import { View, Text, Image } from '@tarojs/components' import { View, Image } from '@tarojs/components'
import assetsMainNext from '@/assets/oss/assets-main-next' import assetsMainNext from '@/assets/oss/assets-main-next'
import { getMenuButtonBoundingClientRect, getSystemInfoSync, navigateTo } from '@tarojs/taro' import { getMenuButtonBoundingClientRect, getSystemInfoSync, navigateTo } from '@tarojs/taro'
import { useMemo } from 'react' import { useMemo } from 'react'
......
import { View, Image, Button } from '@tarojs/components' import { View, Image, Button } from '@tarojs/components'
import assetsPk from '@/assets/oss/assets-pk' import assetsPk from '@/assets/oss/assets-pk'
import { useMemo } from 'react' import { useMemo, useCallback, useEffect } from 'react'
import { getMenuButtonBoundingClientRect, navigateTo } from '@tarojs/taro' import { getMenuButtonBoundingClientRect, navigateTo } from '@tarojs/taro'
import classNames from 'classnames' import classNames from 'classnames'
import assetsMainNext from '@/assets/oss/assets-main-next' import assetsMainNext from '@/assets/oss/assets-main-next'
import { cs } from '@/styles' import { cs } from '@/styles'
import { useStoreActions, useStoreState } from '@/store/hooks' import { useStoreActions, useStoreState } from '@/store/hooks'
import { useFetch } from '@/hooks'
import { fetchUserDetails } from '@/api'
import styles from './create-pk.module.scss' import styles from './create-pk.module.scss'
type CreatePkProps = { type CreatePkProps = {
...@@ -23,6 +25,22 @@ const CreatePk = (props: CreatePkProps) => { ...@@ -23,6 +25,22 @@ const CreatePk = (props: CreatePkProps) => {
updateState({ isCreatePkShow: false, currentPkStage: null }) updateState({ isCreatePkShow: false, currentPkStage: null })
} }
const [dataSource, loadData] = useFetch(fetchUserDetails, useCallback(() => {
if (!currentPkStage) return null
return {
userId: userInfo.userId,
stageId: currentPkStage.id
}
}, [currentPkStage, userInfo]))
useEffect(() => {
if (currentPkStage && userInfo?.userId) {
loadData()
}
}, [currentPkStage, userInfo, loadData])
const detail = dataSource.detail
const closeStyle = useMemo(() => { const closeStyle = useMemo(() => {
return { return {
paddingTop: `${nav.top + 5}px` paddingTop: `${nav.top + 5}px`
...@@ -54,7 +72,7 @@ const CreatePk = (props: CreatePkProps) => { ...@@ -54,7 +72,7 @@ const CreatePk = (props: CreatePkProps) => {
<View>{userInfo.nickName}</View> <View>{userInfo.nickName}</View>
<View className={styles.info_detail}><Image src={assetsPk['bronze-small.png'].u} className={styles.pk_level} />青铜Ⅰ</View> <View className={styles.info_detail}><Image src={assetsPk['bronze-small.png'].u} className={styles.pk_level} />青铜Ⅰ</View>
<View className={styles.info_detail}>本关战绩:胜 {currentPkStage?.pkWinNum ?? 0} 负 {currentPkStage?.pkLoseNum ?? 0}</View> <View className={styles.info_detail}>本关战绩:胜 {currentPkStage?.pkWinNum ?? 0} 负 {currentPkStage?.pkLoseNum ?? 0}</View>
<View className={styles.info_detail}>最佳表现:全对丨29.3s</View> <View className={styles.info_detail}>最佳表现:全对丨{detail?.resultTime ?? '-'}s</View>
</View> </View>
</View> </View>
</View> </View>
......
...@@ -96,7 +96,7 @@ const Prepare = () => { ...@@ -96,7 +96,7 @@ const Prepare = () => {
throttleDelay: 1000, throttleDelay: 1000,
onSuccess: () => { onSuccess: () => {
palyAudio(audio['蹦蹦top出现首页.wav'].u) palyAudio(audio['蹦蹦top出现首页.wav'].u)
getQuestionList(+router.params.id || 1).then(() => { getQuestionList({ stageId: +router.params.id || 1 }).then(() => {
setFalse() setFalse()
navigateTo({ navigateTo({
url: `/pages/game/play/index?id=${router.params.id}` url: `/pages/game/play/index?id=${router.params.id}`
...@@ -128,10 +128,10 @@ const Prepare = () => { ...@@ -128,10 +128,10 @@ const Prepare = () => {
isClickRef.current = true isClickRef.current = true
palyAudio(audio['蹦蹦top出现首页.wav'].u) palyAudio(audio['蹦蹦top出现首页.wav'].u)
getQuestionList(+router.params.id || 1).then(() => { getQuestionList({ stageId: +router.params.id || 1 }).then(() => {
isClickRef.current = false isClickRef.current = false
navigateTo({ navigateTo({
url: `/pages/game/play/index?id=${router.params.id}&isBattle=true` url: `/pages/game/play/index?id=${router.params.id}`
}) })
}) })
} }
......
...@@ -16,4 +16,16 @@ function omit<T extends object, K extends (keyof T)[] = []>(value: T, keys: K): ...@@ -16,4 +16,16 @@ function omit<T extends object, K extends (keyof T)[] = []>(value: T, keys: K):
return ret return ret
} }
export function singular<T extends (...arg: any[]) => any>(fn: T) {
let isRunning = false
return async function (...arg: Parameters<T>) {
if (isRunning) return
try {
return await fn(...arg)
} finally {
isRunning = false
}
}
}
export { omit } export { omit }
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