InitCheckpoint.ts 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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&&peoplePosition.length>0) {
  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 width = 0.442;
  302. const gap = 0.025;
  303. 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)
  304. for (let index = 0; index < row; index++) {
  305. for (let j = 0; j < col; j++) {
  306. const gridEnt = ecs.getEntity<Grid>(Grid);
  307. // 添加关卡到场景
  308. const pos = v3(start_point.x + j * (width+gap), 0, start_point.z + index * (width+gap))
  309. gridEnt.load(checkpoint_root, pos);
  310. e.addChild(gridEnt)
  311. checkpoint_model.grids[index][j] = gridEnt
  312. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  313. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  314. // const obstacleModel = obstacle.get(ObstacleModelComp)
  315. // obstacleModel.type = fill
  316. // obstacle.load(checkpoint_root, pos);
  317. // checkpoint_model.cells[index][j] = obstacle
  318. // checkpoint_model.path_grid[index][j] = {
  319. // x: index,
  320. // y: j,
  321. // fill: fill,
  322. // pos: pos
  323. // }
  324. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  325. // const puppet = ecs.getEntity<Puppet>(Puppet)
  326. // const puppetModel = puppet.get(PuppetModelComp)
  327. // puppetModel.color = fill
  328. // puppetModel.x = index
  329. // puppetModel.y = j
  330. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  331. // checkpoint_model.cells[index][j] = puppet
  332. // checkpoint_model.path_grid[index][j] = {
  333. // x: index,
  334. // y: j,
  335. // fill: fill,
  336. // pos: pos
  337. // }
  338. // const pathComp = puppet.add(PathFindComp)
  339. // pathComp.x = index
  340. // pathComp.y = j
  341. // } else { // 空格
  342. // checkpoint_model.path_grid[index][j] = {
  343. // x: index,
  344. // y: j,
  345. // fill: null,
  346. // pos: pos
  347. // }
  348. // }
  349. }
  350. }
  351. }
  352. // 生成人物
  353. createMan(e: Checkpoint, position: [x: number, y: number][], color: number[], colorArr: string[]) {
  354. const checkpoint_root = e.get(CheckpointViewComp).node
  355. const checkpoint_model = e.get(CheckpointModelComp)
  356. position && position.forEach((val, index) => {
  357. const [x, y] = val
  358. const xIndex = x - 1
  359. const yIndex = y - 1
  360. const puppet = ecs.getEntity<Puppet>(Puppet)
  361. const puppetModel = puppet.get(PuppetModelComp)
  362. const fillColor = colorArr[color[index] - 1]
  363. puppetModel.color = fillColor
  364. puppetModel.x = xIndex
  365. puppetModel.y = yIndex
  366. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  367. puppet.load(checkpoint_root, fillColor, pos, smc.initialize.account.AccountModel.skin);
  368. checkpoint_model.cells[xIndex][yIndex] = puppet
  369. checkpoint_model.path_grid[xIndex][yIndex] = {
  370. x: xIndex,
  371. y: yIndex,
  372. fill: fillColor,
  373. pos: pos
  374. }
  375. const pathComp = puppet.add(PathFindComp)
  376. pathComp.x = xIndex
  377. pathComp.y = yIndex
  378. })
  379. }
  380. fillEmptyMapInfo(e: Checkpoint) {
  381. const checkpoint_model = e.CheckpointModel
  382. checkpoint_model.path_grid?.forEach((v, xIndex) => {
  383. v.forEach((val, yIndex) => {
  384. if (val == null) {
  385. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  386. checkpoint_model.path_grid[xIndex][yIndex] = {
  387. x: xIndex,
  388. y: yIndex,
  389. fill: null,
  390. pos: pos
  391. }
  392. }
  393. })
  394. })
  395. }
  396. // 生成单个人物
  397. createSingleMan(e: Checkpoint, position: [x: number, y: number], color: string) {
  398. const checkpoint_root = e.get(CheckpointViewComp).node
  399. const checkpoint_model = e.get(CheckpointModelComp)
  400. const [x, y] = position
  401. const xIndex = x - 1
  402. const yIndex = y - 1
  403. const puppet = ecs.getEntity<Puppet>(Puppet)
  404. const puppetModel = puppet.get(PuppetModelComp)
  405. const fillColor = color
  406. puppetModel.color = fillColor
  407. puppetModel.x = xIndex
  408. puppetModel.y = yIndex
  409. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  410. puppet.load(checkpoint_root, fillColor, pos, smc.initialize.account.AccountModel.skin);
  411. checkpoint_model.cells[xIndex][yIndex] = puppet
  412. checkpoint_model.path_grid[xIndex][yIndex] = {
  413. x: xIndex,
  414. y: yIndex,
  415. fill: fillColor,
  416. pos: pos
  417. }
  418. const pathComp = puppet.add(PathFindComp)
  419. pathComp.x = xIndex
  420. pathComp.y = yIndex
  421. }
  422. // 生成障碍物
  423. createObstacle(e: Checkpoint, position: [x: number, y: number][]) {
  424. const checkpoint_root = e.get(CheckpointViewComp).node
  425. const checkpoint_model = e.get(CheckpointModelComp)
  426. position && position.forEach((val, index) => {
  427. const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  428. const [x, y] = val
  429. const xIndex = x - 1
  430. const yIndex = y - 1
  431. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  432. obstacle.load(checkpoint_root, pos);
  433. checkpoint_model.cells[xIndex][yIndex] = obstacle
  434. checkpoint_model.path_grid[xIndex][yIndex] = {
  435. x: xIndex,
  436. y: yIndex,
  437. fill: 'obstacle',
  438. pos: pos
  439. }
  440. })
  441. }
  442. // 生成地铁
  443. createSubway(e: Checkpoint, position: [x: number, y: number][], dir: number[], info: number[][], colorArr: string[]) {
  444. const checkpoint_root = e.get(CheckpointViewComp).node
  445. const checkpoint_model = e.get(CheckpointModelComp)
  446. position && position.forEach((val, index) => {
  447. const [x, y] = val
  448. const xIndex = x - 1
  449. const yIndex = y - 1
  450. const pos = checkpoint_model.grids[xIndex][yIndex].GridView.node.position.clone()
  451. const d = dir[index]
  452. const subway = ecs.getEntity<Subway>(Subway)
  453. const subwayModel = subway.SubwayModel
  454. subwayModel.colorArr = info[index].map(v => colorArr[v - 1])
  455. subwayModel.type = d
  456. subwayModel.x = xIndex
  457. subwayModel.y = yIndex
  458. subway.load(checkpoint_root, pos, d);
  459. checkpoint_model.cells[xIndex][yIndex] = subway
  460. checkpoint_model.path_grid[xIndex][yIndex] = {
  461. x: xIndex,
  462. y: yIndex,
  463. fill: 'subway',
  464. pos: pos
  465. }
  466. })
  467. }
  468. // 生成站台
  469. createStation(e: Checkpoint, count: number) {
  470. const checkpoint_root = e.get(CheckpointViewComp).node
  471. const checkpoint_model = e.get(CheckpointModelComp)
  472. const start_point = v3(-1.2, 0, 1.2)
  473. for (let index = 0; index < count; index++) {
  474. const station = ecs.getEntity<Station>(Station);
  475. // 添加关卡到场景
  476. const h_index = index % 5
  477. // const v_index = Math.floor(index / 5)
  478. const v_index = checkpoint_model.stations.length >= 5 ? 1 : 0
  479. station.load(checkpoint_root, v3(start_point.x + h_index * 0.5, 0, start_point.z + v_index * 0.5));
  480. e.addChild(station)
  481. checkpoint_model.stations.push(station)
  482. }
  483. }
  484. // 生成交通工具
  485. createVehicle(e: Checkpoint, count: number, pcolor: number[], colorCount: any, colors: string[]) {
  486. const copyColorCount = { ...colorCount }
  487. const checkpoint_root = e.CheckpointView.node
  488. const checkpoint_model = e.CheckpointModel
  489. const availablePositions = Array.from({ length: count }, (_, i) => i)
  490. checkpoint_model.vehicles = Array(count).fill(null)
  491. const start_point = v3(-6, 0, 0)
  492. pcolor?.forEach((v, i) => {
  493. const color = colors[pcolor[i] - 1]
  494. if (copyColorCount[color] > 0) {
  495. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  496. availablePositions.shift()
  497. copyColorCount[color] -= 3;
  498. // 添加车到场景
  499. vehicle.VehicleModel.color = color
  500. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  501. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  502. e.addChild(vehicle)
  503. checkpoint_model.vehicles[i] = vehicle
  504. }
  505. })
  506. while (availablePositions.length > 0) {
  507. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  508. let colorIndex = Math.floor(Math.random() * colors.length);
  509. let color = colors[colorIndex];
  510. if (copyColorCount[color] > 0) {
  511. // if (randomIndex < pcolor.length) {
  512. // availablePositions.splice(randomIndex, 1);
  513. // }
  514. const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  515. let index = availablePositions.splice(randomIndex, 1)[0];
  516. copyColorCount[color] -= 3;
  517. // 添加车到场景
  518. vehicle.VehicleModel.color = color
  519. const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  520. vehicle.load(checkpoint_root, color, start_point, vehicleType);
  521. e.addChild(vehicle)
  522. checkpoint_model.vehicles[index] = vehicle
  523. }
  524. }
  525. // for (let index = 0; index < count; index++) {
  526. // const vehicle = ecs.getEntity<Vehicle>(Vehicle);
  527. // const vehicleModel = vehicle.get(VehicleModelComp)
  528. // if (index < color.length) {
  529. // const v_color = colors[color[index] - 1]
  530. // vehicleModel.color = v_color
  531. // colorCount[v_color] = colorCount[v_color] - 1
  532. // } else {
  533. // const v_color = colors[index % 3]
  534. // vehicleModel.color
  535. // }
  536. // // 添加车到场景
  537. // const vehicleType = e.CheckpointModelLevel.rtluCurrent.vehicleType
  538. // vehicle.load(checkpoint_root, vehicleModel.color, start_point, vehicleType);
  539. // e.addChild(vehicle)
  540. // checkpoint_model.vehicles.push(vehicle)
  541. // }
  542. }
  543. // // 生成棋盘相关
  544. // createGrid(e: Checkpoint, row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  545. // const checkpoint_root = e.get(CheckpointViewComp).node
  546. // const checkpoint_model = e.get(CheckpointModelComp)
  547. // const grids = this.generateGridWithEmptySpaces(row, col, colors, obstacles, peopleCount, obstacleCount)
  548. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  549. // checkpoint_model.cells = Array.from({ length: row }, () => new Array(col).fill(null));
  550. // checkpoint_model.path_grid = Array.from({ length: row }, () => new Array(col).fill(null));
  551. // const start_point = v3(-1.9, 0, 2.7)
  552. // for (let index = 0; index < grids.length; index++) {
  553. // for (let j = 0; j < grids[index].length; j++) {
  554. // const gridEnt = ecs.getEntity<Grid>(Grid);
  555. // const gridModel = gridEnt.get(GridModelComp)
  556. // // 添加关卡到场景
  557. // const fill = grids[index][j]
  558. // gridModel.color = fill
  559. // const pos = v3(start_point.x + j * 0.5, 0, start_point.z + index * 0.5)
  560. // gridEnt.load(checkpoint_root, pos);
  561. // e.addChild(gridEnt)
  562. // checkpoint_model.grids[index][j] = gridEnt
  563. // if (typeof grids[index][j] === 'number') { // 生成障碍物
  564. // const obstacle = ecs.getEntity<Obstacle>(Obstacle)
  565. // const obstacleModel = obstacle.get(ObstacleModelComp)
  566. // obstacleModel.type = fill
  567. // obstacle.load(checkpoint_root, pos);
  568. // checkpoint_model.cells[index][j] = obstacle
  569. // checkpoint_model.path_grid[index][j] = {
  570. // x: index,
  571. // y: j,
  572. // fill: fill,
  573. // pos: pos
  574. // }
  575. // } else if (typeof grids[index][j] === 'string') { // 生成人物
  576. // const puppet = ecs.getEntity<Puppet>(Puppet)
  577. // const puppetModel = puppet.get(PuppetModelComp)
  578. // puppetModel.color = fill
  579. // puppetModel.x = index
  580. // puppetModel.y = j
  581. // puppet.load(checkpoint_root, fill, pos, smc.initialize.account.AccountModel.skin);
  582. // checkpoint_model.cells[index][j] = puppet
  583. // checkpoint_model.path_grid[index][j] = {
  584. // x: index,
  585. // y: j,
  586. // fill: fill,
  587. // pos: pos
  588. // }
  589. // const pathComp = puppet.add(PathFindComp)
  590. // pathComp.x = index
  591. // pathComp.y = j
  592. // } else { // 空格
  593. // checkpoint_model.path_grid[index][j] = {
  594. // x: index,
  595. // y: j,
  596. // fill: null,
  597. // pos: pos
  598. // }
  599. // }
  600. // }
  601. // }
  602. // }
  603. // // 生成棋盘格
  604. // createGrid(e: Checkpoint, row: number, col: number) {
  605. // const checkpoint_root = e.get(CheckpointViewComp).node
  606. // const checkpoint_model = e.get(CheckpointModelComp)
  607. // checkpoint_model.grids = Array.from({ length: row }, () => new Array(col).fill(null));
  608. // const start_point = v3(-1.706, 0, -1.718)
  609. // for (let index = 0; index < row; index++) {
  610. // for (let j = 0; j < col; j++) {
  611. // const grid = ecs.getEntity<Grid>(Grid);
  612. // // 添加关卡到场景
  613. // grid.load(checkpoint_root, v3(start_point.x + index * 0.6, 0, start_point.z + j * 0.6));
  614. // e.addChild(grid)
  615. // checkpoint_model.grids[index][j] = grid
  616. // }
  617. // }
  618. // }
  619. calcMaxCount(row: number, col: number, peopleCount: number) {
  620. const totalCells = row * col;
  621. let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  622. return Math.min(maxCount / 3, peopleCount * 3); // 分配三分之一
  623. }
  624. generateGridWithEmptySpaces(row: number, col: number, colors: string[], obstacles: number[], peopleCount: number, obstacleCount: number) {
  625. let grid = Array.from({ length: row }, () => new Array(col).fill(null));
  626. // 初始化颜色计数
  627. let counts = {};
  628. colors.forEach(color => {
  629. counts[color] = this.calcMaxCount(row, col, peopleCount); // 分配三分之一
  630. });
  631. // 创建所有可能的格子位置数组
  632. let availablePositions = [];
  633. for (let i = 0; i < row; i++) {
  634. for (let j = 0; j < col; j++) {
  635. availablePositions.push([i, j]);
  636. }
  637. }
  638. let obstacleNum = obstacleCount
  639. // 随机分配颜色到网格中
  640. while (availablePositions.length > 0) {
  641. let randomIndex = Math.floor(Math.random() * availablePositions.length);
  642. let position = availablePositions.splice(randomIndex, 1)[0];
  643. let x = position[0];
  644. let y = position[1];
  645. let colorIndex = Math.floor(Math.random() * colors.length);
  646. let color = colors[colorIndex];
  647. if (counts[color] > 0) {
  648. grid[x][y] = color;
  649. counts[color]--;
  650. } else if (obstacleNum > 0) {
  651. grid[x][y] = obstacles[Math.floor(Math.random() * obstacles.length)]
  652. obstacleNum--
  653. }
  654. }
  655. return grid;
  656. }
  657. // generateOptimizedGrid(colors:string[]) {
  658. // const gridSize = 7;
  659. // const totalCells = gridSize * gridSize;
  660. // // const colors = ['红色', '蓝色', '绿色'];
  661. // let grid = Array(gridSize).fill().map(() => Array(gridSize).fill(''));
  662. // // 初始化每种颜色的人数
  663. // let counts = { '红色': 0, '蓝色': 0, '绿色': 0 };
  664. // // 首先分配每种颜色的人数,使其尽可能接近总数且是 3 的倍数
  665. // for (let color of colors) {
  666. // let maxCount = Math.floor((totalCells - 1) / 3) * 3; // 最大可能的 3 的倍数
  667. // counts[color] = maxCount / 3; // 分配三分之一
  668. // }
  669. // // 在剩余的空格中随机分配颜色或保持为空
  670. // let remainingCells = totalCells - 3 * Math.floor((totalCells - 1) / 3);
  671. // let colorIndices = colors.map((_, index) => index);
  672. // while (remainingCells > 0) {
  673. // let randomIndex = Math.floor(Math.random() * colorIndices.length);
  674. // let color = colors[colorIndices[randomIndex]];
  675. // counts[color]++;
  676. // remainingCells--;
  677. // }
  678. // // 将颜色分配到网格中
  679. // let flatGrid = grid.flat();
  680. // colors.forEach(color => {
  681. // for (let i = 0; i < counts[color]; i++) {
  682. // let pos;
  683. // do {
  684. // pos = Math.floor(Math.random() * flatGrid.length);
  685. // } while (flatGrid[pos] !== '');
  686. // flatGrid[pos] = color;
  687. // }
  688. // });
  689. // // 重新构建二维网格
  690. // for (let i = 0; i < flatGrid.length; i++) {
  691. // grid[Math.floor(i / gridSize)][i % gridSize] = flatGrid[i];
  692. // }
  693. // return grid;
  694. // }
  695. }