useGame.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. growthTotal:0, // 成长类型
  22. progress:0, // 当前进度
  23. shiwuId:null // 上一次食物
  24. })
  25. if (auth) {
  26. data.growthType = auth.growthType;
  27. }
  28. async function getGameInfo() {
  29. const [err, info] = await catchError(getYouxiInfo());
  30. if (err) {
  31. toast("请求异常,请稍后尝试");
  32. return;
  33. }
  34. const {
  35. credit,growth,growthTotal,growthType,progress,shiwuId
  36. } = info;
  37. data.credit = credit;
  38. data.growthTotal = growthTotal;
  39. data.growth = growth;
  40. data.growthType = growthType;
  41. data.progress = progress;
  42. data.shiwuId = shiwuId;
  43. }
  44. async function handleWeishi({id:cShiwuId,credit:cCredit}, doFinish) {
  45. const [err, info] = await catchError(getYouxiWeishi({shiwuId:cCredit,credit:cShiwuId }));
  46. if (err) {
  47. toast("请求异常,请稍后尝试");
  48. return;
  49. }
  50. const {
  51. credit,growth,growthType,progress,shiwuId,growthTotal
  52. } = info;
  53. data.credit = credit;
  54. data.growthTotal = growthTotal;
  55. data.growthType = growthType;
  56. data.growth = growth;
  57. data.progress = progress;
  58. data.shiwuId = shiwuId;
  59. // 更新成长状态
  60. updateCachegrowthType(growthType);
  61. doFinish && doFinish();
  62. }
  63. // 更新缓存 大鹅成长值
  64. function updateCachegrowthType(growthType) {
  65. cacheManager.updateObject('auth', { growthType })
  66. }
  67. onLoad(async (options) => {
  68. if (UserCode !== "Visitor") {
  69. getGameInfo();
  70. } else {}
  71. })
  72. return {
  73. ...toRefs(data),
  74. UserCode,
  75. handleWeishi,
  76. }
  77. }