InitCheckpoint.ts 38 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829
  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. import { CheckpointPathTriggerComp } from "./CheckpointPathTrigger";
  28. import { ArrayUtil } from "../../../../../extensions/oops-plugin-framework/assets/core/utils/ArrayUtil";
  29. /** 初始化游戏公共资源 */
  30. @ecs.register('InitCheckpoint')
  31. export class InitCheckpointComp extends ecs.Comp {
  32. reset() { }
  33. }
  34. export class InitCheckpointSystem extends ecs.ComblockSystem implements ecs.IEntityEnterSystem {
  35. filter(): ecs.IMatcher {
  36. return ecs.allOf(InitCheckpointComp, CheckpointModelComp, CheckpointModelLevelComp, CheckpointModelBaseComp);
  37. }
  38. entityEnter(e: Checkpoint): void {
  39. const levelConfig = e.get(CheckpointModelLevelComp)?.rtluCurrent
  40. const { gridRowCount, gridColCount, levelColor, peopleCount, vehicleColor, vehicleType,
  41. obstaclePosition, stationCount, peopleColor, peoplePosition, subwayPosition, subwayDir, subwayInfo } = levelConfig
  42. this.resetCheckpoint(e)
  43. // 关卡数据
  44. oops.audio.volumeMusic = 1
  45. e.CheckpointModel.vmAdd();
  46. e.CheckpointModelBase.vmAdd();
  47. !e.CheckpointModelLevel && e.CheckpointModelLevel.vmAdd();
  48. // 添加关卡到场景
  49. e.load(oops.game.root, v3(0, 0, 0), () => {
  50. this.createGrid(e, gridRowCount, gridColCount)
  51. if (peopleCount) { // 自动生成
  52. e.CheckpointModel.peopleCount = peopleCount
  53. const count = Math.ceil(peopleCount / 3)
  54. const colorCount = this.distributePeopleToColorsByArray(peopleCount, levelColor)
  55. const { gridPositions, gridColors, subwayPositions, subwayColors, subwayOrientations, obstaclePositions } = this.distributeToGridAndSubwayWithOptimizedPlacement(gridRowCount, gridColCount, colorCount, levelColor, 18)
  56. this.createObstacle(e, obstaclePositions)
  57. this.createMan(e, gridPositions, gridColors, levelColor)
  58. this.createSubway(e, subwayPositions, subwayOrientations, subwayColors, levelColor)
  59. this.createStation(e, stationCount)
  60. // const vColor = e.CheckpointModel.puppets.map(v=>levelColor.findIndex((c)=>c===v.PuppetModel?.color)+1)
  61. this.createVehicle(e, count, [], colorCount, levelColor)
  62. } else { // 依据配置生成
  63. this.createObstacle(e, obstaclePosition)
  64. this.createSubway(e, subwayPosition, subwayDir, subwayInfo, levelColor)
  65. this.createStation(e, stationCount)
  66. let subwayPeople = 0
  67. let flatSubwayArr = []
  68. if (subwayInfo) {
  69. flatSubwayArr = subwayInfo.flat()
  70. subwayPeople = flatSubwayArr.length
  71. }
  72. const colorCount = {}
  73. const colorArr = levelColor as number[]
  74. let newPeoplePosition = []
  75. if (peoplePosition && peoplePosition.length > 0) {
  76. newPeoplePosition = [...peoplePosition]
  77. } else {
  78. e.CheckpointModel.cells?.forEach((v, xIndex) => {
  79. v?.forEach((val, yIndex) => {
  80. if (val == null)
  81. newPeoplePosition.push([xIndex + 1, yIndex + 1])
  82. })
  83. })
  84. }
  85. if (peopleColor) {
  86. e.CheckpointModel.peopleCount = peopleColor.length + subwayPeople
  87. const count = Math.ceil((peopleColor.length + subwayPeople) / 3)
  88. colorArr.forEach((val, index) => {
  89. if (colorCount[val] == null) {
  90. colorCount[val] = 0
  91. }
  92. colorCount[val] = peopleColor.filter(v => v === index + 1).length + flatSubwayArr.filter(v => v === index + 1).length
  93. })
  94. this.createMan(e, newPeoplePosition, peopleColor, levelColor)
  95. this.createVehicle(e, count, vehicleColor, colorCount, levelColor)
  96. } else {
  97. e.CheckpointModel.peopleCount = (newPeoplePosition.length + subwayPeople) - (newPeoplePosition.length + subwayPeople) % 3
  98. const count = Math.ceil((e.CheckpointModel.peopleCount) / 3)
  99. colorArr.forEach((val, index) => {
  100. if (colorCount[val] == null) {
  101. colorCount[val] = 0
  102. }
  103. colorCount[val] = flatSubwayArr.filter(v => v === index + 1).length
  104. })
  105. Object.entries(colorCount).forEach(([color, count]) => {
  106. const remainCount = (count as number) % 3
  107. if (remainCount !== 0) {
  108. const needCount = 3 - remainCount
  109. if (newPeoplePosition.length < needCount) {
  110. console.error('人物位置数量无法支撑地铁中人物颜色为3的倍数')
  111. } else {
  112. for (let index = 0; index < needCount; index++) {
  113. const randIdx = Math.floor(Math.random() * newPeoplePosition.length);
  114. const pos = newPeoplePosition[randIdx]
  115. this.createSingleMan(e, pos, color)
  116. colorCount[color] += 1
  117. newPeoplePosition.splice(randIdx, 1)
  118. }
  119. }
  120. }
  121. // console.log(color, count);
  122. });
  123. const newColorCount = this.distributePeopleToColorsByArray(newPeoplePosition.length, levelColor)
  124. this.distributeToGrid(e, newPeoplePosition, newColorCount, levelColor)
  125. // this.createMan(e, peoplePosition, peopleColor, levelColor)
  126. // 合并两个colorCount对象
  127. let mergedColorCount = { ...colorCount };
  128. Object.keys(newColorCount).forEach(color => {
  129. if (mergedColorCount[color]) {
  130. // 如果color在mergedColorCount中已存在,则累加其值
  131. mergedColorCount[color] += newColorCount[color];
  132. } else {
  133. // 如果color在mergedColorCount中不存在,则直接添加
  134. mergedColorCount[color] = newColorCount[color];
  135. }
  136. });
  137. this.createVehicle(e, count, vehicleColor, mergedColorCount, levelColor)
  138. }
  139. this.fillEmptyMapInfo(e)
  140. }
  141. e.add(CheckpointPathTriggerComp)
  142. e.add(VehicleOperationComp)
  143. e.remove(InitCheckpointComp)
  144. // 关闭加载界面
  145. oops.gui.remove(UIID.Loading);
  146. });
  147. oops.gui.open(UIID.Game)
  148. if (e.CheckpointModelLevel.vm.lv === 1) { // 一级新手引导
  149. oops.gui.open(UIID.Guide)
  150. }
  151. }
  152. resetCheckpoint(e: Checkpoint) {
  153. e.remove(CheckpointViewComp);
  154. e.add(CheckpointModelComp, true)
  155. e.add(CheckpointModelBaseComp, true)
  156. // e.add(CheckpointModelLevelComp, true)
  157. e.children.forEach(child => {
  158. e.removeChild(child);
  159. child.destroy();
  160. });
  161. }
  162. distributePeopleToColorsByArray(totalPeople: number, colors: string[]) {
  163. // 验证输入
  164. if (totalPeople % 3 !== 0) {
  165. console.error('配置自动生成生成不是3的倍数,将去除余数')
  166. }
  167. const adapTotalPeople = totalPeople - totalPeople % 3
  168. const colorCount = colors.length;
  169. let baseDistribution = Math.floor(adapTotalPeople / colorCount);
  170. let remainder = adapTotalPeople % colorCount;
  171. // 确保基础分配是3的倍数
  172. if (baseDistribution % 3 !== 0) {
  173. baseDistribution -= baseDistribution % 3;
  174. remainder += adapTotalPeople - (baseDistribution * colorCount);
  175. }
  176. // 初始化颜色分配对象
  177. const colorDistribution = colors.reduce((acc, color) => {
  178. acc[color] = baseDistribution;
  179. return acc;
  180. }, {});
  181. // 处理余数,尽可能平均分配
  182. let index = 0;
  183. while (remainder > 0) {
  184. colorDistribution[colors[index]] += 3; // 每次增加3人以保持总数为3的倍数
  185. remainder -= 3;
  186. index = (index + 1) % colorCount; // 环形处理颜色索引
  187. }
  188. return colorDistribution;
  189. }
  190. distributeToGrid(e: Checkpoint, position: [x: number, y: number][], colorDistribution: any, colors: string[]) {
  191. // 创建颜色池
  192. let colorPool: number[] = [];
  193. colors.forEach((color, index) => {
  194. for (let i = 0; i < colorDistribution[color]; i++) {
  195. colorPool.push(index + 1);
  196. }
  197. });
  198. const randColorPool = this.shuffleArray(colorPool)
  199. randColorPool.forEach((colorIndex) => {
  200. // let people = colorDistribution[colors[colorIndex-1]];
  201. if (position.length > 0) {
  202. let randomIndex = Math.floor(Math.random() * position.length);
  203. const pos = position[randomIndex];
  204. this.createSingleMan(e, pos, colors[colorIndex - 1])
  205. position.splice(randomIndex, 1);
  206. }
  207. })
  208. }
  209. distributeToGridAndSubwayWithOptimizedPlacement(row: number, col: number, colorDistribution: any, colors: string[], subwayCapacity = 18) {
  210. const grid = Array.from({ length: row }, () => Array(col).fill(null));
  211. let freePositions = [];
  212. // let freePositionsCopy = [];
  213. const obstacleCount = Math.floor(Math.random() * 8); // 随机生成个数
  214. for (let i = 0; i < row; i++) {
  215. for (let j = 0; j < col; j++) {
  216. freePositions.push([i, j]);
  217. // freePositionsCopy.push([i, j]);
  218. }
  219. }
  220. const gridColors: number[] = []
  221. const gridPositions: [x: number, y: number][] = []
  222. // const obstaclePositions: [x: number, y: number][] = []
  223. const subwayPositions: [x: number, y: number][] = [];
  224. const subwayColors: number[][] = [];
  225. const subwayOrientations: number[] = [];
  226. const cellCount = row * col
  227. // 打乱freePositions数组
  228. this.shuffleArray(freePositions);
  229. // this.shuffleArray(freePositions); // 再洗一次,洗乱点
  230. // 从打乱后的数组中选择前 obstacleCount 个位置为障碍物位置
  231. const obstaclePositions: [x: number, y: number][] = freePositions.slice(0, obstacleCount);
  232. // 若需要,从 freePositions 中移除这些障碍物位置
  233. freePositions = freePositions.slice(obstacleCount);
  234. obstaclePositions.forEach(([x, y]) => {
  235. grid[x][y] = 'obstacle'
  236. })
  237. let freePositionsCopy = [...freePositions];
  238. // 创建颜色池
  239. let colorPool: number[] = [];
  240. colors.forEach((color, index) => {
  241. for (let i = 0; i < colorDistribution[color]; i++) {
  242. colorPool.push(index + 1);
  243. }
  244. });
  245. const getSubwayOrientation = () => Math.random() < 0.5 ? SubwayEnum.LEFT : SubwayEnum.RIGHT;
  246. // // 随机选择颜色函数
  247. // const selectRandomColor = () => {
  248. // if (colorPool.length === 0) return null;
  249. // let index = Math.floor(Math.random() * colorPool.length);
  250. // return colorPool.splice(index, 1)[0] as number; // 从颜色池中移除并返回选中的颜色
  251. // };
  252. const randColorPool = this.shuffleArray(colorPool)
  253. randColorPool.forEach((colorIndex) => {
  254. // let people = colorDistribution[colors[colorIndex-1]];
  255. if (freePositions.length > 0) {
  256. // let randomIndex = Math.floor(Math.random() * freePositions.length);
  257. // let [x, y] = freePositions[randomIndex];
  258. let [x, y] = freePositions.shift();
  259. grid[x][y] = colorIndex;
  260. gridColors.push(colorIndex)
  261. gridPositions.push([x, y])
  262. // freePositions.splice(randomIndex, 1);
  263. } else {
  264. if (!subwayColors[subwayColors.length - 1] || subwayColors[subwayColors.length - 1].length >= subwayCapacity) {
  265. const orientation = getSubwayOrientation();
  266. const filteredPositions = freePositionsCopy.filter(([x, y]) =>
  267. ((orientation === SubwayEnum.LEFT && y > 0) || (orientation === SubwayEnum.RIGHT && y < col - 1)) && grid[x][y] !== 'Subway' && grid[x][y] !== 'obstacle' &&
  268. ((orientation === SubwayEnum.RIGHT && grid[x][y + 1] !== 'Subway' && grid[x][y + 1] !== 'obstacle') || (orientation === SubwayEnum.LEFT && grid[x][y - 1] !== 'Subway' && grid[x][y - 1] !== 'obstacle')));
  269. if (filteredPositions.length > 0) {
  270. const index = Math.floor(Math.random() * filteredPositions.length);
  271. const [subwayX, subwayY] = filteredPositions[index];
  272. // let [subwayX, subwayY] = filteredPositions.shift();
  273. const gridColor = grid[subwayX][subwayY]
  274. subwayPositions.push([subwayX, subwayY]);
  275. const existIndex = gridPositions.findIndex(val => {
  276. const [x, y] = val
  277. return x === subwayX && y === subwayY
  278. })
  279. if (existIndex > -1) {
  280. gridPositions.splice(existIndex, 1)
  281. gridColors.splice(existIndex, 1)
  282. }
  283. subwayColors.push([gridColor, colorIndex]); // 新地铁的颜色
  284. subwayOrientations.push(orientation);
  285. grid[subwayX][subwayY] = 'Subway';
  286. freePositionsCopy.splice(index, 1);
  287. }
  288. } else {
  289. subwayColors[subwayColors.length - 1].push(colorIndex); // 添加到最后一个地铁的颜色
  290. }
  291. }
  292. })
  293. return {
  294. gridPositions: gridPositions.map(([x, y]) => [x + 1, y + 1]) as [x: number, y: number][],
  295. gridColors,
  296. subwayPositions: subwayPositions.map(([x, y]) => [x + 1, y + 1]) as [x: number, y: number][],
  297. subwayColors,
  298. subwayOrientations,
  299. obstaclePositions:obstaclePositions.map(([x, y]) => [x + 1, y + 1]) as [x: number, y: number][],
  300. };
  301. }
  302. // 洗牌算法打乱颜色
  303. shuffleArray(array) {
  304. for (let i = array.length - 1; i > 0; i--) {
  305. // 生成从 0 到 i 的随机数
  306. const j = Math.floor(Math.random() * (i + 1));
  307. // 交换元素 array[i] 和 array[j]
  308. [array[i], array[j]] = [array[j], array[i]];
  309. }
  310. return array;
  311. }
  312. // 生成棋盘相关
  313. createGrid(e: Checkpoint, row: number, col: number) {
  314. const checkpoint_root = e.get(CheckpointViewComp).node
  315. const checkpoint_model = e.get(CheckpointModelComp)
  316. checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  317. checkpoint_model.cells = Array.from({ length: row }, () => new Array(col).fill(null));
  318. checkpoint_model.path_grid = Array.from({ length: row }, () => new Array(col).fill(null));
  319. const width = 0.442;
  320. const gap = 0.025;
  321. const start_point = row % 2 === 0 ? v3(-(row / 2 * (width + gap) - gap / 2) + 0.08, 0, 2.7) : v3(-(Math.floor(row / 2) * (width + gap) + width / 2), 0, 2.7)
  322. for (let index = 0; index < row; index++) {
  323. for (let j = 0; j < col; j++) {
  324. const gridEnt = ecs.getEntity<Grid>(Grid);
  325. // 添加关卡到场景
  326. const pos = v3(start_point.x + j * (width + gap), 0, start_point.z + index * (width + gap))
  327. gridEnt.load(checkpoint_root, pos);
  328. e.addChild(gridEnt)
  329. checkpoint_model.grids[index][j] = gridEnt
  330. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  331. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  332. // const obstacleModel = obstacle.get(ObstacleModelComp)
  333. // obstacleModel.type = fill
  334. // obstacle.load(checkpoint_root, pos);
  335. // checkpoint_model.cells[index][j] = obstacle
  336. // checkpoint_model.path_grid[index][j] = {
  337. // x: index,
  338. // y: j,
  339. // fill: fill,
  340. // pos: pos
  341. // }
  342. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  343. // const puppet = ecs.getEntity<Puppet>(Puppet)
  344. // const puppetModel = puppet.get(PuppetModelComp)
  345. // puppetModel.color = fill
  346. // puppetModel.x = index
  347. // puppetModel.y = j
  348. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  349. // checkpoint_model.cells[index][j] = puppet
  350. // checkpoint_model.path_grid[index][j] = {
  351. // x: index,
  352. // y: j,
  353. // fill: fill,
  354. // pos: pos
  355. // }
  356. // const pathComp = puppet.add(PathFindComp)
  357. // pathComp.x = index
  358. // pathComp.y = j
  359. // } else { // 空格
  360. // checkpoint_model.path_grid[index][j] = {
  361. // x: index,
  362. // y: j,
  363. // fill: null,
  364. // pos: pos
  365. // }
  366. // }
  367. }
  368. }
  369. }
  370. // 生成人物
  371. createMan(e: Checkpoint, position: [x: number, y: number][], color: number[], colorArr: string[]) {
  372. const checkpoint_root = e.get(CheckpointViewComp).node
  373. const checkpoint_model = e.get(CheckpointModelComp)
  374. position && position.forEach((val, index) => {
  375. const [x, y] = val
  376. const xIndex = x - 1
  377. const yIndex = y - 1
  378. const puppet = ecs.getEntity<Puppet>(Puppet)
  379. const puppetModel = puppet.get(PuppetModelComp)
  380. const fillColor = colorArr[color[index] - 1]
  381. puppetModel.color = fillColor
  382. puppetModel.x = xIndex
  383. puppetModel.y = yIndex
  384. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  385. puppet.load(checkpoint_root, fillColor, pos, smc.initialize.account.AccountModel.skin);
  386. checkpoint_model.cells[xIndex][yIndex] = puppet
  387. checkpoint_model.path_grid[xIndex][yIndex] = {
  388. x: xIndex,
  389. y: yIndex,
  390. fill: fillColor,
  391. pos: pos
  392. }
  393. const pathComp = puppet.add(PathFindComp)
  394. pathComp.x = xIndex
  395. pathComp.y = yIndex
  396. })
  397. }
  398. fillEmptyMapInfo(e: Checkpoint) {
  399. const checkpoint_model = e.CheckpointModel
  400. checkpoint_model.path_grid?.forEach((v, xIndex) => {
  401. v.forEach((val, yIndex) => {
  402. if (val == null) {
  403. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  404. checkpoint_model.path_grid[xIndex][yIndex] = {
  405. x: xIndex,
  406. y: yIndex,
  407. fill: null,
  408. pos: pos
  409. }
  410. }
  411. })
  412. })
  413. }
  414. // 生成单个人物
  415. createSingleMan(e: Checkpoint, position: [x: number, y: number], color: string) {
  416. const checkpoint_root = e.get(CheckpointViewComp).node
  417. const checkpoint_model = e.get(CheckpointModelComp)
  418. const [x, y] = position
  419. const xIndex = x - 1
  420. const yIndex = y - 1
  421. const puppet = ecs.getEntity<Puppet>(Puppet)
  422. const puppetModel = puppet.get(PuppetModelComp)
  423. const fillColor = color
  424. puppetModel.color = fillColor
  425. puppetModel.x = xIndex
  426. puppetModel.y = yIndex
  427. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  428. puppet.load(checkpoint_root, fillColor, pos, smc.initialize.account.AccountModel.skin);
  429. checkpoint_model.cells[xIndex][yIndex] = puppet
  430. checkpoint_model.path_grid[xIndex][yIndex] = {
  431. x: xIndex,
  432. y: yIndex,
  433. fill: fillColor,
  434. pos: pos
  435. }
  436. const pathComp = puppet.add(PathFindComp)
  437. pathComp.x = xIndex
  438. pathComp.y = yIndex
  439. }
  440. // 生成障碍物
  441. createObstacle(e: Checkpoint, position: [x: number, y: number][]) {
  442. const checkpoint_root = e.get(CheckpointViewComp).node
  443. const checkpoint_model = e.get(CheckpointModelComp)
  444. position && position.forEach((val, index) => {
  445. const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  446. const [x, y] = val
  447. const xIndex = x - 1
  448. const yIndex = y - 1
  449. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  450. obstacle.load(checkpoint_root, pos);
  451. checkpoint_model.cells[xIndex][yIndex] = obstacle
  452. checkpoint_model.path_grid[xIndex][yIndex] = {
  453. x: xIndex,
  454. y: yIndex,
  455. fill: 'obstacle',
  456. pos: pos
  457. }
  458. })
  459. }
  460. // 生成地铁
  461. createSubway(e: Checkpoint, position: [x: number, y: number][], dir: number[], info: number[][], colorArr: string[]) {
  462. const checkpoint_root = e.get(CheckpointViewComp).node
  463. const checkpoint_model = e.get(CheckpointModelComp)
  464. position && position.forEach((val, index) => {
  465. const [x, y] = val
  466. const xIndex = x - 1
  467. const yIndex = y - 1
  468. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  469. const d = dir[index]
  470. const subway = ecs.getEntity<Subway>(Subway)
  471. const subwayModel = subway.SubwayModel
  472. subwayModel.colorArr = info[index].map(v => colorArr[v - 1])
  473. subwayModel.type = d
  474. subwayModel.x = xIndex
  475. subwayModel.y = yIndex
  476. subway.load(checkpoint_root, pos, d);
  477. checkpoint_model.cells[xIndex][yIndex] = subway
  478. checkpoint_model.path_grid[xIndex][yIndex] = {
  479. x: xIndex,
  480. y: yIndex,
  481. fill: 'subway',
  482. pos: pos
  483. }
  484. })
  485. }
  486. // 生成站台
  487. createStation(e: Checkpoint, count: number) {
  488. const checkpoint_root = e.get(CheckpointViewComp).node
  489. const checkpoint_model = e.get(CheckpointModelComp)
  490. const start_point = v3(-1.2, 0, 1.2)
  491. for (let index = 0; index < count; index++) {
  492. const station = ecs.getEntity<Station>(Station);
  493. // 添加关卡到场景
  494. const h_index = index % 5
  495. // const v_index = Math.floor(index / 5)
  496. const v_index = checkpoint_model.stations.length >= 5 ? 1 : 0
  497. station.load(checkpoint_root, v3(start_point.x + h_index * 0.5, 0, start_point.z + v_index * 0.5));
  498. e.addChild(station)
  499. checkpoint_model.stations.push(station)
  500. }
  501. }
  502. // // 生成交通工具
  503. // createVehicleByReachColor(e: Checkpoint, count: number, pcolor: number[], colorCount: any, colors: string[]) {
  504. // const copyColorCount = { ...colorCount }
  505. // const checkpoint_root = e.CheckpointView.node
  506. // const checkpoint_model = e.CheckpointModel
  507. // const availablePositions = Array.from({ length: count }, (_, i) => i)
  508. // checkpoint_model.vehicles = Array(count).fill(null)
  509. // const start_point = v3(-6, 0, 0)
  510. // pcolor?.forEach((v, i) => {
  511. // const color = colors[pcolor[i] - 1]
  512. // if (copyColorCount[color] > 0) {
  513. // const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  514. // availablePositions.shift()
  515. // copyColorCount[color] -= 3;
  516. // // 添加车到场景
  517. // vehicle.VehicleModel.color = color
  518. // const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  519. // vehicle.load(checkpoint_root, color, start_point, vehicleType);
  520. // e.addChild(vehicle)
  521. // checkpoint_model.vehicles[i] = vehicle
  522. // }
  523. // })
  524. // while (availablePositions.length > 0) {
  525. // let randomIndex = Math.floor(Math.random() * availablePositions.length);
  526. // let colorIndex = Math.floor(Math.random() * colors.length);
  527. // let color = colors[colorIndex];
  528. // if (copyColorCount[color] > 0) {
  529. // // if (randomIndex < pcolor.length) {
  530. // // availablePositions.splice(randomIndex, 1);
  531. // // }
  532. // const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  533. // let index = availablePositions.splice(randomIndex, 1)[0];
  534. // copyColorCount[color] -= 3;
  535. // // 添加车到场景
  536. // vehicle.VehicleModel.color = color
  537. // const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  538. // vehicle.load(checkpoint_root, color, start_point, vehicleType);
  539. // e.addChild(vehicle)
  540. // checkpoint_model.vehicles[index] = vehicle
  541. // }
  542. // }
  543. // }
  544. // 生成交通工具
  545. createVehicle(e: Checkpoint, count: number, pcolor: number[], colorCount: any, colors: string[]) {
  546. const copyColorCount = { ...colorCount }
  547. const checkpoint_root = e.CheckpointView.node
  548. const checkpoint_model = e.CheckpointModel
  549. const availablePositions = Array.from({ length: count }, (_, i) => i)
  550. checkpoint_model.vehicles = Array(count).fill(null)
  551. const start_point = v3(-6, 0, 0)
  552. pcolor?.forEach((v, i) => {
  553. const color = colors[pcolor[i] - 1]
  554. if (copyColorCount[color] > 0) {
  555. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  556. availablePositions.shift()
  557. copyColorCount[color] -= 3;
  558. // 添加车到场景
  559. vehicle.VehicleModel.color = color
  560. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  561. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  562. e.addChild(vehicle)
  563. checkpoint_model.vehicles[i] = vehicle
  564. }
  565. })
  566. while (availablePositions.length > 0) {
  567. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  568. let colorIndex = Math.floor(Math.random() * colors.length);
  569. let color = colors[colorIndex];
  570. if (copyColorCount[color] > 0) {
  571. // if (randomIndex < pcolor.length) {
  572. // availablePositions.splice(randomIndex, 1);
  573. // }
  574. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  575. let index = availablePositions.splice(randomIndex, 1)[0];
  576. copyColorCount[color] -= 3;
  577. // 添加车到场景
  578. vehicle.VehicleModel.color = color
  579. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  580. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  581. e.addChild(vehicle)
  582. checkpoint_model.vehicles[index] = vehicle
  583. }
  584. }
  585. // for (let index = 0; index < count; index++) {
  586. // const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  587. // const vehicleModel = vehicle.get(VehicleModelComp)
  588. // if (index < color.length) {
  589. // const v_color = colors[color[index] - 1]
  590. // vehicleModel.color = v_color
  591. // colorCount[v_color] = colorCount[v_color] - 1
  592. // } else {
  593. // const v_color = colors[index % 3]
  594. // vehicleModel.color
  595. // }
  596. // // 添加车到场景
  597. // const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  598. // vehicle.load(checkpoint_root, vehicleModel.color, start_point, vehicleType);
  599. // e.addChild(vehicle)
  600. // checkpoint_model.vehicles.push(vehicle)
  601. // }
  602. }
  603. // // 生成棋盘相关
  604. // createGrid(e: Checkpoint, row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  605. // const checkpoint_root = e.get(CheckpointViewComp).node
  606. // const checkpoint_model = e.get(CheckpointModelComp)
  607. // const grids = this.generateGridWithEmptySpaces(row, col, colors, obstacles, peopleCount, obstacleCount)
  608. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  609. // checkpoint_model.cells = Array.from({ length: row }, () => new Array(col).fill(null));
  610. // checkpoint_model.path_grid = Array.from({ length: row }, () => new Array(col).fill(null));
  611. // const start_point = v3(-1.9, 0, 2.7)
  612. // for (let index = 0; index < grids.length; index++) {
  613. // for (let j = 0; j < grids[index].length; j++) {
  614. // const gridEnt = ecs.getEntity<Grid>(Grid);
  615. // const gridModel = gridEnt.get(GridModelComp)
  616. // // 添加关卡到场景
  617. // const fill = grids[index][j]
  618. // gridModel.color = fill
  619. // const pos = v3(start_point.x + j * 0.5, 0, start_point.z + index * 0.5)
  620. // gridEnt.load(checkpoint_root, pos);
  621. // e.addChild(gridEnt)
  622. // checkpoint_model.grids[index][j] = gridEnt
  623. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  624. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  625. // const obstacleModel = obstacle.get(ObstacleModelComp)
  626. // obstacleModel.type = fill
  627. // obstacle.load(checkpoint_root, pos);
  628. // checkpoint_model.cells[index][j] = obstacle
  629. // checkpoint_model.path_grid[index][j] = {
  630. // x: index,
  631. // y: j,
  632. // fill: fill,
  633. // pos: pos
  634. // }
  635. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  636. // const puppet = ecs.getEntity<Puppet>(Puppet)
  637. // const puppetModel = puppet.get(PuppetModelComp)
  638. // puppetModel.color = fill
  639. // puppetModel.x = index
  640. // puppetModel.y = j
  641. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  642. // checkpoint_model.cells[index][j] = puppet
  643. // checkpoint_model.path_grid[index][j] = {
  644. // x: index,
  645. // y: j,
  646. // fill: fill,
  647. // pos: pos
  648. // }
  649. // const pathComp = puppet.add(PathFindComp)
  650. // pathComp.x = index
  651. // pathComp.y = j
  652. // } else { // 空格
  653. // checkpoint_model.path_grid[index][j] = {
  654. // x: index,
  655. // y: j,
  656. // fill: null,
  657. // pos: pos
  658. // }
  659. // }
  660. // }
  661. // }
  662. // }
  663. // // 生成棋盘格
  664. // createGrid(e: Checkpoint, row: number, col: number) {
  665. // const checkpoint_root = e.get(CheckpointViewComp).node
  666. // const checkpoint_model = e.get(CheckpointModelComp)
  667. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  668. // const start_point = v3(-1.706, 0, -1.718)
  669. // for (let index = 0; index < row; index++) {
  670. // for (let j = 0; j < col; j++) {
  671. // const grid = ecs.getEntity<Grid>(Grid);
  672. // // 添加关卡到场景
  673. // grid.load(checkpoint_root, v3(start_point.x + index * 0.6, 0, start_point.z + j * 0.6));
  674. // e.addChild(grid)
  675. // checkpoint_model.grids[index][j] = grid
  676. // }
  677. // }
  678. // }
  679. calcMaxCount(row: number, col: number, peopleCount: number) {
  680. const totalCells = row * col;
  681. let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  682. return Math.min(maxCount / 3, peopleCount * 3); // 分配三分之一
  683. }
  684. generateGridWithEmptySpaces(row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  685. let grid = Array.from({ length: row }, () => new Array(col).fill(null));
  686. // 初始化颜色计数
  687. let counts = {};
  688. colors.forEach(color => {
  689. counts[color] = this.calcMaxCount(row, col, peopleCount); // 分配三分之一
  690. });
  691. // 创建所有可能的格子位置数组
  692. let availablePositions = [];
  693. for (let i = 0; i < row; i++) {
  694. for (let j = 0; j < col; j++) {
  695. availablePositions.push([i, j]);
  696. }
  697. }
  698. let obstacleNum = obstacleCount
  699. // 随机分配颜色到网格中
  700. while (availablePositions.length > 0) {
  701. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  702. let position = availablePositions.splice(randomIndex, 1)[0];
  703. let x = position[0];
  704. let y = position[1];
  705. let colorIndex = Math.floor(Math.random() * colors.length);
  706. let color = colors[colorIndex];
  707. if (counts[color] > 0) {
  708. grid[x][y] = color;
  709. counts[color]--;
  710. } else if (obstacleNum > 0) {
  711. grid[x][y] = obstacles[Math.floor(Math.random() * obstacles.length)]
  712. obstacleNum--
  713. }
  714. }
  715. return grid;
  716. }
  717. // generateOptimizedGrid(colors:string[]) {
  718. // const gridSize = 7;
  719. // const totalCells = gridSize * gridSize;
  720. // // const colors = ['红色', '蓝色', '绿色'];
  721. // let grid = Array(gridSize).fill().map(() => Array(gridSize).fill(''));
  722. // // 初始化每种颜色的人数
  723. // let counts = { '红色': 0, '蓝色': 0, '绿色': 0 };
  724. // // 首先分配每种颜色的人数,使其尽可能接近总数且是 3 的倍数
  725. // for (let color of colors) {
  726. // let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  727. // counts[color] = maxCount / 3; // 分配三分之一
  728. // }
  729. // // 在剩余的空格中随机分配颜色或保持为空
  730. // let remainingCells = totalCells - 3 * Math.floor((totalCells - 1) / 3);
  731. // let colorIndices = colors.map((_, index) => index);
  732. // while (remainingCells > 0) {
  733. // let randomIndex = Math.floor(Math.random() * colorIndices.length);
  734. // let color = colors[colorIndices[randomIndex]];
  735. // counts[color]++;
  736. // remainingCells--;
  737. // }
  738. // // 将颜色分配到网格中
  739. // let flatGrid = grid.flat();
  740. // colors.forEach(color => {
  741. // for (let i = 0; i < counts[color]; i++) {
  742. // let pos;
  743. // do {
  744. // pos = Math.floor(Math.random() * flatGrid.length);
  745. // } while (flatGrid[pos] !== '');
  746. // flatGrid[pos] = color;
  747. // }
  748. // });
  749. // // 重新构建二维网格
  750. // for (let i = 0; i < flatGrid.length; i++) {
  751. // grid[Math.floor(i / gridSize)][i % gridSize] = flatGrid[i];
  752. // }
  753. // return grid;
  754. // }
  755. }