GameConstant.ts 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635
  1. import { _decorator, Component, Node, math } from 'cc';
  2. import { Player } from './Player';
  3. const { ccclass, property } = _decorator;
  4. export enum ICON_TYPE {
  5. SYMBOL_FREE = 0,
  6. SYMBOL_WILD = 1,
  7. SYMBOL_COW = 2,
  8. SYMBOL_EAGLE = 3,
  9. SYMBOL_LEOPARD = 4,
  10. SYMBOL_WOLF = 5,
  11. SYMBOL_ELK = 6,
  12. SYMBOL_A = 7,
  13. SYMBOL_K = 8,
  14. SYMBOL_Q = 9,
  15. SYMBOL_J = 10,
  16. SYMBOL_10 = 11,
  17. SYMBOL_9 = 12,
  18. }
  19. @ccclass('GameConstant')
  20. export class GameConstant extends Component {
  21. public static readonly GAMEID = 69;
  22. public static readonly HTTP_HOST = "https://test.pgn-nmu2nd.com/";
  23. public static readonly MAX_ROW: number = 4;
  24. public static readonly MAX_COL: number = 6;
  25. public static readonly MAX_BET_TIMES: number = 40;
  26. public static readonly COL_ITEM_LEN: number = 12;
  27. public static readonly MAX_ICON_TYPE: number = 13;
  28. public static readonly ROLL_FAST_SPEED: number = 5200;
  29. public static readonly ROLL_NORMAL_SPEED: number = 4300;
  30. public static readonly SPECIAL_ICON: number = 0;
  31. public static readonly ICON_TYPE = ICON_TYPE;
  32. public static readonly AUTO_TYPE_COUNT = [-1, 500, 300, 100, 50, 30];
  33. public static readonly ICON_NORMAL_SPRITE_NAME: string[] = [
  34. "01_normal",
  35. "02_normal",
  36. "03_normal",
  37. "04_normal",
  38. "05_normal",
  39. "06_normal",
  40. "07_normal",
  41. "08_normal",
  42. "09_normal",
  43. "10_normal",
  44. "11_normal",
  45. "12_normal",
  46. "S13_normal"
  47. ];
  48. public static readonly ICON_BLURRED_SPRITE_NAME: string[] = [
  49. "01_blurred",
  50. "02_blurred",
  51. "03_blurred",
  52. "04_blurred",
  53. "05_blurred",
  54. "06_blurred",
  55. "07_blurred",
  56. "08_blurred",
  57. "09_blurred",
  58. "10_blurred",
  59. "11_blurred",
  60. "12_blurred",
  61. "S13_blurred"
  62. ];
  63. public static readonly RESULT_TITLE = ["nice", "mega", "superb", "sensational"];
  64. public static readonly WILD_TIMES = [1, 2, 3, 5];
  65. public static readonly ICON_TYPE_TIMES = [
  66. [80,60,60,40,40,20,20,10,10,10,10],
  67. [200,100,100,80,80,40,40,30,30,20,20],
  68. [250,200,200,120,120,80,80,60,60,40,40],
  69. [300,250,250,200,200,120,120,100,100,80,80]
  70. ];
  71. public static readonly ICON_TYPE_PROB = [
  72. [1000, 0, 100, 100, 100, 1200, 1200, 1200, 1200, 1400, 1400, 1600, 1600],
  73. [1000, 860, 1200, 1200, 1200, 100, 100, 1200, 1200, 1400, 1400, 1600, 1600],
  74. [100, 860, 1000, 1000, 1000, 1000, 1000, 100, 100, 1400, 1400, 1600, 1600],
  75. [500, 120, 900, 900, 900, 900, 900, 1200, 1200, 100, 100, 100, 100],
  76. [400, 120, 800, 800, 800, 800, 800, 1200, 1200, 1400, 1400, 1600, 1600],
  77. [400, 120, 700, 700, 700, 700, 700, 1200, 1200, 1400, 1400, 1600, 1600],
  78. ];
  79. public static NO_TIMES_ICON_TYPE = [
  80. [[8, 9, 10, 11, 12, 7],[8, 9, 10, 11, 12, 7],[8, 9, 10, 11, 12, 7],[8, 9, 10, 11, 12, 7]],
  81. [[2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7]]
  82. ];
  83. public static TEST_ICON_TYPE = [
  84. [[8, 9, 10, 11, 12, 0],[0, 9, 10, 11, 12, 7],[8, 9, 0, 11, 12, 7],[8, 9, 10, 11, 12, 7]],
  85. // [2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7],[2, 3, 4, 5, 6, 7]
  86. // [[2,2,2,2,2,2],[2,2,2,2,2,2],[2,2,2,2,2,2],[2,2,2,2,2,2]]
  87. ];
  88. public static readonly ENTER_FREE_COUNTS = [1, 1, 1, 1, 1];//[5, 8, 15, 25, 100]
  89. public static readonly bets = [100, 0.2, 0.3, 0.4, 0.5];
  90. public static readonly ENTER_TYPE_PROB = [10, 0];
  91. public static readonly ENTER_FREE_COUNTS_PROB = [100,30,20,5];
  92. public static readonly ENTER_ADD_FREE_COUNTS_PROB = [100,30,20,10,5];
  93. // 通用权重随机工具函数
  94. // ===========================
  95. private static weightedRandom(weights: number[]): number {
  96. const total = weights.reduce((a, b) => a + b, 0);
  97. let rand = Math.random() * total;
  98. for (let i = 0; i < weights.length; i++) {
  99. if (rand < weights[i]) return i;
  100. rand -= weights[i];
  101. }
  102. return weights.length - 1;
  103. }
  104. // ===========================
  105. // 是否进入小环节(根据权重)
  106. // ===========================
  107. private static shouldEnterFreeRound(): boolean {
  108. const idx = this.weightedRandom(this.ENTER_TYPE_PROB);
  109. return idx === 1; // 1代表进入
  110. }
  111. // ===========================
  112. // 获取小环节图标数量
  113. // ===========================
  114. private static getFreeRoundIconCount(isAddFree: boolean): number {
  115. const prob = isAddFree ? this.ENTER_ADD_FREE_COUNTS_PROB : this.ENTER_FREE_COUNTS_PROB;
  116. const idx = this.weightedRandom(prob);
  117. const base = isAddFree ? 2 : 3;
  118. return base + idx; // 范围:小环节 3~6,追加时 2~6
  119. }
  120. // ====================
  121. // 1️⃣ 生成随机矩阵
  122. // ====================
  123. // ===========================
  124. // ===========================
  125. // 生成图形函数(支持小环节)
  126. // ===========================
  127. public static generateGrid(isTest = false, isFreeRound = false, isAddFree = false): number[][] {
  128. const grid: number[][] = [];
  129. for (let r = 0; r < GameConstant.MAX_ROW; r++) grid[r] = [];
  130. // 计算是否要插入小环节图标
  131. let freeIconPositions: { r: number, c: number }[] = [];
  132. if (isFreeRound || isAddFree) {
  133. const iconCount = this.getFreeRoundIconCount(isAddFree);
  134. const availableCols = Array.from({ length: GameConstant.MAX_COL }, (_, i) => i);
  135. const selectedCols = [];
  136. // 每列最多一个小环节
  137. while (selectedCols.length < iconCount && availableCols.length > 0) {
  138. const idx = Math.floor(Math.random() * availableCols.length);
  139. selectedCols.push(availableCols.splice(idx, 1)[0]);
  140. }
  141. // 为每个选中列随机一行放置小环节图标(0)
  142. for (const c of selectedCols) {
  143. const r = Math.floor(Math.random() * GameConstant.MAX_ROW);
  144. freeIconPositions.push({ r, c });
  145. }
  146. }
  147. // 生成普通图标
  148. for (let c = 0; c < GameConstant.MAX_COL; c++) {
  149. const colProb = GameConstant.ICON_TYPE_PROB[c];
  150. const total = colProb.reduce((a, b) => a + b, 0);
  151. for (let r = 0; r < GameConstant.MAX_ROW; r++) {
  152. // 若该位置是小环节图标,则直接放0
  153. if (freeIconPositions.some(p => p.r === r && p.c === c)) {
  154. grid[r][c] = 0;
  155. continue;
  156. }
  157. // 否则按普通权重随机(剔除0图标)
  158. let rand = Math.floor(Math.random() * (total - colProb[0]));
  159. let acc = 0, type = 1;
  160. for (let i = 1; i < colProb.length; i++) {
  161. acc += colProb[i];
  162. if (rand < acc) {
  163. type = i;
  164. break;
  165. }
  166. }
  167. grid[r][c] = isTest ? GameConstant.TEST_ICON_TYPE[0][r][c] : type;
  168. }
  169. }
  170. return grid;
  171. }
  172. // ====================
  173. // 2️⃣ 生成百搭倍数矩阵
  174. // ====================
  175. public static generateWildTimes(grid: number[][], isInFree = false): number[][] {
  176. const rows = grid.length;
  177. const cols = grid[0].length;
  178. const wildTimes: number[][] = Array.from({ length: rows }, () => Array(cols).fill(1));
  179. for (let r = 0; r < rows; r++) {
  180. for (let c = 0; c < cols; c++) {
  181. if (grid[r][c] === 1) {
  182. // 小环节中才会随机倍数,否则始终为 1
  183. if (isInFree) {
  184. const randTimes = GameConstant.WILD_TIMES[Math.floor(Math.random() * GameConstant.WILD_TIMES.length) + 1];
  185. wildTimes[r][c] = randTimes;
  186. } else {
  187. wildTimes[r][c] = 1;
  188. }
  189. }
  190. }
  191. }
  192. return wildTimes;
  193. }
  194. // ====================
  195. // 3️⃣ 计算连线(含百搭规则)
  196. // ====================
  197. public static calcSlotLinesWithWildTimes(grid: number[][], wildsTimes: number[][], betScore) {
  198. const ROWS = grid.length;
  199. const COLS = grid[0].length;
  200. const idx = (r: number, c: number) => r * COLS + c;
  201. const toRC = (i: number) => [Math.floor(i / COLS), i % COLS];
  202. const canConnect = (a: number, b: number, baseType: number | null) => {
  203. if (a === 0 || b === 0) return false;
  204. if (b === 1) return true;
  205. if (a === 1) return !baseType || b === baseType;
  206. return b === a;
  207. };
  208. function extendFrom(row: number, col: number, symbol: number, path: number[], baseType: number | null) {
  209. const results: any[] = [];
  210. if (col >= COLS - 1) {
  211. results.push({ path, resolvedType: baseType });
  212. return results;
  213. }
  214. const nextCol = col + 1;
  215. for (let nr = 0; nr < ROWS; nr++) {
  216. const nextSym = grid[nr][nextCol];
  217. if (nextSym === 0) continue;
  218. let currentBase = baseType;
  219. if (!currentBase && symbol !== 1) currentBase = symbol;
  220. if (!canConnect(symbol, nextSym, currentBase)) continue;
  221. let nextBase = currentBase;
  222. if (nextSym !== 1) nextBase = nextSym;
  223. const newPath = [...path, idx(nr, nextCol)];
  224. results.push(...extendFrom(nr, nextCol, nextSym, newPath, nextBase));
  225. }
  226. if (results.length === 0) results.push({ path, resolvedType: baseType });
  227. return results;
  228. }
  229. const allLines: any[] = [];
  230. var m_lottery_size: number = 0;
  231. for (let r = 0; r < ROWS; r++) {
  232. const sym = grid[r][0];
  233. if (sym === 0) continue;
  234. const startIdx = idx(r, 0);
  235. const branches = extendFrom(r, 0, sym, [startIdx], sym === 1 ? null : sym);
  236. for (const b of branches) {
  237. if (b.path.length >= 3) {
  238. if (b.resolvedType === null) {
  239. for (const i of b.path) {
  240. const [rr, cc] = toRC(i);
  241. const s = grid[rr][cc];
  242. if (s !== 1 && s !== 0) {
  243. b.resolvedType = s;
  244. break;
  245. }
  246. }
  247. }
  248. if (b.resolvedType) allLines.push(b);
  249. }
  250. }
  251. }
  252. const m_line_icon: number[][] = [];
  253. const m_line_size: number[] = [];
  254. const m_line_icon_active = Array.from({ length: ROWS }, () => Array(COLS).fill(0));
  255. const m_line_times: number[] = [];
  256. const m_line_index: number[][] = [];
  257. for (const line of allLines) {
  258. const path = line.path;
  259. const iconType = line.resolvedType;
  260. const icons = path.map(i => {
  261. const [r, c] = toRC(i);
  262. return grid[r][c];
  263. });
  264. const indexes = path.map(i => i);
  265. const size = path.length;
  266. for (const i of path) {
  267. const [r, c] = toRC(i);
  268. m_line_icon_active[r][c] = 1;
  269. }
  270. let times = 0;
  271. if (size >= 3 && size <= 6 && iconType >= 2 && iconType <= 12) {
  272. times = GameConstant.ICON_TYPE_TIMES[size - 3][iconType - 2];
  273. }
  274. let wildMultiplier = 1;
  275. for (const i of path) {
  276. const [r, c] = toRC(i);
  277. if (grid[r][c] === 1 && wildsTimes[r][c] > 1) {
  278. wildMultiplier *= wildsTimes[r][c];
  279. }
  280. }
  281. times *= wildMultiplier;
  282. m_line_icon.push(icons);
  283. m_line_size.push(size);
  284. m_line_times.push(times);
  285. m_line_index.push(indexes);
  286. }
  287. m_lottery_size = m_line_times.length > 0 ? (m_line_times.reduce((pre, cur)=>{ return pre + cur; }) * betScore) : 0;
  288. return {
  289. m_line_icon,
  290. m_line_size,
  291. m_line_icon_active,
  292. m_line_times,
  293. m_line_index,
  294. m_lottery_size
  295. };
  296. }
  297. // ====================
  298. // 4️⃣ 判断是否进入小环节
  299. // ====================
  300. public static checkSpecialRound(grid: number[][], isInFree = false) {
  301. let zeroCount = 0;
  302. for (const row of grid) {
  303. for (const val of row) {
  304. if (val === 0) zeroCount++;
  305. }
  306. }
  307. let m_isSpecialGame = 0;
  308. let m_freeCount = 0;
  309. let m_freeCountAdd = 0;
  310. if (!isInFree) {
  311. // 普通模式中:≥3个0触发小环节,获得对应次数
  312. if (zeroCount >= 3) {
  313. m_isSpecialGame = 1;
  314. const idx = Math.min(zeroCount - 2, GameConstant.ENTER_FREE_COUNTS.length - 1);
  315. m_freeCount = GameConstant.ENTER_FREE_COUNTS[idx];
  316. }
  317. } else {
  318. // 小环节中:若有2个0以上则追加次数
  319. if (zeroCount >= 2) {
  320. m_isSpecialGame = 1;
  321. const idx = Math.min(zeroCount - 2, GameConstant.ENTER_FREE_COUNTS.length - 1);
  322. m_freeCountAdd = GameConstant.ENTER_FREE_COUNTS[idx];
  323. }
  324. }
  325. return { m_isSpecialGame, m_freeCount, m_freeCountAdd };
  326. }
  327. // ====================
  328. // 5️⃣ 主流程控制器
  329. // ====================
  330. public static playRound(betScore) {
  331. const results: any[] = [];
  332. let isFree = false; // 是否处于免费
  333. let remainingFree = 0; // 剩余免费次数
  334. let totalFreeCount = 0; // 累计免费次数
  335. let hasReachedMaxFree = false; // 是否到达上限
  336. let totalTimes = 0; // 累计倍数
  337. const MAX_TRIES = 100;
  338. let tempIndex = 10;
  339. do {
  340. let m_desk_data: number[][] = [];
  341. let m_wildTimes_data: number[][] = [];
  342. let lineResult: any;
  343. let specialResult: any;
  344. let tryCount = 0;
  345. let accepted = false;
  346. while (tryCount < MAX_TRIES && !accepted) {
  347. tryCount++;
  348. // === 生成图形 & 倍数 ===
  349. const shouldEnterFree = !isFree && this.shouldEnterFreeRound();
  350. const isAddFree = isFree && shouldEnterFree;
  351. m_desk_data = this.generateGrid(tempIndex++ == 0, shouldEnterFree, isAddFree);
  352. m_wildTimes_data = this.generateWildTimes(m_desk_data, isFree);
  353. // === 计算连线 & 小环节 ===
  354. lineResult = this.calcSlotLinesWithWildTimes(m_desk_data, m_wildTimes_data, betScore);
  355. specialResult = this.checkSpecialRound(m_desk_data, isFree);
  356. const hasLineWin = (lineResult.m_line_icon && lineResult.m_line_icon.length > 0);
  357. const addsFree = isFree && specialResult.m_freeCountAdd > 0;
  358. // 达到上限后禁止追加
  359. if (hasReachedMaxFree && addsFree) continue;
  360. // 触发或追加免费必须无连线
  361. if (addsFree && hasLineWin) continue;
  362. // 超出100上限
  363. if (!hasReachedMaxFree && isFree && (totalFreeCount + specialResult.m_freeCountAdd > 100)) {
  364. hasReachedMaxFree = true;
  365. }
  366. accepted = true;
  367. }
  368. // ❗保底逻辑
  369. if (!accepted) {
  370. m_desk_data = this.NO_TIMES_ICON_TYPE[0];
  371. m_wildTimes_data = this.generateWildTimes(m_desk_data, isFree);
  372. lineResult = this.calcSlotLinesWithWildTimes(m_desk_data, m_wildTimes_data, betScore);
  373. specialResult = { m_isSpecialGame: 0, m_freeCount: 0, m_freeCountAdd: 0 };
  374. if (lineResult && 'm_lottery_size' in lineResult) lineResult.m_lottery_size = 0;
  375. }
  376. const triggeredFree = specialResult.m_isSpecialGame && !isFree;
  377. const addFree = isFree && specialResult.m_isSpecialGame && specialResult.m_freeCountAdd > 0;
  378. // 触发或追加免费时不中奖
  379. if (triggeredFree || addFree) {
  380. if (lineResult && 'm_lottery_size' in lineResult) lineResult.m_lottery_size = 0;
  381. }
  382. // === 更新免费次数逻辑 ===
  383. if (specialResult.m_isSpecialGame) {
  384. if (isFree) {
  385. if (!hasReachedMaxFree) {
  386. remainingFree += specialResult.m_freeCountAdd;
  387. totalFreeCount += specialResult.m_freeCountAdd;
  388. if (totalFreeCount >= 100) {
  389. totalFreeCount = 100;
  390. hasReachedMaxFree = true;
  391. }
  392. }
  393. } else {
  394. remainingFree = specialResult.m_freeCount;
  395. totalFreeCount = specialResult.m_freeCount;
  396. if (totalFreeCount >= 100) {
  397. totalFreeCount = 100;
  398. hasReachedMaxFree = true;
  399. }
  400. isFree = true;
  401. }
  402. }
  403. // ✅ 在这里再扣除一次免费次数(只对已经在免费状态的轮次)
  404. if (isFree && !specialResult.m_isSpecialGame) {
  405. remainingFree--;
  406. }
  407. // === 累计倍数 ===
  408. if (lineResult && typeof lineResult.m_lottery_size === "number") {
  409. totalTimes += (lineResult.m_lottery_size / betScore);
  410. }
  411. const roundResult = {
  412. ...lineResult,
  413. ...specialResult,
  414. m_desk_data,
  415. m_wildTimes_data,
  416. m_curTotalFreeCount: remainingFree,
  417. tryCount,
  418. };
  419. results.push(roundResult);
  420. } while (isFree && remainingFree > 0);
  421. return { results, totalFreeCount, totalTimes };
  422. }
  423. public static getRandomNumber(min, max) {
  424. return Math.floor(math.random() * (max - min)) + min;
  425. }
  426. /**
  427. * 通用数字格式化函数
  428. *
  429. * @param value 数字值
  430. * @param options 可选配置
  431. * - decimals: 保留的小数位数(默认 2)
  432. * - useGrouping: 是否使用千分位分隔符(默认 true)
  433. * - trimZero: 是否去掉小数点后的多余 0(默认 true)
  434. * - hideDecimalIfZero: 若小数部分为 0 是否隐藏(默认 true)
  435. *
  436. * @returns 格式化后的字符串
  437. */
  438. public static formatNumber(
  439. value: number,
  440. options?: {
  441. decimals?: number; // 保留小数位
  442. useGrouping?: boolean; // 是否使用千分位
  443. trimZero?: boolean; // 是否去除多余的 0
  444. hideDecimalIfZero?: boolean; // 小数为 0 是否隐藏
  445. currency?: string; //'USD' | 'MYR' | 'EUR' | 'GBP' | 'BRL'; // 货币类型
  446. showCurrencyBefore?: boolean; // 货币符号是否在前面(默认 true)
  447. }
  448. ): string {
  449. if (isNaN(value)) return '0';
  450. const {
  451. decimals = 2,
  452. useGrouping = true,
  453. trimZero = true,
  454. hideDecimalIfZero = true,
  455. currency = Player.getInstance().currencyType || 'USD',
  456. showCurrencyBefore = true,
  457. } = options || {};
  458. // 定义货币符号映射表
  459. const currencySymbols: Record<string, string> = {
  460. USD: '$', // 美元
  461. MYR: 'RM', // 林吉特(马来西亚)
  462. EUR: '€', // 欧元
  463. GBP: '£', // 英镑
  464. BRL: 'R$', // 巴西雷亚尔
  465. };
  466. const symbol = currencySymbols[currency] || '';
  467. // 保留指定小数位
  468. let str = value.toFixed(decimals);
  469. let [integerPart, decimalPart] = str.split('.');
  470. // 千分位格式化
  471. if (useGrouping) {
  472. integerPart = integerPart.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
  473. }
  474. // 去除无意义的尾部 0
  475. if (trimZero && decimalPart) {
  476. decimalPart = decimalPart.replace(/0+$/, '');
  477. }
  478. // 如果小数部分为空或全为 0 且允许隐藏
  479. if (hideDecimalIfZero && (!decimalPart || parseInt(decimalPart) === 0)) {
  480. return showCurrencyBefore ? `${symbol}${integerPart}` : `${integerPart}${symbol}`;
  481. }
  482. // 拼接完整结果
  483. const formatted = `${integerPart}.${decimalPart}`;
  484. return showCurrencyBefore ? `${symbol}${formatted}` : `${formatted}${symbol}`;
  485. }
  486. /**
  487. * 通用 HTTP 请求方法
  488. * @param type 请求类型:"GET" 或 "POST"
  489. * @param url 请求地址
  490. * @param params 请求参数对象(GET时为查询参数,POST时为请求体)
  491. * @param isJson 是否使用 JSON 格式(仅对 POST 有效,默认 true)
  492. * @param timeout 超时时间(毫秒,默认 10000)
  493. */
  494. public static httpRequest<T = any>(
  495. type: 'GET' | 'POST',
  496. url: string,
  497. params?: Record<string, any>,
  498. isJson: boolean = true,
  499. timeout: number = 10000
  500. ): Promise<T> {
  501. return new Promise((resolve, reject) => {
  502. const xhr = new XMLHttpRequest();
  503. if (type === 'GET' && params) {
  504. // 拼接 GET 参数
  505. const query = Object.keys(params)
  506. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params[key])}`)
  507. .join('&');
  508. url += (url.includes('?') ? '&' : '?') + query;
  509. }
  510. console.log(url);
  511. xhr.open(type, url, true);
  512. xhr.timeout = timeout;
  513. if (type === 'POST') {
  514. if (isJson) {
  515. xhr.setRequestHeader('Content-Type', 'application/json');
  516. } else {
  517. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
  518. }
  519. }
  520. xhr.onreadystatechange = () => {
  521. if (xhr.readyState === 4) {
  522. if (xhr.status >= 200 && xhr.status < 300) {
  523. try {
  524. const response = JSON.parse(xhr.responseText);
  525. resolve(response);
  526. } catch {
  527. resolve(xhr.responseText as any);
  528. }
  529. } else {
  530. reject(new Error(`HTTP ${type} 请求失败:状态码 ${xhr.status}`));
  531. }
  532. }
  533. };
  534. xhr.onerror = (e) => {
  535. console.error(`HTTP ${type} 请求网络错误:`, e);
  536. reject(new Error(`HTTP ${type} 请求网络错误`));
  537. }
  538. xhr.ontimeout = () => reject(new Error(`HTTP ${type} 请求超时`));
  539. if (type === 'POST') {
  540. const body = isJson
  541. ? JSON.stringify(params || {})
  542. : Object.keys(params || {})
  543. .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(params![key])}`)
  544. .join('&');
  545. xhr.send(body);
  546. } else {
  547. xhr.send();
  548. }
  549. });
  550. }
  551. }