useGame.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. import {
  2. reactive,
  3. ref,
  4. getCurrentInstance,
  5. onMounted,
  6. toRefs
  7. } from "vue";
  8. import {
  9. onLoad
  10. } from '@dcloudio/uni-app';
  11. import {toast,getUserIdentity,catchError} from "@/utils/common";
  12. import {getYouxiInfo, getYouxiWeishi} from "@/api/game.js";
  13. import cacheManager from "@/utils/cacheManager.js"
  14. export function useGame() {
  15. const UserCode = getUserIdentity();
  16. const auth = cacheManager.get('auth');
  17. const data = reactive({
  18. credit: 0, // 当前积分
  19. growth: 0, // 成长值
  20. growthType:0, // 成长类型
  21. progress:0, // 当前进度
  22. shiwuId:null // 上一次食物
  23. })
  24. if (auth) {
  25. data.growthType = auth.growthType;
  26. }
  27. async function getGameInfo() {
  28. const [err, info] = await catchError(getYouxiInfo());
  29. if (err) {
  30. toast("请求异常,请稍后尝试");
  31. return;
  32. }
  33. const {
  34. credit,growth,growthType,progress,shiwuId
  35. } = info;
  36. data.credit = credit;
  37. data.growth = growth;
  38. data.growthType = growthType;
  39. data.progress = progress;
  40. data.shiwuId = shiwuId;
  41. }
  42. async function handleWeishi({id:cShiwuId,credit:cCredit}, doFinish) {
  43. const [err, info] = await catchError(getYouxiWeishi({shiwuId:cCredit,credit:cShiwuId }));
  44. if (err) {
  45. toast("请求异常,请稍后尝试");
  46. return;
  47. }
  48. const {
  49. credit,growth,growthType,progress,shiwuId
  50. } = info;
  51. data.credit = credit;
  52. data.growthType = growthType;
  53. data.progress = progress;
  54. data.shiwuId = shiwuId;
  55. // 更新成长状态
  56. updateCachegrowthType(growthType);
  57. doFinish && doFinish();
  58. }
  59. // 更新缓存 大鹅成长值
  60. function updateCachegrowthType(growthType) {
  61. cacheManager.updateObject('auth', { growthType })
  62. }
  63. onLoad(async (options) => {
  64. if (UserCode !== "Visitor") {
  65. getGameInfo();
  66. } else {}
  67. })
  68. return {
  69. ...toRefs(data),
  70. UserCode,
  71. handleWeishi,
  72. }
  73. }