InitCheckpoint.ts 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  1. import { color, v3 } from "cc";
  2. import { AsyncQueue } from "../../../../../extensions/oops-plugin-framework/assets/libs/collection/AsyncQueue";
  3. import { ecs } from "../../../../../extensions/oops-plugin-framework/assets/libs/ecs/ECS";
  4. import { Grid } from "../../grid/Grid";
  5. import { Checkpoint } from "../Checkpoint";
  6. import { CheckpointModelLevelComp } from "../model/CheckpointModelLevel";
  7. import { CheckpointViewComp } from "../view/CheckpointViewComp";
  8. import { CheckpointModelComp } from "../model/CheckpointModel";
  9. import { Station } from "../../station/Station";
  10. import { GridModelComp } from "../../grid/model/GridModelComp";
  11. import { Obstacle } from "../../obstacle/Obstacle";
  12. import { Puppet } from "../../puppet/puppet";
  13. import { PuppetModelComp } from "../../puppet/model/PuppetModelComp";
  14. import { ObstacleModelComp } from "../../obstacle/model/ObstacleModelComp";
  15. import { PathFindComp } from "../../common/ecs/path/PathFind";
  16. import { oops } from "../../../../../extensions/oops-plugin-framework/assets/core/Oops";
  17. import { Vehicle } from "../../vehicle/Vehicle";
  18. import { VehicleModelComp } from "../../vehicle/model/VehicleModelComp";
  19. import { VehicleOperationComp } from "./VehicleOperation";
  20. import { UIID } from "../../common/config/GameUIConfig";
  21. import { CheckpointModelBaseComp } from "../model/CheckpointModelBase";
  22. import { SingletonModuleComp, smc } from "../../common/SingletonModuleComp";
  23. import { ECSEntity } from "../../../../../extensions/oops-plugin-framework/assets/libs/ecs/ECSEntity";
  24. import { Subway } from "../../subway/Subway";
  25. import { SubwayModelComp } from "../../subway/model/SubwayModelComp";
  26. import { SubwayEnum } from "../../subway/model/SubwayEnum";
  27. /** 初始化游戏公共资源 */
  28. @ecs.register('InitCheckpoint')
  29. export class InitCheckpointComp extends ecs.Comp {
  30. reset() { }
  31. }
  32. export class InitCheckpointSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
  33. filter(): ecs.IMatcher {
  34. return ecs.allOf(InitCheckpointComp, CheckpointModelComp, CheckpointModelLevelComp, CheckpointModelBaseComp);
  35. }
  36. entityEnter(e: Checkpoint): void {
  37. const levelConfig = e.get(CheckpointModelLevelComp)?.rtluCurrent
  38. const { gridRowCount, gridColCount, levelColor, peopleCount, vehicleColor, vehicleType,
  39. obstaclePosition, stationCount, peopleColor, peoplePosition, subwayPosition, subwayDir, subwayInfo } = levelConfig
  40. this.resetCheckpoint(e)
  41. // 关卡数据
  42. oops.audio.volumeMusic = 1
  43. e.CheckpointModel.vmAdd();
  44. e.CheckpointModelBase.vmAdd();
  45. !e.CheckpointModelLevel && e.CheckpointModelLevel.vmAdd();
  46. // 添加关卡到场景
  47. e.load(oops.game.root, v3(0, 0, 0), () => {
  48. this.createGrid(e, gridRowCount, gridColCount)
  49. if (peopleCount) { // 自动生成
  50. e.CheckpointModel.peopleCount = peopleCount
  51. const count = Math.ceil(peopleCount / 3)
  52. const colorCount = this.distributePeopleToColorsByArray(peopleCount, levelColor)
  53. const { gridPositions, gridColors, subwayPositions, subwayColors, subwayOrientations } = this.distributeToGridAndSubwayWithOptimizedPlacement(gridRowCount, gridColCount, colorCount, levelColor, 24)
  54. this.createMan(e, gridPositions, gridColors, levelColor)
  55. this.createSubway(e, subwayPositions, subwayOrientations, subwayColors, levelColor)
  56. this.createStation(e, stationCount)
  57. this.createVehicle(e, count, [], colorCount, levelColor)
  58. } else { // 依据配置生成
  59. this.createObstacle(e, obstaclePosition)
  60. this.createMan(e, peoplePosition, peopleColor, levelColor)
  61. this.createSubway(e, subwayPosition, subwayDir, subwayInfo, levelColor)
  62. this.createStation(e, stationCount)
  63. let subwayPeople = 0
  64. let flatSubwayArr = []
  65. if (subwayInfo) {
  66. flatSubwayArr = subwayInfo.flat()
  67. subwayPeople = flatSubwayArr.length
  68. }
  69. e.CheckpointModel.peopleCount = peopleColor.length + subwayPeople
  70. const count = Math.ceil((peopleColor.length + subwayPeople) / 3)
  71. const colorCount = {}
  72. const colorArr = levelColor as number[]
  73. colorArr.forEach((val, index) => {
  74. if (colorCount[val] == null) {
  75. colorCount[val] = 0
  76. }
  77. colorCount[val] = peopleColor.filter(v => v === index + 1).length + flatSubwayArr.filter(v => v === index + 1).length
  78. })
  79. this.createVehicle(e, count, vehicleColor, colorCount, levelColor)
  80. }
  81. e.add(VehicleOperationComp)
  82. e.remove(InitCheckpointComp)
  83. // 关闭加载界面
  84. oops.gui.remove(UIID.Loading);
  85. });
  86. oops.gui.open(UIID.Game)
  87. }
  88. resetCheckpoint(e: Checkpoint) {
  89. e.remove(CheckpointViewComp);
  90. e.add(CheckpointModelComp, true)
  91. e.add(CheckpointModelBaseComp, true)
  92. // e.add(CheckpointModelLevelComp, true)
  93. e.children.forEach(child => {
  94. e.removeChild(child);
  95. child.destroy();
  96. });
  97. }
  98. distributePeopleToColorsByArray(totalPeople: number, colors: string[]) {
  99. // 验证输入
  100. if (totalPeople % 3 !== 0) {
  101. return '给定的人数必须是3的倍数';
  102. }
  103. const colorCount = colors.length;
  104. let baseDistribution = Math.floor(totalPeople / colorCount);
  105. let remainder = totalPeople % colorCount;
  106. // 确保基础分配是3的倍数
  107. if (baseDistribution % 3 !== 0) {
  108. baseDistribution -= baseDistribution % 3;
  109. remainder += totalPeople - (baseDistribution * colorCount);
  110. }
  111. // 初始化颜色分配对象
  112. const colorDistribution = colors.reduce((acc, color) => {
  113. acc[color] = baseDistribution;
  114. return acc;
  115. }, {});
  116. // 处理余数,尽可能平均分配
  117. let index = 0;
  118. while (remainder > 0) {
  119. colorDistribution[colors[index]] += 3; // 每次增加3人以保持总数为3的倍数
  120. remainder -= 3;
  121. index = (index + 1) % colorCount; // 环形处理颜色索引
  122. }
  123. return colorDistribution;
  124. }
  125. distributeToGridAndSubwayWithOptimizedPlacement(row: number, col: number, colorDistribution: any, colors: string[], subwayCapacity = 24) {
  126. const grid = Array.from({ length: row }, () => Array(col).fill(null));
  127. let freePositions = [];
  128. let freePositionsCopy = [];
  129. for (let i = 0; i < row; i++) {
  130. for (let j = 0; j < col; j++) {
  131. freePositions.push([i, j]);
  132. freePositionsCopy.push([i, j]);
  133. }
  134. }
  135. const gridColors: number[] = []
  136. const gridPositions: [x: number, y: number][] = []
  137. const subwayPositions: [x: number, y: number][] = [];
  138. const subwayColors: number[][] = [];
  139. const subwayOrientations: number[] = [];
  140. const cellCount = row * col
  141. // 创建颜色池
  142. let colorPool: number[] = [];
  143. colors.forEach((color, index) => {
  144. for (let i = 0; i < colorDistribution[color]; i++) {
  145. colorPool.push(index + 1);
  146. }
  147. });
  148. const getSubwayOrientation = () => Math.random() < 0.5 ? SubwayEnum.LEFT : SubwayEnum.RIGHT;
  149. // // 随机选择颜色函数
  150. // const selectRandomColor = () => {
  151. // if (colorPool.length === 0) return null;
  152. // let index = Math.floor(Math.random() * colorPool.length);
  153. // return colorPool.splice(index, 1)[0] as number; // 从颜色池中移除并返回选中的颜色
  154. // };
  155. const randColorPool = this.shuffleArray(colorPool)
  156. randColorPool.forEach((colorIndex) => {
  157. // let people = colorDistribution[colors[colorIndex-1]];
  158. if (freePositions.length > 0) {
  159. let randomIndex = Math.floor(Math.random() * freePositions.length);
  160. let [x, y] = freePositions[randomIndex];
  161. grid[x][y] = colorIndex;
  162. gridColors.push(colorIndex)
  163. gridPositions.push([x, y])
  164. freePositions.splice(randomIndex, 1);
  165. } else {
  166. if (!subwayColors[subwayColors.length - 1] || subwayColors[subwayColors.length - 1].length >= subwayCapacity) {
  167. const orientation = getSubwayOrientation();
  168. const filteredPositions = freePositionsCopy.filter(([x, y]) =>
  169. ((orientation === SubwayEnum.LEFT && y > 0) || (orientation === SubwayEnum.RIGHT && y < col - 1)) && grid[x][y] !== 'Subway');
  170. if (filteredPositions.length > 0) {
  171. const index = Math.floor(Math.random() * filteredPositions.length);
  172. const [subwayX, subwayY] = filteredPositions[index];
  173. const gridColor = grid[subwayX][subwayY]
  174. subwayPositions.push([subwayX, subwayY]);
  175. const existIndex = gridPositions.findIndex(val => {
  176. const [x, y] = val
  177. return x === subwayX && y === subwayY
  178. })
  179. if (existIndex > -1) {
  180. gridPositions.splice(existIndex, 1)
  181. gridColors.splice(existIndex, 1)
  182. }
  183. subwayColors.push([gridColor, colorIndex]); // 新地铁的颜色
  184. subwayOrientations.push(orientation);
  185. grid[subwayX][subwayY] = 'Subway';
  186. freePositionsCopy.splice(index, 1);
  187. }
  188. } else {
  189. subwayColors[subwayColors.length - 1].push(colorIndex); // 添加到最后一个地铁的颜色
  190. }
  191. }
  192. })
  193. return {
  194. gridPositions: gridPositions.map(([x, y]) => [x + 1, y + 1]) as [x: number, y: number][],
  195. gridColors,
  196. subwayPositions: subwayPositions.map(([x, y]) => [x + 1, y + 1]) as [x: number, y: number][],
  197. subwayColors,
  198. subwayOrientations
  199. };
  200. }
  201. // 洗牌算法打乱颜色
  202. shuffleArray(array) {
  203. for (let i = array.length - 1; i > 0; i--) {
  204. // 生成从 0 到 i 的随机数
  205. const j = Math.floor(Math.random() * (i + 1));
  206. // 交换元素 array[i] 和 array[j]
  207. [array[i], array[j]] = [array[j], array[i]];
  208. }
  209. return array;
  210. }
  211. // 生成棋盘相关
  212. createGrid(e: Checkpoint, row: number, col: number) {
  213. const checkpoint_root = e.get(CheckpointViewComp).node
  214. const checkpoint_model = e.get(CheckpointModelComp)
  215. checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  216. checkpoint_model.cells = Array.from({ length: row }, () => new Array(col).fill(null));
  217. checkpoint_model.path_grid = Array.from({ length: row }, () => new Array(col).fill(null));
  218. const start_point = row % 2 === 0 ? v3(-row / 2 * 0.5+0.1, 0, 2.7) : v3(-row / 2 * 0.75, 0, 2.7)
  219. for (let index = 0; index < row; index++) {
  220. for (let j = 0; j < col; j++) {
  221. const gridEnt = ecs.getEntity<Grid>(Grid);
  222. // 添加关卡到场景
  223. const pos = v3(start_point.x + j * 0.5, 0, start_point.z + index * 0.5)
  224. gridEnt.load(checkpoint_root, pos);
  225. e.addChild(gridEnt)
  226. checkpoint_model.grids[index][j] = gridEnt
  227. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  228. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  229. // const obstacleModel = obstacle.get(ObstacleModelComp)
  230. // obstacleModel.type = fill
  231. // obstacle.load(checkpoint_root, pos);
  232. // checkpoint_model.cells[index][j] = obstacle
  233. // checkpoint_model.path_grid[index][j] = {
  234. // x: index,
  235. // y: j,
  236. // fill: fill,
  237. // pos: pos
  238. // }
  239. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  240. // const puppet = ecs.getEntity<Puppet>(Puppet)
  241. // const puppetModel = puppet.get(PuppetModelComp)
  242. // puppetModel.color = fill
  243. // puppetModel.x = index
  244. // puppetModel.y = j
  245. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  246. // checkpoint_model.cells[index][j] = puppet
  247. // checkpoint_model.path_grid[index][j] = {
  248. // x: index,
  249. // y: j,
  250. // fill: fill,
  251. // pos: pos
  252. // }
  253. // const pathComp = puppet.add(PathFindComp)
  254. // pathComp.x = index
  255. // pathComp.y = j
  256. // } else { // 空格
  257. // checkpoint_model.path_grid[index][j] = {
  258. // x: index,
  259. // y: j,
  260. // fill: null,
  261. // pos: pos
  262. // }
  263. // }
  264. }
  265. }
  266. }
  267. // 生成人物
  268. createMan(e: Checkpoint, position: [x: number, y: number][], color: number[], colorArr: string[]) {
  269. const checkpoint_root = e.get(CheckpointViewComp).node
  270. const checkpoint_model = e.get(CheckpointModelComp)
  271. position && position.forEach((val, index) => {
  272. const [x, y] = val
  273. const xIndex = x - 1
  274. const yIndex = y - 1
  275. const puppet = ecs.getEntity<Puppet>(Puppet)
  276. const puppetModel = puppet.get(PuppetModelComp)
  277. const fillColor = colorArr[color[index] - 1]
  278. puppetModel.color = fillColor
  279. puppetModel.x = xIndex
  280. puppetModel.y = yIndex
  281. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  282. puppet.load(checkpoint_root, fillColor, pos, smc.initialize.account.AccountModel.skin);
  283. checkpoint_model.cells[xIndex][yIndex] = puppet
  284. checkpoint_model.path_grid[xIndex][yIndex] = {
  285. x: xIndex,
  286. y: yIndex,
  287. fill: fillColor,
  288. pos: pos
  289. }
  290. const pathComp = puppet.add(PathFindComp)
  291. pathComp.x = xIndex
  292. pathComp.y = yIndex
  293. })
  294. }
  295. // 生成障碍物
  296. createObstacle(e: Checkpoint, position: [x: number, y: number][]) {
  297. const checkpoint_root = e.get(CheckpointViewComp).node
  298. const checkpoint_model = e.get(CheckpointModelComp)
  299. position && position.forEach((val, index) => {
  300. const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  301. const [x, y] = val
  302. const xIndex = x - 1
  303. const yIndex = y - 1
  304. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  305. obstacle.load(checkpoint_root, pos);
  306. checkpoint_model.cells[xIndex][yIndex] = obstacle
  307. checkpoint_model.path_grid[xIndex][yIndex] = {
  308. x: xIndex,
  309. y: yIndex,
  310. fill: 'obstacle',
  311. pos: pos
  312. }
  313. })
  314. }
  315. // 生成地铁
  316. createSubway(e: Checkpoint, position: [x: number, y: number][], dir: number[], info: number[][], colorArr: string[]) {
  317. const checkpoint_root = e.get(CheckpointViewComp).node
  318. const checkpoint_model = e.get(CheckpointModelComp)
  319. position && position.forEach((val, index) => {
  320. const [x, y] = val
  321. const xIndex = x - 1
  322. const yIndex = y - 1
  323. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  324. const d = dir[index]
  325. const subway = ecs.getEntity<Subway>(Subway)
  326. const subwayModel = subway.SubwayModel
  327. subwayModel.colorArr = info[index].map(v => colorArr[v - 1])
  328. subwayModel.type = d
  329. subwayModel.x = xIndex
  330. subwayModel.y = yIndex
  331. subway.load(checkpoint_root, pos, d);
  332. checkpoint_model.cells[xIndex][yIndex] = subway
  333. checkpoint_model.path_grid[xIndex][yIndex] = {
  334. x: xIndex,
  335. y: yIndex,
  336. fill: 'subway',
  337. pos: pos
  338. }
  339. })
  340. }
  341. // 生成站台
  342. createStation(e: Checkpoint, count: number) {
  343. const checkpoint_root = e.get(CheckpointViewComp).node
  344. const checkpoint_model = e.get(CheckpointModelComp)
  345. const start_point = v3(-1.2, 0, 1.2)
  346. for (let index = 0; index < count; index++) {
  347. const station = ecs.getEntity<Station>(Station);
  348. // 添加关卡到场景
  349. const h_index = index % 5
  350. // const v_index = Math.floor(index / 5)
  351. const v_index = checkpoint_model.stations.length >= 5 ? 1 : 0
  352. station.load(checkpoint_root, v3(start_point.x + h_index * 0.5, 0, start_point.z + v_index * 0.5));
  353. e.addChild(station)
  354. checkpoint_model.stations.push(station)
  355. }
  356. }
  357. // 生成交通工具
  358. createVehicle(e: Checkpoint, count: number, pcolor: number[], colorCount: any, colors: string[]) {
  359. const copyColorCount = {...colorCount}
  360. const checkpoint_root = e.CheckpointView.node
  361. const checkpoint_model = e.CheckpointModel
  362. const availablePositions = Array.from({ length: count }, (_, i) => i)
  363. checkpoint_model.vehicles = Array(count).fill(null)
  364. const start_point = v3(-5, 0, 0)
  365. pcolor?.forEach((v,i)=>{
  366. const color = colors[pcolor[i] - 1]
  367. if (copyColorCount[color] > 0) {
  368. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  369. availablePositions.shift()
  370. copyColorCount[color]-=3;
  371. // 添加车到场景
  372. vehicle.VehicleModel.color = color
  373. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  374. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  375. e.addChild(vehicle)
  376. checkpoint_model.vehicles[i] = vehicle
  377. }
  378. })
  379. while (availablePositions.length > 0) {
  380. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  381. let colorIndex = Math.floor(Math.random() * colors.length);
  382. let color = colors[colorIndex];
  383. if (copyColorCount[color] > 0) {
  384. // if (randomIndex < pcolor.length) {
  385. // availablePositions.splice(randomIndex, 1);
  386. // }
  387. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  388. let index = availablePositions.splice(randomIndex, 1)[0];
  389. copyColorCount[color]-=3;
  390. // 添加车到场景
  391. vehicle.VehicleModel.color = color
  392. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  393. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  394. e.addChild(vehicle)
  395. checkpoint_model.vehicles[index] = vehicle
  396. }
  397. }
  398. // for (let index = 0; index < count; index++) {
  399. // const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  400. // const vehicleModel = vehicle.get(VehicleModelComp)
  401. // if (index < color.length) {
  402. // const v_color = colors[color[index] - 1]
  403. // vehicleModel.color = v_color
  404. // colorCount[v_color] = colorCount[v_color] - 1
  405. // } else {
  406. // const v_color = colors[index % 3]
  407. // vehicleModel.color
  408. // }
  409. // // 添加车到场景
  410. // const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  411. // vehicle.load(checkpoint_root, vehicleModel.color, start_point, vehicleType);
  412. // e.addChild(vehicle)
  413. // checkpoint_model.vehicles.push(vehicle)
  414. // }
  415. }
  416. // // 生成棋盘相关
  417. // createGrid(e: Checkpoint, row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  418. // const checkpoint_root = e.get(CheckpointViewComp).node
  419. // const checkpoint_model = e.get(CheckpointModelComp)
  420. // const grids = this.generateGridWithEmptySpaces(row, col, colors, obstacles, peopleCount, obstacleCount)
  421. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  422. // checkpoint_model.cells = Array.from({ length: row }, () => new Array(col).fill(null));
  423. // checkpoint_model.path_grid = Array.from({ length: row }, () => new Array(col).fill(null));
  424. // const start_point = v3(-1.9, 0, 2.7)
  425. // for (let index = 0; index < grids.length; index++) {
  426. // for (let j = 0; j < grids[index].length; j++) {
  427. // const gridEnt = ecs.getEntity<Grid>(Grid);
  428. // const gridModel = gridEnt.get(GridModelComp)
  429. // // 添加关卡到场景
  430. // const fill = grids[index][j]
  431. // gridModel.color = fill
  432. // const pos = v3(start_point.x + j * 0.5, 0, start_point.z + index * 0.5)
  433. // gridEnt.load(checkpoint_root, pos);
  434. // e.addChild(gridEnt)
  435. // checkpoint_model.grids[index][j] = gridEnt
  436. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  437. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  438. // const obstacleModel = obstacle.get(ObstacleModelComp)
  439. // obstacleModel.type = fill
  440. // obstacle.load(checkpoint_root, pos);
  441. // checkpoint_model.cells[index][j] = obstacle
  442. // checkpoint_model.path_grid[index][j] = {
  443. // x: index,
  444. // y: j,
  445. // fill: fill,
  446. // pos: pos
  447. // }
  448. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  449. // const puppet = ecs.getEntity<Puppet>(Puppet)
  450. // const puppetModel = puppet.get(PuppetModelComp)
  451. // puppetModel.color = fill
  452. // puppetModel.x = index
  453. // puppetModel.y = j
  454. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  455. // checkpoint_model.cells[index][j] = puppet
  456. // checkpoint_model.path_grid[index][j] = {
  457. // x: index,
  458. // y: j,
  459. // fill: fill,
  460. // pos: pos
  461. // }
  462. // const pathComp = puppet.add(PathFindComp)
  463. // pathComp.x = index
  464. // pathComp.y = j
  465. // } else { // 空格
  466. // checkpoint_model.path_grid[index][j] = {
  467. // x: index,
  468. // y: j,
  469. // fill: null,
  470. // pos: pos
  471. // }
  472. // }
  473. // }
  474. // }
  475. // }
  476. // // 生成棋盘格
  477. // createGrid(e: Checkpoint, row: number, col: number) {
  478. // const checkpoint_root = e.get(CheckpointViewComp).node
  479. // const checkpoint_model = e.get(CheckpointModelComp)
  480. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  481. // const start_point = v3(-1.706, 0, -1.718)
  482. // for (let index = 0; index < row; index++) {
  483. // for (let j = 0; j < col; j++) {
  484. // const grid = ecs.getEntity<Grid>(Grid);
  485. // // 添加关卡到场景
  486. // grid.load(checkpoint_root, v3(start_point.x + index * 0.6, 0, start_point.z + j * 0.6));
  487. // e.addChild(grid)
  488. // checkpoint_model.grids[index][j] = grid
  489. // }
  490. // }
  491. // }
  492. calcMaxCount(row: number, col: number, peopleCount: number) {
  493. const totalCells = row * col;
  494. let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  495. return Math.min(maxCount / 3, peopleCount * 3); // 分配三分之一
  496. }
  497. generateGridWithEmptySpaces(row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  498. let grid = Array.from({ length: row }, () => new Array(col).fill(null));
  499. // 初始化颜色计数
  500. let counts = {};
  501. colors.forEach(color => {
  502. counts[color] = this.calcMaxCount(row, col, peopleCount); // 分配三分之一
  503. });
  504. // 创建所有可能的格子位置数组
  505. let availablePositions = [];
  506. for (let i = 0; i < row; i++) {
  507. for (let j = 0; j < col; j++) {
  508. availablePositions.push([i, j]);
  509. }
  510. }
  511. let obstacleNum = obstacleCount
  512. // 随机分配颜色到网格中
  513. while (availablePositions.length > 0) {
  514. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  515. let position = availablePositions.splice(randomIndex, 1)[0];
  516. let x = position[0];
  517. let y = position[1];
  518. let colorIndex = Math.floor(Math.random() * colors.length);
  519. let color = colors[colorIndex];
  520. if (counts[color] > 0) {
  521. grid[x][y] = color;
  522. counts[color]--;
  523. } else if (obstacleNum > 0) {
  524. grid[x][y] = obstacles[Math.floor(Math.random() * obstacles.length)]
  525. obstacleNum--
  526. }
  527. }
  528. return grid;
  529. }
  530. // generateOptimizedGrid(colors:string[]) {
  531. // const gridSize = 7;
  532. // const totalCells = gridSize * gridSize;
  533. // // const colors = ['红色', '蓝色', '绿色'];
  534. // let grid = Array(gridSize).fill().map(() => Array(gridSize).fill(''));
  535. // // 初始化每种颜色的人数
  536. // let counts = { '红色': 0, '蓝色': 0, '绿色': 0 };
  537. // // 首先分配每种颜色的人数,使其尽可能接近总数且是 3 的倍数
  538. // for (let color of colors) {
  539. // let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  540. // counts[color] = maxCount / 3; // 分配三分之一
  541. // }
  542. // // 在剩余的空格中随机分配颜色或保持为空
  543. // let remainingCells = totalCells - 3 * Math.floor((totalCells - 1) / 3);
  544. // let colorIndices = colors.map((_, index) => index);
  545. // while (remainingCells > 0) {
  546. // let randomIndex = Math.floor(Math.random() * colorIndices.length);
  547. // let color = colors[colorIndices[randomIndex]];
  548. // counts[color]++;
  549. // remainingCells--;
  550. // }
  551. // // 将颜色分配到网格中
  552. // let flatGrid = grid.flat();
  553. // colors.forEach(color => {
  554. // for (let i = 0; i < counts[color]; i++) {
  555. // let pos;
  556. // do {
  557. // pos = Math.floor(Math.random() * flatGrid.length);
  558. // } while (flatGrid[pos] !== '');
  559. // flatGrid[pos] = color;
  560. // }
  561. // });
  562. // // 重新构建二维网格
  563. // for (let i = 0; i < flatGrid.length; i++) {
  564. // grid[Math.floor(i / gridSize)][i % gridSize] = flatGrid[i];
  565. // }
  566. // return grid;
  567. // }
  568. }