Commit d20e5b10 authored by m's avatar m
parents fb7f17e8 8a77f86a
......@@ -13,10 +13,12 @@ declare module '*.styl';
type CountUptime = React.FC<{ maxNum }>
type CountUpTime = React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & { 'max-value'?: number, onTimeup?: () => void }, HTMLElement>
declare namespace JSX{
interface IntrinsicElements{
interface IntrinsicElements {
// 扩展 IntrinsicElements 否则无法识别自定义标签
'count-up-time': React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement> & { 'max-value'?: number, onTimeup?: () => void }, HTMLElement>
'count-up-time': CountUpTime
}
}
......
import { request } from '@/utils/request'
import { request, requestAfterSilentLogin } from '@/utils/request'
import { getStorage, StorageKeys } from '@/utils/storage'
import qs from 'qs'
type LoginResult = {
......@@ -12,17 +13,17 @@ type LoginResult = {
/** 登录token */
token: string;
/** 用户ID */
id: number;
userId: number;
/** */
unionId: string;
}
/** 静默登录 */
export function silentLoginApi (code: string, recommendId:string) {
return request<LoginResult, { code: string, recommendId:string, }>({
method: 'POST',
url: '/service-activity-pbl/user/login',
data: { code, recommendId }
export function silentLoginApi (code: string) {
return request<LoginResult, { code: string}>({
method: 'GET',
url: '/service-idea/stage/user/userLogin',
data: { code }
})
}
......
import { requestAfterSilentLogin } from '@/utils/request'
import { getStorage, StorageKeys } from '@/utils/storage'
import { QuestionItem, type QuestionType } from '@/pages/game/play/types'
export const getQuestionList = (stageId: number) => {
return requestAfterSilentLogin<QuestionType[], { stageId: number, userId?: number }>({
url: '/service-idea/stage/startStage',
method: 'GET',
data: { stageId, userId: getStorage(StorageKeys.userInfo)?.userId }
})
}
export const enum StageStatus {
CURRENT = 'CURRENT',
DISABLED = 'DISABLED',
PASSED = 'PASSED',
}
export const enum StageType {
Strong = '强化',
Enhance = '应用',
OneStop = '一站到底',
}
export const enum StageLevel {
S = 'S',
A = 'A',
B = 'B'
}
export interface Stage {
content: string;
gear: number;
id: number;
label: string;
level: StageLevel;
name: string;
stageLabel: string;
status?: StageStatus;
type?: StageType;
upGear: boolean;
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 () {
return requestAfterSilentLogin<Stage[], { chapter: number; userId?: number }>({
method: 'GET',
url: '/service-idea/stage/listStages',
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
}
})
}
export * from './auth'
export * from './game'
......@@ -2,6 +2,7 @@ import { Component, PropsWithChildren } from 'react'
import { StoreProvider } from 'easy-peasy'
import { getUpdateManager, showModal } from '@tarojs/taro'
import { configSkynet } from '@/utils/skynet'
import { silentLogin } from '@/utils/silent-login'
import store from './store'
......@@ -44,6 +45,8 @@ class App extends Component<PropsWithChildren> {
showCancel: false
})
}
silentLogin()
}
componentDidHide () {}
......
import { baseUrl } from './server'
const _baseUrl = process.env.SERVER_ENDPOINT === 'https://geek.jkwljy.com' ? baseUrl : 'http://172.10.62.134'
const _baseUrl = process.env.SERVER_ENDPOINT === 'https://geek.jkwljy.com' ? baseUrl : 'http://172.10.61.134'
export const SkynetConfig = {
appId: 'learn-math',
......
......@@ -37,6 +37,7 @@ Component({
attached () {
this._tick = 0
this.startCount()
console.log(this)
},
methods: {
......
import { View, Image } from '@tarojs/components'
import { useState, useEffect, useCallback, useMemo } from 'react'
import { createSelectorQuery } from '@tarojs/taro'
import { useState, useEffect, useCallback, useMemo, useRef } from 'react'
import { createSelectorQuery, getCurrentInstance } from '@tarojs/taro'
import { useStoreState } from '@/store/hooks'
import { type StageDetail } from '@/api'
import styles from './count-up.module.scss'
const speed = 4
const id = '_process__'
const CountUp = () => {
type CountUpProps = {
stageDetail: StageDetail
}
const CountUp = (props: CountUpProps) => {
const { stageDetail } = props
const currentQuestionIndex = useStoreState(states => states.gameModel.currentQuestionIndex)
const questionList = useStoreState(state => state.gameModel.questionList)
const isSubmit = useStoreState(state => state.gameModel.isSubmit)
const [width, setWidth] = useState(0)
const countUp = useRef<any>(null)
const questionLength = useMemo(() => {
return questionList.length
}, [questionList])
useEffect(() => {
const query = createSelectorQuery()
query.select(`#${id}`)
createSelectorQuery().select(`#${id}`)
.boundingClientRect()
.exec((res) => {
console.log(res)
......@@ -32,15 +38,29 @@ const CountUp = () => {
const roleStyle = useMemo(() => {
return {
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(() => {
if (isSubmit) {
return {
width: '100%'
}
}
return {
width: `${currentQuestionIndex * 100 / questionLength}%`
}
}, [currentQuestionIndex, questionLength])
}, [currentQuestionIndex, questionLength, isSubmit])
const handleTimeUp = useCallback(() => {
console.log('upd1')
......@@ -58,7 +78,7 @@ const CountUp = () => {
</View>
<View className={styles.time}>
<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>
)
......
import { View, Image, Text } from '@tarojs/components'
import { getMenuButtonBoundingClientRect } from '@tarojs/taro'
import { getMenuButtonBoundingClientRect, navigateBack } from '@tarojs/taro'
import { useState, memo } from 'react'
import { useStoreState } from '@/store/hooks'
......@@ -9,7 +9,6 @@ const PageHead = () => {
const [nav] = useState(getMenuButtonBoundingClientRect())
const questionList = useStoreState(states => states.gameModel.questionList)
const currentQuestionIndex = useStoreState(states => states.gameModel.currentQuestionIndex)
console.log('rr')
return (
<View className={styles.header}>
......@@ -20,8 +19,11 @@ const PageHead = () => {
}}
>
<View className={styles.inner} style={{ height: `${nav.height + 10}px` }}>
<Image src={require('../assets/arrow.png')} className={styles.arrow}></Image>
<Text>{currentQuestionIndex + 1}/{questionList.length}</Text>
<Image src={require('../assets/arrow.png')} className={styles.arrow} onClick={() => navigateBack()}></Image>
{questionList.length > 0
? (<Text>{currentQuestionIndex + 1}/{questionList.length}</Text>)
: (<Text>出错了</Text>)
}
</View>
</View>
</View>
......
......@@ -14,6 +14,13 @@
display: flex;
line-height: 112px;
align-items: center;
justify-content: center;
flex-direction: column;
.top {
flex: 2;
}
.bottom {
flex: 4;
}
}
}
......@@ -21,9 +21,11 @@ const QuestionBlank = (props: QuestionBlankProps) => {
return (
<View className={classNames(styles.content, question.simpleType && styles.is_sample)}>
<View className={styles.top}></View>
<View>
{tree.map(item => renderRichText(item))}
</View>
<View className={styles.bottom}></View>
</View>
)
}
......
......@@ -7,7 +7,11 @@
}
.gap {
flex: 1;
flex: 2;
}
.gap_2 {
flex: 3;
}
.top {
......
......@@ -43,7 +43,7 @@ const QuestionVerticalDivision = (props: QuestionSelectionProps) => {
<View className={styles.footer}>
<AnswerBlank index={3}></AnswerBlank>
</View>
<View className={styles.gap}></View>
<View className={styles.gap_2}></View>
</View>
)
}
......
import { View, ScrollView } from '@tarojs/components'
import { useStoreState } from '@/store/hooks'
import { useStoreState, useStoreActions } from '@/store/hooks'
import { useEffect } from 'react'
import { useRouter } from '@tarojs/taro'
import PageHead from './components/page-head'
import PageFooter from './components/page-footer'
......@@ -11,20 +13,36 @@ import styles from './index.module.scss'
const GamePlay = () => {
const currentQuestion = useStoreState(states => states.gameModel.currentQuestion)
const getQuestionList = useStoreActions(actions => actions.gameModel.getQuestionList)
const stageDetail = useStoreState(state => state.gameModel.stageDetail)
const router = useRouter<{ id: string }>()
useEffect(() => {
getQuestionList(+router.params.id)
}, [router, getQuestionList])
return (
<View className={styles.viewport}>
<PageHead />
<CountUp />
{currentQuestion && stageDetail && (
<>
<CountUp stageDetail={stageDetail} />
</>
)}
<ScrollView className={styles.body} scrollY>
{currentQuestion && (
<Question question={currentQuestion} />
)}
</ScrollView>
{currentQuestion?.questionType !== '选择题' && (
<NumberKeyboard />
{currentQuestion && (
<>
{currentQuestion?.questionType !== '选择题' && (
<NumberKeyboard />
)}
<PageFooter />
</>
)}
<PageFooter />
</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 { getQuestionList, type StageDetail, getStageDetail, completeStage } from '@/api'
import { showLoading, hideLoading, showModal } from '@tarojs/taro'
import {
QuestionType,
QuestionAnswer,
isSelectionQuestion,
QuestionOption,
// QuestionOption,
} from '../types'
import { buildCompleteStageParam } from './utils'
import questionListJson from './test.json'
// import questionListJson from './test.json'
export interface GameModel {
/** 题目列表 */
questionList: QuestionType[];
stageDetail: StageDetail | null;
gameStartTime: number;
updateState: Action<GameModel, Partial<State<GameModel>>>;
/** 当前题目 */
currentQuestion: Computed<GameModel, QuestionType | undefined>;
/** 当前题目下标 */
......@@ -38,12 +44,27 @@ export interface GameModel {
getQuestionList: Thunk<GameModel, number, void, AppStoreModel>;
handleGoNext: Thunk<GameModel, void, void, AppStoreModel>;
isSubmit: boolean;
submit: Thunk<GameModel, void, void, AppStoreModel>;
}
const gameModel: GameModel = {
questionList: questionListJson as QuestionType[],
questionList: [],
gameStartTime: 0,
isSubmit: false,
stageDetail: null,
updateState: action((state, obj) => {
for (const key in obj) {
state[key] = obj[key]
}
}),
currentInputIndex: 0,
currentQuestionIndex: 0,
updateCurrentInputIndex: action((state, num) => {
state.currentInputIndex = num
}),
......@@ -66,6 +87,7 @@ const gameModel: GameModel = {
}
return questionAnswers?.every((c) => !!c.userAnswer) ?? false
}),
updateSelectionAnswer: action((state, index) => {
const question = state.questionList[state.currentQuestionIndex]
if (isSelectionQuestion(question)) {
......@@ -118,19 +140,61 @@ const gameModel: GameModel = {
handleGoNext: thunk(async (actions, _, helpers) => {
const { canGoNext, currentQuestionIndex, questionList } = helpers.getState()
if (!canGoNext) return
const len = questionList.length
if (len === currentQuestionIndex + 1) {
if (questionList.length === currentQuestionIndex + 1) {
console.log('submit')
actions.submit()
return
}
actions.updateCurrentIndex(currentQuestionIndex + 1)
}),
getQuestionList: thunk(async (actions, round, helpers) => {
getQuestionList: thunk(async (actions, round) => {
try {
showLoading()
const [{ data: questionList }, { data: stageDetail }] = await Promise.all([
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 {
actions.updateList([])
} catch (err) {}
showLoading({
mask: true,
title: '提交中'
})
actions.updateState({ isSubmit: true })
const { questionList, gameStartTime, stageDetail } = helpers.getState()
await completeStage(buildCompleteStageParam(questionList, stageDetail!, gameStartTime))
} catch (err) {
showModal({
title: '提示',
content: err.message || '出错了',
showCancel: false,
})
console.log(err)
} finally {
hideLoading()
}
}),
}
......
[
{
"answers": [
{
"contentText": "69",
"sort": 0
}
],
"contentText": "28<MathSymbol value=\"+\" />41<MathSymbol value=\"=\" /><AnswerBlank index=\"0\" />",
"questionItems": [
{
"contentText": "28",
"sort": 0
},
{
"contentText": "41",
"sort": 1
},
{
"contentText": "69",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": true,
"sort": 11
},
{
"answers": [
{
"contentText": "44",
"sort": 0
}
],
"contentText": "30元钱可以买<AnswerBlank index=\"0\" />元笔记本74本",
"questionItems": [
{
"contentText": "30",
"sort": 0
},
{
"contentText": "44",
"sort": 1
},
{
"contentText": "74",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": false,
"sort": 13
},
{
"answers": [
{
"contentText": "C",
"sort": 1
}
],
"contentText": "爸爸把一盘糖果的一半给了弟弟,把剩下的糖果给了一半给姐姐,这时盘里还剩8块,请问盘里原来有几块糖?",
"options": [
{
"answer": false,
"contentText": "16块",
"index": "A"
},
{
"answer": false,
"contentText": "24块",
"index": "B"
},
{
"answer": true,
"contentText": "32块",
"index": "C"
},
{
"answer": false,
"contentText": "64块",
"index": "D"
}
],
"questionType": "选择题",
"simpleType": false,
"sort": 28
},
{
"answers": [
{
"contentText": "35",
"sort": 0
}
],
"contentText": "22<MathSymbol value=\"+\" />13<MathSymbol value=\"=\" /><AnswerBlank index=\"0\" />",
"questionItems": [
{
"contentText": "22",
"sort": 0
},
{
"contentText": "13",
"sort": 1
},
{
"contentText": "35",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": true,
"sort": 49
},
{
"answers": [
{
"contentText": "59",
"sort": 0
}
],
"contentText": "43元钱可以买16元笔记本<AnswerBlank index=\"0\" />本",
"questionItems": [
{
"contentText": "43",
"sort": 0
},
{
"contentText": "16",
"sort": 1
},
{
"contentText": "59",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": false,
"sort": 51
},
{
"answers": [
{
"contentText": "13",
"sort": 0
}
],
"contentText": "<AnswerBlank index=\"0\" />元钱可以买21元笔记本34本",
"questionItems": [
{
"contentText": "13",
"sort": 0
},
{
"contentText": "21",
"sort": 1
},
{
"contentText": "34",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": false,
"sort": 82
},
{
"answers": [
{
"contentText": "45",
"sort": 0
}
],
"contentText": "33<MathSymbol value=\"+\" />12<MathSymbol value=\"=\" /><AnswerBlank index=\"0\" />",
"questionItems": [
{
"contentText": "33",
"sort": 0
},
{
"contentText": "12",
"sort": 1
},
{
"contentText": "45",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": true,
"sort": 83
},
{
"answers": [
{
"contentText": "20",
"sort": 0
}
],
"contentText": "8<MathSymbol value=\"+\" />12<MathSymbol value=\"=\" /><AnswerBlank index=\"0\" />",
"questionItems": [
{
"contentText": "8",
"sort": 0
},
{
"contentText": "12",
"sort": 1
},
{
"contentText": "20",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": true,
"sort": 92
},
{
"answers": [
{
"contentText": "18",
"sort": 0
}
],
"contentText": "7<MathSymbol value=\"+\" />11<MathSymbol value=\"=\" /><AnswerBlank index=\"0\" />",
"questionItems": [
{
"contentText": "7",
"sort": 0
},
{
"contentText": "11",
"sort": 1
},
{
"contentText": "18",
"sort": 2
}
],
"questionType": "随机填空",
"simpleType": true,
"sort": 95
},
{
"answers": [
{
"contentText": "C",
"sort": 1
}
],
"contentText": "《钢铁是怎样炼成的》是前苏联作家奥斯特洛夫斯基的自传体小说,小说的主人公是()?",
"options": [
{
"answer": false,
"contentText": "格列佛",
"index": "A"
},
{
"answer": false,
"contentText": "汤姆·索亚",
"index": "B"
},
{
"answer": true,
"contentText": "保尔·柯察金",
"index": "C"
},
{
"answer": false,
"contentText": "海伦",
"index": "D"
}
],
"questionType": "选择题",
"simpleType": false,
"sort": 98
}
]
......@@ -32,6 +32,74 @@
"questionType": "选择题",
"simpleType": false
},
{
"contentText": "<p>某班50名学生在一次百米测试中,成绩全部介于13秒与19秒之间,将测试结果分成六组,得到频率分布直方图(如图).设成绩小于16秒的学生人数占全班总人数的百分比为<i>x</i>,成绩大于等于15秒且小于17秒的学生人数为<i>y</i>,则从频率分布直方图中可分析出<i>x</i>和<i>y</i>分别为(  )</p><p><img src=\"https://profile-1257124244.cos.ap-chengdu.myqcloud.com/question/image/943c1ee2-ed62-42d7-b381-d0e3d31677a7.png\" style=\"max-width:90vw;max-height:62.005104vw\" alt=\"\" width=\"202.90031\" height=\"139.78728\"></p>",
"options": [
{
"contentText": "<p>0.56,35</p>",
"answer": true,
"index": "A"
},
{
"contentText": "<p>0.56,45</p>",
"answer": false,
"index": "B"
},
{
"contentText": "<p>0.44,35</p>",
"answer": false,
"index": "C"
},
{
"contentText": "<p>0.44,45</p>",
"answer": false,
"index": "D"
}
],
"answers": [
{
"contentText": "C",
"sort": 1
}
],
"questionType": "选择题",
"simpleType": false,
"sort": 98
},
{
"answers": [
{
"contentText": "C",
"sort": 1
}
],
"contentText": "《钢铁是怎样炼成的》是前苏联作家奥斯特洛夫斯基的自传体小说,小说的主人公是()?",
"options": [
{
"answer": false,
"contentText": "格列佛",
"index": "A"
},
{
"answer": false,
"contentText": "汤姆·索亚",
"index": "B"
},
{
"answer": true,
"contentText": "保尔·柯察金",
"index": "C"
},
{
"answer": false,
"contentText": "海伦",
"index": "D"
}
],
"questionType": "选择题",
"simpleType": false,
"sort": 98
},
{
"answers": [
{
......
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 {
questionType: string;
answers: QuestionAnswer[];
simpleType?: boolean;
contentText: string;
options: QuestionOption[];
questionItems?: RandomQuestionItem[];
sort: number;
}
export interface BlankQuestion extends QuestionItem {
......@@ -21,9 +25,9 @@ export interface SelectionQuestion extends QuestionItem {
options: QuestionOption[];
}
export interface RandomQuestion extends QuestionItem {
questionItems?: RandomQuestionItem[];
}
// export interface RandomQuestion extends QuestionItem {
// questionItems?: RandomQuestionItem[];
// }
/** 带余除法 */
export interface DivisionWithRemainderQuestion extends QuestionItem {
......@@ -42,7 +46,7 @@ export interface MultiplicationQuestion extends QuestionItem {
questionItems: [];
}
export type QuestionType = BlankQuestion | SelectionQuestion | RandomQuestion
export type QuestionType = BlankQuestion | SelectionQuestion | VerticalDivisionQuestion
export function isBlankQuestion (q: QuestionType): q is BlankQuestion {
return q?.questionType === '填空题' || q?.questionType === '随机填空'
......
import assets from '@/assets/oss/assets-main'
import { createContext } from 'react'
import { type Stage, StageStatus, StageLevel, StageType } from '@/api'
export const SceneContext = createContext<{ ready: boolean }>({ ready: false })
......@@ -29,6 +30,8 @@ const NomalPartBgPool = [
assets['round-center-6.png'],
]
export { StageStatus, StageLevel, Stage, StageType }
export const CurrentRoundId = '__current_round__'
export const getSmallPartBg = (index: number, type: 'even' | 'odd' | 'special'): ImageSource => {
......@@ -49,7 +52,7 @@ let evenIndex = 0
let oddIndex = 0
let specialIndex = 0
export function groupRoundToSmallPart (list: Round[]): SmallPart[] {
export function groupRoundToSmallPart (list: Stage[]): SmallPart[] {
const ret: SmallPart[] = []
let flag: 'even' | 'odd' = 'even'
......@@ -102,37 +105,15 @@ export const enum RoundState {
UnLocked = 3
}
export const enum RoundType {
Strong = 'Strong',
Enhance = 'Enhance',
OneStop = 'OneStop',
}
export const enum RoundScore {
S = 'S',
A = 'A',
B = 'B'
}
export type Round = {
state?: RoundState;
score?: RoundScore;
type?: RoundType;
id: number;
name?: string;
tag?: string;
upBonus?: boolean;
}
export type SmallPart = {
rounds: Round[];
rounds: Stage[];
bg: ImageSource;
offset: number;
type: 'odd' | 'even' | 'special';
}
export type Part = {
rounds: Round[];
stages: Stage[];
number: number;
}
......
import { View } from '@tarojs/components'
import assets from '@/assets/oss/assets-main'
import { useMemo } from 'react'
import LazeImage from '../lazy-image'
import { Part, RoundScore, RoundState, RoundType } from './constants'
import { Part, Stage } from './constants'
import ScenePart from './part'
import styles from './scene.module.scss'
type SceneProps = {
stageList: Stage[];
}
function toPart (stageList: Stage[]): Part[] {
const ret: Part[] = []
stageList.forEach(item => {
const last = ret.find(c => c.number === (item.part || 0))
if (last) {
last.stages.push(item)
} else {
ret.push({
number: item.part ?? 0,
stages: [item]
})
}
})
return ret
}
const dataList: Part[] = [
{
rounds: [
{
state: RoundState.Clear,
type: RoundType.Strong,
score: RoundScore.S,
name: '计算达标1',
tag: 'top10',
id: 1,
},
{
state: RoundState.Clear,
type: RoundType.Enhance,
score: RoundScore.A,
upBonus: true,
tag: 'top20',
name: '应用过关1',
id: 2,
},
{
state: RoundState.Clear,
type: RoundType.Enhance,
score: RoundScore.S,
tag: 'top30',
name: '应用过关2',
id: 3,
},
{
state: RoundState.Clear,
type: RoundType.Strong,
score: RoundScore.A,
upBonus: true,
tag: 'topn',
name: '计算达标3',
id: 4,
},
{
state: RoundState.Clear,
type: RoundType.OneStop,
score: RoundScore.B,
name: '一站到底1',
id: 5,
}
],
number: 0
},
{
rounds: [
{
id: 6,
state: RoundState.Clear,
type: RoundType.Enhance,
name: '计算达标1',
score: RoundScore.A,
},
{
id: 7,
state: RoundState.Clear,
type: RoundType.Strong,
score: RoundScore.S,
tag: 'top20',
name: '计算达标1',
},
{
id: 8,
state: RoundState.Clear,
type: RoundType.OneStop,
score: RoundScore.S,
tag: 'top10',
name: '计算达标1',
},
{
id: 9,
state: RoundState.Clear,
type: RoundType.Enhance,
score: RoundScore.A,
name: '计算达标1',
}
],
number: 1
},
{
rounds: [
{ id: 10, type: RoundType.Enhance, state: RoundState.UnLocked, name: '计算达标1' },
{ id: 11 },
{
id: 12,
type: RoundType.OneStop,
},
{ id: 13, type: RoundType.Enhance, },
{ id: 14 },
{ id: 15, type: RoundType.Enhance, }
],
number: 2
},
{
rounds: [{ id: 16, type: RoundType.Enhance, }, { id: 17 }, { id: 18, type: RoundType.OneStop }],
number: 3
},
{
rounds: [{ id: 19 }, { id: 20, type: RoundType.OneStop }, { id: 21 }, { id: 22, type: RoundType.Enhance }, { id: 23, type: RoundType.OneStop }, { id: 24 }, { id: 25 }],
number: 4
},
]
const Scene = (props: SceneProps) => {
const partList = useMemo(() => {
return toPart(props.stageList)
}, [props.stageList])
const Scene = () => {
return (
<View>
{dataList.map(item => {
{partList.map(item => {
return (
<ScenePart part={item} key={item.number} />
)
......
......@@ -19,19 +19,17 @@ const ScenePart = (props: ScenePartProps) => {
}, [part.number])
const smallParts = useMemo(() => {
return groupRoundToSmallPart(part.rounds)
}, [part])
return groupRoundToSmallPart(part.stages)
}, [part.stages])
return (
<View>
<LazeImage source={bg} contentClass={classNames(cs.flex, cs.align_center)}>
<View className={classNames(styles.partName, cs.flex, cs.align_center)}>Part {part.number + 1}</View>
</LazeImage>
{smallParts.map(item => {
return (
<SceneSmallPart part={item} key={item.offset} />
)
})}
{smallParts.map(item => (
<SceneSmallPart part={item} key={item.offset} />
))}
</View>
)
}
......
import LazeImage from '../lazy-image'
import { type SmallPart, } from './constants'
import RoundComp from './round'
import RoundComp from './stage'
import styles from './small-part.module.scss'
......@@ -26,7 +26,7 @@ const SceneSmallPart = (props: SceneSmallPartProps) => {
<LazeImage source={part.bg}>
{part.rounds.map((item, index) => {
return (
<RoundComp round={item} key={item.id} className={getClassName(index, part.type)} />
<RoundComp stage={item} key={item.id} className={getClassName(index, part.type)} />
)
})}
</LazeImage>
......
......@@ -3,14 +3,14 @@ import { useEffect, useRef, useMemo } from 'react'
import assets from '@/assets/oss/assets-round'
import { usePageScroll, createIntersectionObserver, getCurrentInstance, getMenuButtonBoundingClientRect, IntersectionObserver, nextTick } from '@tarojs/taro'
type RoundTagProps = {
type StageTagProps = {
url?: string;
className: string;
id: number | string;
ready: boolean;
}
const RoundTag = (props: RoundTagProps) => {
const StageTag = (props: StageTagProps) => {
const nav = useRef(getMenuButtonBoundingClientRect())
const { url, className, id, ready } = props
const scrollRef = useRef(0)
......@@ -104,4 +104,4 @@ const RoundTag = (props: RoundTagProps) => {
)
}
export default RoundTag
export default StageTag
......@@ -3,25 +3,25 @@ import assets from '@/assets/oss/assets-round'
import classNames from 'classnames'
import { cs } from '@/styles'
import { navigateTo } from '@tarojs/taro'
import { RoundState, type Round, RoundType, type ImageSource, RoundScore, CurrentRoundId, SceneContext } from './constants'
import RoundTag from './round-tag'
import { type Stage, StageType, StageStatus, type ImageSource, StageLevel, CurrentRoundId, SceneContext } from './constants'
import StageTag from './stage-tag'
import styles from './round.module.scss'
import styles from './stage.module.scss'
type RoundProps = {
round: Round;
type StageProps = {
stage: Stage;
className?: string;
}
const getLockedIcon = (type?: RoundType): ImageSource => {
const getLockedIcon = (type?: StageType): ImageSource => {
switch (type) {
case RoundType.Strong: {
case StageType.Strong: {
return assets['strong-unlock.png']
}
case RoundType.Enhance: {
case StageType.Enhance: {
return assets['enhance-unlock.png']
}
case RoundType.OneStop: {
case StageType.OneStop: {
return assets['one-stop-unlock.png']
}
}
......@@ -29,15 +29,15 @@ const getLockedIcon = (type?: RoundType): ImageSource => {
return assets['strong-unlock.png']
}
const getTagIcon = (tag?: string): ImageSource | null => {
const getTagIcon = (tag?: number): ImageSource | null => {
switch (tag) {
case 'top10': {
case 10: {
return assets['top-10.png']
}
case 'top20': {
case 20: {
return assets['top-20.png']
}
case 'top30': {
case 30: {
return assets['top-30.png']
}
// case 'topn': {
......@@ -48,15 +48,15 @@ const getTagIcon = (tag?: string): ImageSource | null => {
return null
}
const getUnlockedIcon = (type?: RoundType): ImageSource => {
const getUnlockedIcon = (type?: StageType): ImageSource => {
switch (type) {
case RoundType.Strong: {
case StageType.Strong: {
return assets['strong-current-base.png']
}
case RoundType.Enhance: {
case StageType.Enhance: {
return assets['enhance-current-base.png']
}
case RoundType.OneStop: {
case StageType.OneStop: {
return assets['one-stop-current.png']
}
}
......@@ -64,15 +64,15 @@ const getUnlockedIcon = (type?: RoundType): ImageSource => {
return assets['strong-current-base.png']
}
const getClearIcon = (type?: RoundType): ImageSource => {
const getClearIcon = (type?: StageType): ImageSource => {
switch (type) {
case RoundType.Strong: {
case StageType.Strong: {
return assets['strong-clear-base.png']
}
case RoundType.Enhance: {
case StageType.Enhance: {
return assets['enhance-clear-base.png']
}
case RoundType.OneStop: {
case StageType.OneStop: {
return assets['one-stop-clear-base.png']
}
}
......@@ -80,50 +80,50 @@ const getClearIcon = (type?: RoundType): ImageSource => {
return assets['strong-clear-base.png']
}
const getScoreIcon = (score?: RoundScore): ImageSource => {
const getScoreIcon = (score?: StageLevel): ImageSource => {
switch (score) {
case RoundScore.S: {
case StageLevel.S: {
return assets['score-s.png']
}
case RoundScore.A: {
case StageLevel.A: {
return assets['score-a.png']
}
case RoundScore.B: {
case StageLevel.B: {
return assets['score-b.png']
}
}
return assets['score-b.png']
}
const getIconClassNames = (type?: RoundType, extra: string[] = []) => {
return classNames(styles.icon, type === RoundType.OneStop && styles.isOneStop, ...extra)
const getIconClassNames = (type?: StageType, extra: string[] = []) => {
return classNames(styles.icon, type === StageType.OneStop && styles.isOneStop, ...extra)
}
const RoundComp = (props: RoundProps) => {
const { round } = props
const StageComp = (props: StageProps) => {
const { stage } = props
const renderRound = (ready: boolean) => {
switch (round.state) {
case RoundState.Locked: {
switch (stage.status) {
case StageStatus.DISABLED: {
return (
<Image src={getLockedIcon(round.type).u} className={getIconClassNames(round.type)} />
<Image src={getLockedIcon(stage.type).u} className={getIconClassNames(stage.type)} />
)
}
case RoundState.UnLocked: {
case StageStatus.CURRENT: {
return (
<Image src={getUnlockedIcon(round.type).u} className={getIconClassNames(round.type)} />
<Image src={getUnlockedIcon(stage.type).u} className={getIconClassNames(stage.type)} />
)
}
case RoundState.Clear: {
const tag = getTagIcon(round.tag)
case StageStatus.PASSED: {
const tag = getTagIcon(stage.gear)
return (
<View className={styles.clear}>
<RoundTag url={tag?.u} className={styles.tag} id={round.id} ready={ready} />
<Image src={getScoreIcon(round.score).u} className={styles.score} />
<Image src={getClearIcon(round.type).u} className={getIconClassNames(round.type, [styles.clearIcon])} />
{!!round.upBonus && (
<StageTag url={tag?.u} className={styles.tag} id={stage.id} ready={ready} />
<Image src={getScoreIcon(stage.level).u} className={styles.score} />
<Image src={getClearIcon(stage.type).u} className={getIconClassNames(stage.type, [styles.clearIcon])} />
{!!stage.upGear && (
<>
<Image src={assets['up-bonus.png'].u} className={styles.upname}></Image>
<Image src={assets['up-bonus-arrow.png'].u} className={styles.uparrow}></Image>
......@@ -135,7 +135,7 @@ const RoundComp = (props: RoundProps) => {
}
return (
<Image src={getLockedIcon(round.type).u} className={getIconClassNames(round.type)} />
<Image src={getLockedIcon(stage.type).u} className={getIconClassNames(stage.type)} />
)
}
......@@ -145,15 +145,15 @@ const RoundComp = (props: RoundProps) => {
<View
className={classNames(props.className, cs.bounce_btn)}
hoverClass={cs.bounce_btn_hover}
id={round.state === RoundState.UnLocked ? CurrentRoundId : undefined}
onClick={() => navigateTo({ url: '/pages/game/play/index' })}
id={stage.status === StageStatus.CURRENT ? CurrentRoundId : undefined}
onClick={() => navigateTo({ url: `/pages/game/play/index?id=${stage.id}` })}
>
{renderRound(ready)}
<View className={styles.roundName}>{round.name}</View>
<View className={styles.roundName}>{stage.name}</View>
</View>
)}
</SceneContext.Consumer>
)
}
export default RoundComp
export default StageComp
import { View } from '@tarojs/components'
import { getMenuButtonBoundingClientRect, useDidShow, getCurrentInstance, getTabBar, pageScrollTo, getSystemInfoSync } from '@tarojs/taro'
import { useState, useMemo, useEffect, useCallback } from 'react'
import { useStoreActions, useStoreState } from '@/store/hooks'
import { CurrentRoundId, SceneContext } from './components/scene/constants'
import MainHeader from './components/header'
import MainChapter from './components/chapter'
......@@ -12,6 +13,8 @@ import styles from './main.module.scss'
const MainPage = () => {
const page = useMemo(() => getCurrentInstance().page, [])
const [isReady, setIsReady] = useState(false)
const fetchStage = useStoreActions(actions => actions.mainModel.fetchStage)
const stageList = useStoreState(state => state.mainModel.stageList)
useDidShow(() => {
const tabbar = getTabBar(page) as any
......@@ -29,12 +32,14 @@ const MainPage = () => {
}, [])
useEffect(() => {
setTimeout(() => {
scrollToCurrent(() => {
setIsReady(true)
})
}, 1000)
}, [scrollToCurrent])
fetchStage().then(() => {
setTimeout(() => {
scrollToCurrent(() => {
setIsReady(true)
})
}, 1000)
})
}, [scrollToCurrent, fetchStage])
return (
<>
......@@ -42,7 +47,7 @@ const MainPage = () => {
<View className={styles.body} style={{ paddingTop: `${nav.height + nav.top + 5}px` }}>
<MainChapter />
<SceneContext.Provider value={{ ready: isReady }}>
<MainScene />
<MainScene stageList={stageList} />
</SceneContext.Provider>
<View className={styles.gap}></View>
</View>
......
import {
action, Action, Thunk, thunk
} from 'easy-peasy'
import { AppStoreModel } from '@/store/store-model'
import { type Stage, getStageList } from '@/api'
export interface MainModel {
stageList: Stage[];
updateStageList: Action<MainModel, Stage[]>;
fetchStage: Thunk<MainModel, void, void, AppStoreModel>;
}
const mainModel: MainModel = {
stageList: [],
updateStageList: action((state, stageList) => {
state.stageList = stageList
}),
fetchStage: thunk(async (actions, _) => {
try {
const { data: stageList } = await getStageList()
actions.updateStageList(stageList)
} catch (err) {
actions.updateStageList([])
}
}),
}
export default mainModel
import gameModel from '@/pages/game/play/model'
import mainModel from '@/pages/main/model'
import cartModel from './modules/cart'
import counterModel from './modules/counter'
import prepareModel from './modules/prepare'
......@@ -8,6 +9,7 @@ const appStoreModel = {
counterModel,
prepareModel,
gameModel,
mainModel,
}
export default appStoreModel
......
......@@ -9,13 +9,13 @@ import {
const silentLoginDeferred = new Deferred<null>()
async function silentLogin (recommendId:string) {
async function silentLogin () {
try {
await Taro.checkSession()
const token = getStorage(StorageKeys.token)
// const token = getStorage(StorageKeys.token)
const openId = getStorage(StorageKeys.openid)
const userInfo = getStorage(StorageKeys.userInfo)
if (!token || !openId) { // 未登录
if (!openId) { // 未登录
throw new Error('unlogin')
}
setProfile(openId, `${userInfo?.userId}`)
......@@ -24,13 +24,16 @@ async function silentLogin (recommendId:string) {
try {
const { code } = await Taro.login()
const { data } = await silentLoginApi(code, recommendId)
const { data } = await silentLoginApi(code)
updateStorage(StorageKeys.openid, data.openId)
updateStorage(StorageKeys.unionid, data.unionId)
updateStorage(StorageKeys.token, data.token)
updateStorage(StorageKeys.userInfo, {
userId: data.userId,
})
setProfile(data.openId, `${data.id}`)
setProfile(data.openId, `${data.userId}`)
} catch (silentLoginError) {
console.log('silent login error', error)
}
......
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