InitCheckpoint.ts 34 KB

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