GameConstant.ts 23 KB

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