InitCheckpoint.ts 34 KB

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