fruit.vue 52 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856
  1. <template>
  2. <div class="game-container">
  3. <div id="game"></div>
  4. <canvas ref="canvasRef" :width="clientObj.width" :height="clientObj.height"
  5. style="position:fixed;left: 0; top: 0;"></canvas>
  6. </div>
  7. </template>
  8. <script setup name="Fruit" lang="ts">
  9. import { onMounted, ref } from 'vue';
  10. import Phaser from 'phaser';
  11. import { initSpeech, speckText, playMusic, controlMusic, speckCancel, chineseNumber } from '@/utils/speech';
  12. import { useWebSocket } from '@/utils/bodyposeWs';
  13. const { proxy } = getCurrentInstance() as any;
  14. const router = useRouter();
  15. const { bodyposeWs, startDevice, checkBodypose, openBodypose, terminateBodypose, suspendBodypose, resumeBodypose, getBodyposeState, closeWS } = useWebSocket();
  16. const gameRef = ref(null); // 用于保存游戏实例的ref
  17. const canvasRef = ref(null);
  18. const data = reactive<any>({
  19. bodyposeData: {},//姿态信息
  20. bodyposeState: false,//姿态识别窗口状态
  21. parameter: {},//参数
  22. deviceInfo: {},//设备信息
  23. againNum: 0,//再次启动次数
  24. againTimer: null,//定时状态
  25. wsState: false,//WS状态
  26. clientObj: {},//浏览器对象
  27. boxes: [],//四个点坐标
  28. proportion: null,//人框和屏幕比例
  29. scaleRatio: 2.2,//素材比例
  30. });
  31. const { bodyposeData, bodyposeState, parameter, deviceInfo, againNum, againTimer, wsState, clientObj, boxes, proportion, scaleRatio } = toRefs(data);
  32. /**
  33. * 初始化
  34. */
  35. const getInit = async () => {
  36. console.log("触发姿态识别")
  37. let deviceid = localStorage.getItem('deviceid') || '';
  38. if (!deviceid) {
  39. proxy?.$modal.msgError(`请重新登录绑定设备号后使用`);
  40. return false;
  41. }
  42. bodyposeState.value = true;
  43. if (wsState.value) {
  44. proxy?.$modal.msgWarning(`操作过快,请稍后重试`);
  45. setTimeout(() => {
  46. bodyposeState.value = false;
  47. }, 1000)
  48. return false;
  49. }
  50. speckText("正在姿态识别");
  51. proxy?.$modal.msgWarning(`正在姿态识别`);
  52. bodyposeWs((e: any) => {
  53. //console.log("bodyposeWS", e)
  54. if (e?.wksid) {
  55. wsState.value = true;
  56. //获取设备信息
  57. startDevice({ deviceid: deviceid });
  58. console.log("获取设备信息")
  59. }
  60. if (e?.type == 'fe_device_init_result') {
  61. //接收设备信息并发送请求
  62. if (e?.device_info) {
  63. deviceInfo.value = e.device_info;
  64. getCheckBodypose();
  65. console.log("返回设备信息,检查是否支持姿态识别")
  66. } else {
  67. proxy?.$modal.msgError(`设备信息缺失,请重新登录绑定设备号后使用`);
  68. }
  69. }
  70. if (e?.cmd == 'check_bodyposecontroller_available') {
  71. let handcontroller_id = deviceInfo.value.handcontroller_id;
  72. if (e?.code == 0) {
  73. //查看姿态识别状态,如果不处于关闭就先关闭再重新启动(可能会APP退出然后工作站还在运行的可能性)
  74. getBodyposeState(handcontroller_id);
  75. againNum.value = 0;
  76. againTimer.value = null;
  77. clearTimeout(againTimer.value);
  78. console.log("查看姿态识别状态")
  79. } else {
  80. //尝试多次查询姿态识别状态
  81. if (againNum.value <= 2) {
  82. againTimer.value = setTimeout(() => {
  83. getCheckBodypose();
  84. }, 500)
  85. againNum.value++;
  86. } else {
  87. let msg = "";
  88. if (e.code == 102402) {
  89. msg = `多次连接失败请重试,姿态识别模块被占用`;
  90. } else {
  91. msg = `多次连接失败请重试,姿态识别模块不可用,code:${e.code}`;
  92. }
  93. proxy?.$modal.msgWarning(msg);
  94. againNum.value = 0;
  95. againTimer.value = null;
  96. clearTimeout(againTimer.value);
  97. getCloseBodypose();//直接关闭
  98. }
  99. }
  100. }
  101. if (e?.cmd == 'get_bodyposecontroller_state') {
  102. let handcontroller_id = deviceInfo.value.handcontroller_id;
  103. //state说明: 0:关闭,3:空闲,36:工作中
  104. if ([3, 36].includes(e.state)) {
  105. getCloseBodypose();
  106. proxy?.$modal.msgWarning(`请重新姿态识别`);
  107. } else {
  108. openBodypose(handcontroller_id);
  109. }
  110. }
  111. if (e?.type == 'bodyposecontroller_result') {
  112. let arr = e.data.result.keypoints;
  113. let result = [];
  114. for (let i = 0; i < arr.length; i += 3) {
  115. result.push(arr.slice(i, i + 2));
  116. }
  117. // console.log("result", result)
  118. bodyposeData.value = result;
  119. if (boxes.value.length == 0) {
  120. speckText("识别成功");
  121. proxy?.$modal.msgWarning(`识别成功`);
  122. let arr = e.data.result.boxes;
  123. boxes.value = [{ x: arr[0], y: arr[3] }, { x: arr[0], y: arr[1] }, { x: arr[2], y: arr[1] }, { x: arr[2], y: arr[3] }]
  124. proportion.value = (clientObj.value.height / (arr[3] - arr[1])).toFixed(2);
  125. }
  126. getCanvas();
  127. }
  128. if (e?.cmd == 'terminate_bodyposecontroller') {
  129. if (e?.code == 0) {
  130. closeWS();
  131. bodyposeState.value = false;
  132. }
  133. }
  134. if (e?.type == 'disconnect') {
  135. wsState.value = false;
  136. }
  137. });
  138. };
  139. /**
  140. * 查询姿态识别状态
  141. */
  142. const getCheckBodypose = () => {
  143. let handcontroller_id = deviceInfo.value.handcontroller_id;
  144. //检查是否支持姿态识别
  145. checkBodypose(handcontroller_id);
  146. };
  147. /**
  148. * 关闭姿态识别
  149. */
  150. const getCloseBodypose = () => {
  151. let handcontroller_id = deviceInfo.value.handcontroller_id;
  152. terminateBodypose(handcontroller_id);
  153. bodyposeState.value = false;
  154. speckCancel(); //停止播报
  155. setTimeout(() => {
  156. if (wsState.value) {
  157. closeWS();
  158. }
  159. }, 3000)
  160. };
  161. /**
  162. * 绘图
  163. */
  164. const getCanvas = () => {
  165. const canvas: any = canvasRef.value;
  166. const ctx = canvas.getContext('2d');
  167. // 清空整个画布
  168. ctx.clearRect(0, 0, canvas.width, canvas.height);
  169. // 保存当前状态
  170. ctx.save();
  171. function calculateOffset(a: any, b: any) {
  172. return {
  173. x: b.x - a.x,
  174. y: b.y - a.y
  175. };
  176. }
  177. const pointA = { x: clientObj.value.width / 2, y: clientObj.value.height / 2 };
  178. const pointB = { x: (boxes.value[2].x + boxes.value[0].x) / 2, y: (boxes.value[3].y + boxes.value[1].y) / 2 };
  179. const offset = calculateOffset(pointA, pointB);
  180. ctx.translate(-offset.x, -offset.y);
  181. // console.log("Canvas分辨率", clientObj.value);
  182. // console.log("人体图片四点坐标", boxes.value)
  183. // console.log("Canvas中心", pointA);
  184. // console.log("人体中心", pointB);
  185. // console.log("offset", offset)
  186. // console.log("proportion.value",proportion.value)
  187. const originalPoints = bodyposeData.value;
  188. // 计算缩放后坐标
  189. const postData = originalPoints.map((point: any) => {
  190. const newX = (point[0] - pointB.x) * proportion.value + pointB.x;
  191. const newY = (point[1] - pointB.y) * proportion.value + pointB.y;
  192. return [newX, newY];
  193. });
  194. // console.log("原始坐标:", originalPoints);
  195. // console.log("缩放后坐标:", postData);
  196. //externalMethod(postData[10][0] - offset.x, postData[10][1] - offset.y)
  197. externalRightHandMethod(postData[10][0] - offset.x, postData[10][1] - offset.y)
  198. externalLeftHandMethod(postData[9][0] - offset.x, postData[9][1] - offset.y)
  199. //绘制头部
  200. const point1 = { x: postData[4][0], y: postData[4][1] };
  201. const point2 = { x: postData[3][0], y: postData[3][1] };
  202. // 计算椭圆参数
  203. const centerX = (point1.x + point2.x) / 2; // 椭圆中心X
  204. const centerY = (point1.y + point2.y) / 2; // 椭圆中心Y
  205. const distance = Math.sqrt(
  206. Math.pow(point2.x - point1.x, 2) +
  207. Math.pow(point2.y - point1.y, 2)
  208. ); // 两个焦点之间的距离
  209. const radiusX = distance * 0.5; // 水平半径(可调整)
  210. const radiusY = distance * 0.6; // 垂直半径(可调整)
  211. // 1. 绘制填充椭圆
  212. ctx.beginPath();
  213. ctx.ellipse(centerX, centerY, radiusX, radiusY, 0, 0, Math.PI * 2);
  214. ctx.fillStyle = 'red'; // 填充颜色
  215. ctx.fill(); // 填充
  216. // 2. 绘制边框
  217. ctx.strokeStyle = 'red';
  218. ctx.lineWidth = 5;
  219. ctx.stroke();
  220. // 绘制每个点
  221. postData.forEach((point: any, index: number) => {
  222. //眼睛鼻子不显示
  223. if (![0, 1, 2].includes(index)) {
  224. const [x, y] = point;
  225. ctx.beginPath();
  226. ctx.arc(x, y, 5, 0, Math.PI * 2); // 绘制半径为5的圆点
  227. ctx.fillStyle = 'red';
  228. ctx.fill();
  229. ctx.lineWidth = 1;
  230. ctx.stroke();
  231. }
  232. });
  233. // 根据点关系连线
  234. const arr = [[10, 8], [8, 6], [6, 5], [5, 7], [7, 9], [6, 12], [5, 11], [12, 11], [12, 14], [14, 16], [11, 13], [13, 15]]
  235. arr.forEach((point: any) => {
  236. let index1 = point[0];
  237. let index2 = point[1];
  238. //连线
  239. const dian1 = { x: postData[index1][0], y: postData[index1][1] };
  240. const dian2 = { x: postData[index2][0], y: postData[index2][1] };
  241. // 绘制连线
  242. ctx.beginPath();
  243. ctx.moveTo(dian1.x, dian1.y); // 起点
  244. ctx.lineTo(dian2.x, dian2.y); // 终点
  245. ctx.strokeStyle = 'red'; // 线条颜色
  246. ctx.lineWidth = 3; // 线条宽度
  247. ctx.stroke(); // 描边
  248. });
  249. ctx.restore(); // 恢复状态
  250. };
  251. // 游戏容器和尺寸相关
  252. const width = document.documentElement.clientWidth;
  253. const height = document.documentElement.clientHeight;
  254. const wRatio = document.documentElement.clientWidth / 640;
  255. const hRatio = document.documentElement.clientHeight / 480;
  256. const gameContainer = ref(null);
  257. let game = null;
  258. // 工具类
  259. const mathTool = {
  260. init() {
  261. },
  262. // 计算延长线,p2往p1延长
  263. calcParallel(p1, p2, L) {
  264. const p = {};
  265. if (p1.x === p2.x) {
  266. if (p1.y - p2.y > 0) {
  267. p.x = p1.x;
  268. p.y = p1.y + L;
  269. } else {
  270. p.x = p1.x;
  271. p.y = p1.y - L;
  272. }
  273. } else {
  274. const k = (p2.y - p1.y) / (p2.x - p1.x);
  275. if (p2.x - p1.x < 0) {
  276. p.x = p1.x + L / Math.sqrt(1 + k * k);
  277. p.y = p1.y + L * k / Math.sqrt(1 + k * k);
  278. } else {
  279. p.x = p1.x - L / Math.sqrt(1 + k * k);
  280. p.y = p1.y - L * k / Math.sqrt(1 + k * k);
  281. }
  282. }
  283. p.x = Math.round(p.x);
  284. p.y = Math.round(p.y);
  285. return new Phaser.Math.Vector2(p.x, p.y);
  286. },
  287. // 计算垂直线,p2点开始垂直
  288. calcVertical(p1, p2, L, isLeft) {
  289. const p = {};
  290. if (p1.y === p2.y) {
  291. p.x = p2.x;
  292. if (isLeft) {
  293. if (p2.x - p1.x > 0) {
  294. p.y = p2.y - L;
  295. } else {
  296. p.y = p2.y + L;
  297. }
  298. } else {
  299. if (p2.x - p1.x > 0) {
  300. p.y = p2.y + L;
  301. } else {
  302. p.y = p2.y - L;
  303. }
  304. }
  305. } else {
  306. const k = -(p2.x - p1.x) / (p2.y - p1.y);
  307. if (isLeft) {
  308. if (p2.y - p1.y > 0) {
  309. p.x = p2.x + L / Math.sqrt(1 + k * k);
  310. p.y = p2.y + L * k / Math.sqrt(1 + k * k);
  311. } else {
  312. p.x = p2.x - L / Math.sqrt(1 + k * k);
  313. p.y = p2.y - L * k / Math.sqrt(1 + k * k);
  314. }
  315. } else {
  316. if (p2.y - p1.y > 0) {
  317. p.x = p2.x - L / Math.sqrt(1 + k * k);
  318. p.y = p2.y - L * k / Math.sqrt(1 + k * k);
  319. } else {
  320. p.x = p2.x + L / Math.sqrt(1 + k * k);
  321. p.y = p2.y + L * k / Math.sqrt(1 + k * k);
  322. }
  323. }
  324. }
  325. p.x = Math.round(p.x);
  326. p.y = Math.round(p.y);
  327. return new Phaser.Math.Vector2(p.x, p.y);
  328. },
  329. // 形成刀光点
  330. generateBlade(points) {
  331. const res = [];
  332. if (points.length <= 0) {
  333. return res;
  334. } else if (points.length === 1) {
  335. const oneLength = 6;
  336. res.push(new Phaser.Math.Vector2(points[0].x - oneLength, points[0].y));
  337. res.push(new Phaser.Math.Vector2(points[0].x, points[0].y - oneLength));
  338. res.push(new Phaser.Math.Vector2(points[0].x + oneLength, points[0].y));
  339. res.push(new Phaser.Math.Vector2(points[0].x, points[0].y + oneLength));
  340. } else {
  341. const tailLength = 10;
  342. const headLength = 20;
  343. const tailWidth = 1;
  344. const headWidth = 6;
  345. res.push(this.calcParallel(points[0], points[1], tailLength));
  346. for (let i = 0; i < points.length - 1; i++) {
  347. res.push(this.calcVertical(
  348. points[i + 1],
  349. points[i],
  350. Math.round((headWidth - tailWidth) * i / (points.length - 1) + tailWidth),
  351. true
  352. ));
  353. }
  354. res.push(this.calcVertical(
  355. points[points.length - 2],
  356. points[points.length - 1],
  357. headWidth,
  358. false
  359. ));
  360. res.push(this.calcParallel(
  361. points[points.length - 1],
  362. points[points.length - 2],
  363. headLength
  364. ));
  365. res.push(this.calcVertical(
  366. points[points.length - 2],
  367. points[points.length - 1],
  368. headWidth,
  369. true
  370. ));
  371. for (let i = points.length - 1; i > 0; i--) {
  372. res.push(this.calcVertical(
  373. points[i],
  374. points[i - 1],
  375. Math.round((headWidth - tailWidth) * (i - 1) / (points.length - 1) + tailWidth),
  376. false
  377. ));
  378. }
  379. }
  380. return res;
  381. },
  382. randomMinMax(min, max) {
  383. return Math.random() * (max - min) + min;
  384. },
  385. randomPosX() {
  386. return this.randomMinMax(-100, width + 100);
  387. },
  388. randomPosY() {
  389. //return this.randomMinMax(100, 200) + height;
  390. return this.randomMinMax(height - 100, height);
  391. },
  392. randomVelocityX(posX) {
  393. if (posX < 0) {
  394. return this.randomMinMax(100, 400);
  395. } else if (posX >= 0 && posX < width / 2) {
  396. return this.randomMinMax(0, 400);
  397. } else if (posX >= width / 2 && posX < width) {
  398. return this.randomMinMax(-400, 0);
  399. } else {
  400. return this.randomMinMax(-400, -100);
  401. }
  402. },
  403. randomVelocityY() {
  404. const myH = height - 600;
  405. // 调整范围为原速度的70%左右(根据需要微调)
  406. return this.randomMinMax(-630 - myH * 0.5, -595 - myH * 0.5);
  407. },
  408. degCos(deg) {
  409. return Math.cos(deg * Math.PI / 180);
  410. },
  411. degSin(deg) {
  412. return Math.sin(deg * Math.PI / 180);
  413. },
  414. shuffle(o) {
  415. for (let j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
  416. return o;
  417. }
  418. };
  419. // 炸弹类
  420. class Bomb {
  421. constructor(envConfig) {
  422. this.env = envConfig;
  423. this.game = envConfig.scene;
  424. this.sprite = null;
  425. this.bombImage = null;
  426. this.bombSmoke = null;
  427. this.bombEmit = null;
  428. this.init();
  429. }
  430. init() {
  431. // 创建容器
  432. this.sprite = this.game.add.container(
  433. this.env.x || 0,
  434. this.env.y || 0
  435. );
  436. // 炸弹图像
  437. this.bombImage = this.game.add.sprite(0, 0, 'bomb');
  438. this.bombImage.setOrigin(0.5, 0.5);
  439. // 烟雾
  440. this.bombSmoke = this.game.add.sprite(-55, -55, 'smoke');
  441. // 创建粒子纹理
  442. const bitmap = this.game.make.graphics({ x: 0, y: 0, add: false });
  443. this.generateFlame(bitmap);
  444. const texture = bitmap.generateTexture('flameParticle', 50, 50);
  445. // 粒子发射器
  446. this.bombEmit = this.game.add.particles(0, 0, texture.key, {
  447. x: -30,
  448. y: -30,
  449. speed: { min: -100, max: 100 },
  450. scale: { start: 1, end: 0.8 },
  451. alpha: { start: 1, end: 0.1 },
  452. lifespan: 1500,
  453. frequency: 50,
  454. maxParticles: 20
  455. });
  456. // 添加到容器
  457. this.sprite.add([this.bombImage, this.bombEmit, this.bombSmoke]);
  458. // 物理属性
  459. this.game.physics.add.existing(this.sprite);
  460. this.sprite.body.setCollideWorldBounds(false);
  461. }
  462. generateFlame(bitmap) {
  463. const len = 5;
  464. bitmap.fillStyle(0xffffff);
  465. bitmap.beginPath();
  466. bitmap.moveTo(25 + len, 25 - len);
  467. bitmap.lineTo(25 + len, 25 + len);
  468. bitmap.lineTo(25 - len, 25 + len);
  469. bitmap.lineTo(25 - len, 25 - len);
  470. bitmap.closePath();
  471. bitmap.fill();
  472. }
  473. explode(onWhite, onComplete) {
  474. // 播放炸弹爆炸音效
  475. const boomSound = this.game.sound.add('boom');
  476. boomSound.play({
  477. volume: 0.7 // 炸弹音效可稍大,增强冲击力
  478. });
  479. const lights = [];
  480. const startDeg = Math.floor(Math.random() * 360);
  481. // 保存外部this上下文
  482. const self = this;
  483. // 创建直射光芒效果
  484. const maxRays = 25; // 光芒数量
  485. const rayLength = 400; // 光芒长度
  486. const rayWidth = 200; // 光芒宽度
  487. for (let i = 0; i < maxRays; i++) {
  488. const angle = (i / maxRays) * Math.PI * 2; // 计算每个光芒的角度
  489. const light = self.game.add.graphics({
  490. x: self.sprite.x,
  491. y: self.sprite.y
  492. });
  493. // 设置初始透明度和颜色
  494. const alpha = 0.8 - (Math.random() * 0.3); // 随机透明度,增加自然感
  495. const hue = 45 - (Math.random() * 20); // 随机色调,从黄色到白色
  496. const color = Phaser.Display.Color.HSVToRGB(hue / 360, 0.8, 1).color;
  497. light.alpha = alpha;
  498. light.fillStyle(color, 1);
  499. // 创建细长三角形
  500. light.beginPath();
  501. light.moveTo(0, 0); // 起点在中心
  502. light.lineTo(
  503. Math.cos(angle) * rayLength,
  504. Math.sin(angle) * rayLength
  505. ); // 终点在外围
  506. light.lineTo(
  507. Math.cos(angle + Math.PI + 0.1) * (rayWidth / 2),
  508. Math.sin(angle + Math.PI + 0.1) * (rayWidth / 2)
  509. ); // 底部左点
  510. light.closePath();
  511. light.fill();
  512. light.setDepth(2000);
  513. lights.push(light);
  514. // 添加脉动动画效果
  515. self.game.tweens.add({
  516. targets: light,
  517. alpha: alpha * 0.5,
  518. duration: 800 + Math.random() * 400,
  519. yoyo: true,
  520. repeat: -1,
  521. ease: 'Sine.easeInOut'
  522. });
  523. }
  524. // 2. 打乱灯光顺序
  525. mathTool.shuffle(lights);
  526. // 3. 创建白屏元素
  527. const whiteScreen = self.game.add.graphics({
  528. x: 0,
  529. y: 0
  530. });
  531. whiteScreen.fillStyle(0xffffff, 0);
  532. whiteScreen.fillRect(0, 0, width, height);
  533. whiteScreen.setDepth(3000);
  534. whiteScreen.alpha = 0;
  535. // 4. 按顺序执行灯光动画
  536. function playChainAnimations(index) {
  537. if (index >= lights.length) {
  538. playWhiteScreenAnimation();
  539. return;
  540. }
  541. const light = lights[index];
  542. self.game.tweens.add({
  543. targets: light,
  544. alpha: { from: 0, to: 1, from: 0 },
  545. scale: { from: 1, to: 2 },
  546. duration: 100,
  547. onComplete: () => {
  548. light.destroy();
  549. playChainAnimations(index + 1);
  550. }
  551. });
  552. }
  553. function playWhiteScreenAnimation() {
  554. self.game.tweens.add({
  555. targets: whiteScreen,
  556. alpha: { from: 0, to: 1, to: 0 },
  557. duration: 50,
  558. onUpdate: (tween) => {
  559. if (tween.progress >= 0.25 && tween.progress <= 0.3) {
  560. onWhite();
  561. }
  562. },
  563. onComplete: () => {
  564. whiteScreen.destroy();
  565. if (typeof onComplete === 'function') {
  566. onComplete();
  567. }
  568. }
  569. });
  570. }
  571. // 开始执行第一个灯光动画
  572. playChainAnimations(0);
  573. // 新增:在爆炸动画开始后立即隐藏炸弹,动画结束后销毁
  574. this.sprite.visible = false; // 先隐藏视觉元素
  575. // 在爆炸完成回调中销毁炸弹
  576. const originalOnComplete = onComplete;
  577. onComplete = () => {
  578. // 销毁炸弹容器及其内部所有元素
  579. if (this.sprite) {
  580. this.sprite.destroy();
  581. }
  582. if (this.bombEmit) {
  583. this.bombEmit.destroy();
  584. }
  585. if (this.bombSmoke) {
  586. this.bombSmoke.destroy();
  587. }
  588. // 执行原有的完成回调
  589. if (typeof originalOnComplete === 'function') {
  590. originalOnComplete();
  591. }
  592. };
  593. }
  594. getSprite() {
  595. return this.sprite;
  596. }
  597. }
  598. // 水果类
  599. class Fruit {
  600. constructor(envConfig) {
  601. this.env = envConfig;
  602. this.game = envConfig.scene;
  603. this.sprite = null;
  604. this.emitterMap = {
  605. "apple": 0xFFC3E925,
  606. "banana": 0xFFFFE337,
  607. "basaha": 0xFFEB2D13,
  608. "peach": 0xFFF8C928,
  609. "sandia": 0xFF739E0F
  610. };
  611. this.bitmap = null;
  612. this.emitter = null;
  613. this.halfOne = null;
  614. this.halfTwo = null;
  615. this.init();
  616. }
  617. init() {
  618. this.sprite = this.game.add.sprite(
  619. this.env.x || 0,
  620. this.env.y || 0,
  621. this.env.key
  622. );
  623. this.sprite.setOrigin(0.5, 0.5);
  624. this.sprite.setScale(scaleRatio.value);
  625. // 物理属性
  626. this.game.physics.add.existing(this.sprite);
  627. this.sprite.body.setCollideWorldBounds(false);
  628. this.sprite.body.onWorldBounds = true;
  629. // 创建粒子纹理
  630. this.bitmap = this.game.make.graphics({ x: 0, y: 0, add: false });
  631. // 粒子发射器
  632. this.emitter = this.game.add.particles(0, 0, 'flameParticle', {
  633. visible: false // 初始隐藏
  634. });
  635. }
  636. // 水果类中的half方法
  637. half(deg, shouldEmit = false) {
  638. // 计算世界坐标
  639. const transform = this.sprite.getWorldTransformMatrix();
  640. const worldPos = new Phaser.Math.Vector2(
  641. transform.getX(0, 0),
  642. transform.getY(0, 0)
  643. );
  644. // 播放切割音效
  645. if (shouldEmit) { // 仅在需要发射粒子时播放(即有效切割时)
  646. const splatterSound = this.game.sound.add('splatter');
  647. splatterSound.play({
  648. volume: 0.5 // 可调节音量,范围0-1
  649. });
  650. }
  651. // 1. 计算切割方向的垂直向量(用于分离力)
  652. // 刀刃角度转弧度
  653. const rad = Phaser.Math.DegToRad(deg);
  654. // 垂直于刀刃的方向向量(单位向量)
  655. const sepX = Math.sin(rad); // 垂直方向X分量
  656. const sepY = -Math.cos(rad); // 垂直方向Y分量
  657. // 分离力度(可根据水果大小调整)
  658. const sepForce = 300;
  659. // 2. 创建第一半水果
  660. this.halfOne = this.game.add.sprite(worldPos.x, worldPos.y, this.sprite.texture.key + '-1');
  661. this.halfOne.setOrigin(0.5, 0.5);
  662. this.halfOne.setScale(scaleRatio.value);
  663. this.halfOne.rotation = Phaser.Math.DegToRad(deg + 45); // 初始角度与刀刃匹配
  664. this.game.physics.add.existing(this.halfOne);
  665. // 速度 = 原速度 + 分离速度(向一侧)
  666. this.halfOne.body.velocity.x = this.sprite.body.velocity.x + sepX * sepForce;
  667. this.halfOne.body.velocity.y = this.sprite.body.velocity.y + sepY * sepForce;
  668. this.halfOne.body.gravity.y = 2000;
  669. // 增加旋转(顺时针)
  670. this.halfOne.body.angularVelocity = 500; // 旋转速度(度/秒)
  671. this.halfOne.body.setCollideWorldBounds(false);
  672. this.halfOne.checkWorldBounds = true;
  673. this.halfOne.outOfBoundsKill = true;
  674. // 3. 创建第二半水果(分离方向相反)
  675. this.halfTwo = this.game.add.sprite(worldPos.x, worldPos.y, this.sprite.texture.key + '-2');
  676. this.halfTwo.setOrigin(0.5, 0.5);
  677. this.halfTwo.setScale(scaleRatio.value);
  678. this.halfTwo.rotation = Phaser.Math.DegToRad(deg + 45);
  679. this.game.physics.add.existing(this.halfTwo);
  680. // 速度 = 原速度 - 分离速度(向另一侧)
  681. this.halfTwo.body.velocity.x = this.sprite.body.velocity.x - sepX * sepForce;
  682. this.halfTwo.body.velocity.y = this.sprite.body.velocity.y - sepY * sepForce;
  683. this.halfTwo.body.gravity.y = 2000;
  684. // 增加旋转(逆时针,与第一半相反)
  685. this.halfTwo.body.angularVelocity = -500;
  686. this.halfTwo.body.setCollideWorldBounds(false);
  687. this.halfTwo.checkWorldBounds = true;
  688. this.halfTwo.outOfBoundsKill = true;
  689. // 4. 原水果透明度渐变消失(替代直接销毁)
  690. this.game.tweens.add({
  691. targets: this.sprite,
  692. alpha: 0, // 透明度从1→0
  693. duration: 100, // 100ms内消失
  694. onComplete: () => {
  695. this.sprite.destroy();
  696. }
  697. });
  698. // 5. 优化粒子效果(沿分离方向飞溅)
  699. if (shouldEmit) {
  700. const emitColor = this.emitterMap[this.sprite.texture.key];
  701. this.generateFlame(this.bitmap, emitColor);
  702. const texture = this.bitmap.generateTexture('fruitParticle', 60, 60);
  703. // 粒子发射器:沿分离方向扩散
  704. this.emitter = this.game.add.particles(0, 0, texture.key, {
  705. x: worldPos.x,
  706. y: worldPos.y,
  707. // 速度方向:以分离方向为中心,±30度范围
  708. angle: {
  709. min: deg - 30,
  710. max: deg + 30
  711. },
  712. speed: { min: 100, max: 300 }, // 速度与分离力度匹配
  713. scale: { start: 0.8, end: 0.1 },
  714. alpha: { start: 1, end: 0.1 },
  715. lifespan: 600, // 延长粒子生命周期,增强视觉效果
  716. maxParticles: 15 // 增加粒子数量
  717. });
  718. }
  719. }
  720. generateFlame(bitmap, color) {
  721. // const len = 30;
  722. // bitmap.clear();
  723. // const rgb = Phaser.Display.Color.IntegerToRGB(color);
  724. // const radgrad = bitmap.context.createRadialGradient(len, len, 4, len, len, len);
  725. // radgrad.addColorStop(0, `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 1)`);
  726. // radgrad.addColorStop(1, `rgba(${rgb.r}, ${rgb.g}, ${rgb.b}, 0)`);
  727. // bitmap.fillStyle(radgrad);
  728. // bitmap.fillRect(0, 0, 2 * len, 2 * len);
  729. const len = 30;
  730. bitmap.clear();
  731. // 将 16 进制颜色转换为 RGB 值(0-255 范围)
  732. const rgb = Phaser.Display.Color.IntegerToRGB(color);
  733. const r = rgb.r / 255; // 转换为 0-1 范围
  734. const g = rgb.g / 255;
  735. const b = rgb.b / 255;
  736. // 使用 Phaser 的径向渐变 API:fillGradientStyle
  737. // 参数说明:
  738. // 1. 渐变类型:1 表示径向渐变
  739. // 2-5. 内圆中心坐标 (x1, y1) 和半径 (r1)
  740. // 6-9. 外圆中心坐标 (x2, y2) 和半径 (r2)
  741. // 10-13. 内圆颜色(r, g, b, a)
  742. // 14-17. 外圆颜色(r, g, b, a)
  743. bitmap.fillGradientStyle(
  744. 1, // 径向渐变
  745. len, len, 4, // 内圆:中心 (len, len),半径 4
  746. len, len, len, // 外圆:中心 (len, len),半径 len
  747. r, g, b, 1, // 内圆颜色(不透明)
  748. r, g, b, 0 // 外圆颜色(透明)
  749. );
  750. // 绘制矩形作为粒子纹理
  751. bitmap.fillRect(0, 0, 2 * len, 2 * len);
  752. }
  753. getSprite() {
  754. return this.sprite;
  755. }
  756. }
  757. // 刀身类
  758. class Blade {
  759. constructor(envConfig, handType) {// 新增handType区分左右手
  760. this.env = envConfig;
  761. this.game = envConfig.scene;
  762. this.points = []; // 记录鼠标轨迹点
  763. this.graphics = null;
  764. this.POINTLIFETIME = 200; // 轨迹点的生命周期(毫秒)
  765. this.allowBlade = false;
  766. this.lastPoint = null; // 上一个记录的点
  767. this.moveThreshold = 5; // 鼠标移动超过这个距离才记录新点(避免密集冗余)
  768. this.handType = handType; // 存储"left"或"right"
  769. this.color = handType === 'left' ? 0x00FFFF : 0xFFFF00; // 左手蓝色,右手黄色(示例)
  770. this.init();
  771. }
  772. init() {
  773. this.graphics = this.game.add.graphics({
  774. x: 0,
  775. y: 0
  776. });
  777. // 根据手型设置绘图层级(可选)
  778. this.graphics.setDepth(this.handType === 'left' ? 1001 : 1002);
  779. // 监听鼠标移动事件(可选,也可在update中处理)
  780. this.game.input.on('pointermove', (pointer) => {
  781. //console.log("11111", pointer)
  782. if (this.allowBlade) {
  783. this.handleMouseMove(pointer);
  784. }
  785. });
  786. }
  787. // 处理鼠标移动:记录轨迹点
  788. handleMouseMove(pointer) {
  789. if (!this.allowBlade) return;
  790. const point = {
  791. x: pointer.x,
  792. y: pointer.y,
  793. time: Date.now()
  794. };
  795. if (!this.lastPoint) {
  796. // 首次记录点
  797. this.lastPoint = point;
  798. this.points.push(point);
  799. } else {
  800. // 计算与上一个点的距离,超过阈值才记录新点
  801. const dis = Math.hypot(
  802. point.x - this.lastPoint.x,
  803. point.y - this.lastPoint.y
  804. );
  805. if (dis > this.moveThreshold) {
  806. this.lastPoint = point;
  807. this.points.push(point);
  808. }
  809. }
  810. }
  811. update() {
  812. if (!this.allowBlade) return;
  813. this.graphics.clear();
  814. const now = Date.now();
  815. this.points = this.points.filter(point => now - point.time < this.POINTLIFETIME);
  816. if (this.points.length > 0) {
  817. const bladePoints = mathTool.generateBlade(this.points);
  818. if (bladePoints.length > 0) {
  819. this.graphics.fillStyle(this.color, 0.8); // 使用当前刀光的颜色
  820. this.graphics.beginPath();
  821. this.graphics.moveTo(bladePoints[0].x, bladePoints[0].y);
  822. bladePoints.forEach((point, i) => i > 0 && this.graphics.lineTo(point.x, point.y));
  823. this.graphics.closePath();
  824. this.graphics.fill();
  825. }
  826. }
  827. }
  828. // 碰撞检测:去掉“鼠标按下”的限制,只要有轨迹就检测
  829. checkCollide(sprite, onCollide) {
  830. if (this.allowBlade && this.points.length > 2) { // 仅保留轨迹点数量的判断
  831. const bounds = sprite.getBounds();
  832. for (const point of this.points) {
  833. if (Phaser.Geom.Rectangle.Contains(bounds, point.x, point.y)) {
  834. onCollide();
  835. break;
  836. }
  837. }
  838. }
  839. }
  840. collideDeg() {
  841. let deg = 0;
  842. const len = this.points.length;
  843. if (len >= 2) {
  844. const p0 = this.points[0];
  845. const p1 = this.points[len - 1];
  846. if (p0.x === p1.x) {
  847. deg = 90;
  848. } else {
  849. const val = (p0.y - p1.y) / (p0.x - p1.x);
  850. deg = Math.round(Math.atan(val) * 180 / Math.PI);
  851. }
  852. if (deg < 0) {
  853. deg += 180;
  854. }
  855. }
  856. return deg;
  857. }
  858. enable() {
  859. this.allowBlade = true;
  860. }
  861. }
  862. // 启动场景
  863. class BootScene extends Phaser.Scene {
  864. constructor() {
  865. super('boot');
  866. }
  867. preload() {
  868. this.load.image('loading', 'static/images/fruit/preloader.gif');
  869. }
  870. create() {
  871. this.scene.start('preload');
  872. }
  873. }
  874. // 预加载场景
  875. class PreloadScene extends Phaser.Scene {
  876. constructor() {
  877. super('preload');
  878. }
  879. preload() {
  880. this.add.sprite(10, height / 2, 'loading').setPosition((width) / 2, height / 2);
  881. this.load.on('progress', (value) => {
  882. // console.log("进度", value)
  883. });
  884. // 加载游戏资源
  885. this.load.image('apple', 'static/images/fruit/apple.png');
  886. this.load.image('apple-1', 'static/images/fruit/apple-1.png');
  887. this.load.image('apple-2', 'static/images/fruit/apple-2.png');
  888. this.load.image('background', 'static/images/fruit/background.jpg');
  889. this.load.image('banana', 'static/images/fruit/banana.png');
  890. this.load.image('banana-1', 'static/images/fruit/banana-1.png');
  891. this.load.image('banana-2', 'static/images/fruit/banana-2.png');
  892. this.load.image('basaha', 'static/images/fruit/basaha.png');
  893. this.load.image('basaha-1', 'static/images/fruit/basaha-1.png');
  894. this.load.image('basaha-2', 'static/images/fruit/basaha-2.png');
  895. this.load.image('best', 'static/images/fruit/best.png');
  896. this.load.image('bomb', 'static/images/fruit/bomb.png');
  897. this.load.image('game-over', 'static/images/fruit/game-over.png');
  898. this.load.image('home-desc', 'static/images/fruit/home-desc.png');
  899. this.load.image('home-mask', 'static/images/fruit/home-mask.png');
  900. this.load.image('logo', 'static/images/fruit/logo.png');
  901. this.load.image('lose', 'static/images/fruit/lose.png');
  902. this.load.image('new-game', 'static/images/fruit/new-game.png');
  903. this.load.image('peach', 'static/images/fruit/peach.png');
  904. this.load.image('peach-1', 'static/images/fruit/peach-1.png');
  905. this.load.image('peach-2', 'static/images/fruit/peach-2.png');
  906. this.load.image('quit', 'static/images/fruit/quit.png');
  907. this.load.image('sandia', 'static/images/fruit/sandia.png');
  908. this.load.image('sandia-1', 'static/images/fruit/sandia-1.png');
  909. this.load.image('sandia-2', 'static/images/fruit/sandia-2.png');
  910. this.load.image('score', 'static/images/fruit/score.png');
  911. this.load.image('shadow', 'static/images/fruit/shadow.png');
  912. this.load.image('smoke', 'static/images/fruit/smoke.png');
  913. this.load.image('x', 'static/images/fruit/x.png');
  914. this.load.image('xf', 'static/images/fruit/xf.png');
  915. this.load.image('xx', 'static/images/fruit/xx.png');
  916. this.load.image('xxf', 'static/images/fruit/xxf.png');
  917. this.load.image('xxx', 'static/images/fruit/xxx.png');
  918. this.load.image('xxxf', 'static/images/fruit/xxxf.png');
  919. this.load.bitmapFont('number', 'static/images/fruit/bitmapFont.png', 'static/images/fruit/bitmapFont.xml');
  920. this.load.audio('splatter', 'static/images/fruit/splatter.mp3');
  921. this.load.audio('boom', 'static/images/fruit/boom.mp3');
  922. this.load.audio('throw', 'static/images/fruit/throw.mp3');
  923. }
  924. create() {
  925. this.scene.start('main');
  926. }
  927. }
  928. // 主场景
  929. class MainScene extends Phaser.Scene {
  930. constructor() {
  931. super('main');
  932. this.bg = null;
  933. this.blade = null;
  934. this.homeGroup = null;
  935. this.home_mask = null;
  936. this.logo = null;
  937. this.home_desc = null;
  938. this.sandiaGroup = null;
  939. this.new_game = null;
  940. this.sandia = null;
  941. this.lose = null;
  942. this.start = false;
  943. this.sandiaRotateSpeed = 0.9;
  944. this.newGameRotateSpeed = -0.3;
  945. this.leftBlade = null; // 左手刀光
  946. this.rightBlade = null; // 右手刀光
  947. }
  948. create() {
  949. // 初始化物理系统
  950. this.physics.world.gravity.y = 0;
  951. // 背景
  952. this.bg = this.add.image(0, 0, "background");
  953. this.bg.setScale(wRatio, hRatio);
  954. this.bg.setPosition(width / 2, height / 2);
  955. this.bg.setOrigin(0.5, 0.5);
  956. // 刀光
  957. this.blade = new Blade({
  958. scene: this
  959. });
  960. // 开始动画
  961. this.homeGroupAnim();
  962. // 初始化左右手刀光
  963. this.leftBlade = new Blade({ scene: this }, 'left');
  964. this.rightBlade = new Blade({ scene: this }, 'right');
  965. }
  966. update() {
  967. this.updateRotate();
  968. // 检查是否该跳转到游戏场景
  969. // if (this.start) {
  970. // this.gotoNextScene();
  971. // }
  972. // 更新刀光
  973. this.blade.update();
  974. // 检查水果碰撞
  975. if (this.sandia && this.sandia.getSprite() && this.sandia.getSprite().active && !this.start) {
  976. this.blade.checkCollide(
  977. this.sandia.getSprite(),
  978. () => {
  979. this.startGame();
  980. }
  981. );
  982. }
  983. // 分别更新左右手刀光
  984. this.leftBlade.update();
  985. this.rightBlade.update();
  986. // 分别检测左右手刀光与水果的碰撞
  987. if (this.sandia && this.sandia.getSprite() && !this.start) {
  988. // 右手碰撞检测
  989. this.rightBlade.checkCollide(
  990. this.sandia.getSprite(),
  991. () => this.startGame()
  992. );
  993. // 左手碰撞检测(可选:允许左手也能启动游戏)
  994. this.leftBlade.checkCollide(
  995. this.sandia.getSprite(),
  996. () => this.startGame()
  997. );
  998. }
  999. }
  1000. homeGroupAnim() {
  1001. //创建组合默认先隐藏
  1002. this.homeGroup = this.add.container(0, -height);
  1003. //背景蒙版
  1004. // this.home_mask = this.add.image(0, 0, "home-mask");
  1005. // this.home_mask.setOrigin(0, 0);
  1006. // this.home_mask.setScale(wRatio);
  1007. // this.home_mask.y = -200;
  1008. //logo
  1009. this.logo = this.add.image(20, 50, "logo");
  1010. this.logo.setOrigin(0, 0);
  1011. //提示语
  1012. this.home_desc = this.add.image(0, 0, "home-desc");
  1013. this.home_desc.setPosition((width - this.home_desc.width / 2) - 20, 70);
  1014. //合并图层
  1015. //this.homeGroup.add([this.home_mask, this.logo, this.home_desc]);
  1016. this.homeGroup.add([this.logo, this.home_desc]);
  1017. // 退出按钮
  1018. this.lose = this.add.image(0, 0, "lose");
  1019. this.lose.setPosition(width - this.lose.width - 30, height - this.lose.height - 30);
  1020. this.lose.setInteractive();
  1021. // 绑定点击事件
  1022. this.lose.on('pointerdown', () => this.getExit());
  1023. //动画效果,接着展示西瓜
  1024. this.tweens.add({
  1025. targets: this.homeGroup,
  1026. y: 0,
  1027. duration: 400,
  1028. ease: 'Sine.InOut',
  1029. onComplete: () => this.fruitAnim()
  1030. });
  1031. }
  1032. fruitAnim() {
  1033. // 每次创建全新的容器,避免复用旧实例
  1034. this.sandiaGroup = this.add.container(0, 0); // 先置0,后续重新计算
  1035. // 西瓜组初始位置:基于当前窗口尺寸动态计算(核心修复)
  1036. this.sandiaGroup.setPosition(width / 2, height / 2); // 强制设置位置
  1037. //圆圈
  1038. this.new_game = this.add.sprite(0, 0, "new-game");
  1039. this.new_game.setOrigin(0.5, 0.5);
  1040. this.new_game.setScale(scaleRatio.value);
  1041. //西瓜
  1042. this.sandia = new Fruit({ scene: this, key: "sandia" });
  1043. this.sandiaGroup.add([this.new_game, this.sandia.getSprite()]);
  1044. //动画效果,接着开放鼠标事件
  1045. this.tweens.add({
  1046. targets: this.sandiaGroup,
  1047. scale: 1,
  1048. duration: 500,
  1049. ease: 'Linear.None',
  1050. onComplete: () => this.allowBlade()
  1051. });
  1052. }
  1053. updateRotate() {
  1054. //西瓜外框圆圈图片旋转
  1055. if (this.new_game) {
  1056. this.new_game.rotation += this.newGameRotateSpeed * 0.016;
  1057. }
  1058. if (this.sandia && this.sandia.getSprite()) {
  1059. this.sandia.getSprite().rotation += this.sandiaRotateSpeed * 0.016;
  1060. }
  1061. }
  1062. allowBlade() {
  1063. this.blade.enable();
  1064. // 同时启用左右手刀光
  1065. this.leftBlade.enable();
  1066. this.rightBlade.enable();
  1067. }
  1068. startGame() {
  1069. // this.start = true;
  1070. // // 隐藏主界面元素
  1071. // this.tweens.add({
  1072. // targets: this.homeGroup,
  1073. // y: -height,
  1074. // duration: 200,
  1075. // ease: 'Sine.InOut'
  1076. // });
  1077. // // 隐藏按钮
  1078. // this.new_game.destroy();
  1079. // this.lose.destroy();
  1080. // // 切开西瓜
  1081. // const deg = this.blade.collideDeg();
  1082. // this.sandia.half(deg);
  1083. this.start = true; // 先禁用立即切换
  1084. const deg = this.blade.collideDeg();
  1085. // 播放初始西瓜切割音效
  1086. const splatterSound = this.sound.add('splatter');
  1087. splatterSound.play({
  1088. volume: 0.5 // 与普通水果切割音量保持一致
  1089. });
  1090. this.sandia.half(deg); // 切开西瓜,生成两半
  1091. // 延迟1秒(1000ms)后再切换场景,等待动画展示
  1092. setTimeout(() => {
  1093. this.gotoNextScene();
  1094. }, 1000);
  1095. }
  1096. gotoNextScene() {
  1097. this.resetScene();
  1098. this.scene.start("play");
  1099. }
  1100. getExit() {
  1101. console.log("退出");
  1102. router.push({ path: '/game' });
  1103. }
  1104. resetScene() {
  1105. this.sandia = null;
  1106. this.start = false;
  1107. // 新增:销毁西瓜容器,避免残留
  1108. if (this.sandiaGroup) {
  1109. this.sandiaGroup.destroy(); // 销毁容器及其子元素
  1110. this.sandiaGroup = null; // 置空引用
  1111. }
  1112. }
  1113. }
  1114. // 游戏场景
  1115. class PlayScene extends Phaser.Scene {
  1116. constructor() {
  1117. super('play');
  1118. this.bg = null;
  1119. this.blade = null;
  1120. this.fruits = [];
  1121. this.score = 0;
  1122. this.playing = false; // 改为false,在初始化方法中设置为true
  1123. this.bombExplode = false;
  1124. this.lostCount = 0;
  1125. this.scoreImage = null;
  1126. this.best = null;
  1127. this.scoreText = null;
  1128. this.xxxGroup = null;
  1129. this.x = null;
  1130. this.xx = null;
  1131. this.xxx = null;
  1132. this.gravity = 200;
  1133. this.leftBlade = null;
  1134. this.rightBlade = null;
  1135. }
  1136. create() {
  1137. // 物理系统
  1138. this.physics.world.gravity.y = this.gravity;
  1139. // 背景
  1140. // this.bg = this.add.image(0, 0, 'background');
  1141. // this.bg.setScale(wRatio, hRatio);
  1142. // this.bg.setPosition(width / 2, height / 2);
  1143. // this.bg.setOrigin(0, 0);
  1144. this.bg = this.add.image(0, 0, "background");
  1145. // 设置背景图铺满整个游戏区域
  1146. this.bg.displayWidth = width;
  1147. this.bg.displayHeight = height;
  1148. // 设置背景图原点为左上角
  1149. this.bg.setOrigin(0, 0);
  1150. // 刀光
  1151. this.blade = new Blade({
  1152. scene: this
  1153. });
  1154. this.blade.enable();
  1155. // 初始化UI
  1156. this.scoreAnim();
  1157. this.scoreTextAnim();
  1158. this.bestAnim();
  1159. this.xxxAnim();
  1160. // 添加调试信息
  1161. console.log("PlayScene created");
  1162. // 调用初始化方法,而不是直接开始生成水果
  1163. this.initGame();
  1164. // 初始化左右手刀光
  1165. this.leftBlade = new Blade({ scene: this }, 'left');
  1166. this.rightBlade = new Blade({ scene: this }, 'right');
  1167. this.leftBlade.enable();
  1168. this.rightBlade.enable();
  1169. }
  1170. initGame() {
  1171. // 重置游戏状态
  1172. this.fruits = [];
  1173. this.score = 0;
  1174. this.lostCount = 0;
  1175. this.bombExplode = false;
  1176. this.scoreText.setText(this.score.toString());
  1177. // 重置失去计数UI
  1178. if (this.xxxGroup) {
  1179. this.xxxGroup.removeAll(true);
  1180. this.x = this.add.image(0, 0, 'x');
  1181. this.xx = this.add.image(22, 0, 'xx');
  1182. this.xxx = this.add.image(49, 0, 'xxx');
  1183. this.x.setOrigin(0, 0);
  1184. this.xx.setOrigin(0, 0);
  1185. this.xxx.setOrigin(0, 0);
  1186. this.xxxGroup.add([this.x, this.xx, this.xxx]);
  1187. }
  1188. // 开始游戏
  1189. this.playing = true;
  1190. console.log("Game initialized and started");
  1191. // 延迟一点时间再生成第一个水果,让玩家有准备
  1192. this.time.delayedCall(1000, () => {
  1193. this.startFruit();
  1194. console.log("First fruit spawned");
  1195. });
  1196. }
  1197. update() {
  1198. // 如果游戏未开始,不执行任何操作
  1199. if (!this.playing) return;
  1200. // 检查是否有水果出界
  1201. if (!this.bombExplode) {
  1202. for (let i = this.fruits.length - 1; i >= 0; i--) {
  1203. const fruit = this.fruits[i];
  1204. const sprite = fruit.getSprite();
  1205. if (sprite && !sprite.active) continue;
  1206. if (sprite && (
  1207. sprite.y > height + 100 ||
  1208. sprite.x < -100 ||
  1209. sprite.x > width + 100
  1210. )) {
  1211. if (fruit.isFruit) {
  1212. this.onOut(fruit);
  1213. }
  1214. sprite.destroy();
  1215. this.fruits.splice(i, 1);
  1216. }
  1217. }
  1218. }
  1219. // 如果没有水果且游戏进行中,生成新水果
  1220. if (this.playing && this.fruits.length === 0 && !this.bombExplode) {
  1221. this.startFruit();
  1222. }
  1223. // 更新刀光
  1224. this.blade.update();
  1225. // 分别更新左右手刀光
  1226. this.leftBlade.update();
  1227. this.rightBlade.update();
  1228. // 检查碰撞
  1229. if (!this.bombExplode) {
  1230. this.fruits.forEach((fruit, i) => {
  1231. if (fruit.getSprite() && fruit.getSprite().active) {
  1232. this.blade.checkCollide(
  1233. fruit.getSprite(),
  1234. () => {
  1235. if (fruit.isFruit) {
  1236. this.onKill(fruit);
  1237. this.fruits.splice(i, 1);
  1238. } else {
  1239. this.onBomb(fruit);
  1240. }
  1241. }
  1242. );
  1243. // 右手碰撞
  1244. this.rightBlade.checkCollide(
  1245. fruit.getSprite(),
  1246. () => this.handleCollision(fruit, i)
  1247. );
  1248. // 左手碰撞
  1249. this.leftBlade.checkCollide(
  1250. fruit.getSprite(),
  1251. () => this.handleCollision(fruit, i)
  1252. );
  1253. }
  1254. });
  1255. }
  1256. }
  1257. // 统一处理碰撞逻辑(提取重复代码)
  1258. handleCollision(fruit, index) {
  1259. if (fruit.isFruit) {
  1260. this.onKill(fruit);
  1261. this.fruits.splice(index, 1);
  1262. } else {
  1263. this.onBomb(fruit);
  1264. }
  1265. }
  1266. scoreAnim() {
  1267. this.scoreImage = this.add.image(-100, 8, 'score');
  1268. this.scoreImage.setOrigin(0, 0);
  1269. this.tweens.add({
  1270. targets: this.scoreImage,
  1271. x: 8,
  1272. duration: 300,
  1273. ease: 'Sine.InOut'
  1274. });
  1275. }
  1276. bestAnim() {
  1277. this.best = this.add.image(-100, 52, 'best');
  1278. this.best.setOrigin(0, 0);
  1279. this.tweens.add({
  1280. targets: this.best,
  1281. x: 5,
  1282. duration: 300,
  1283. ease: 'Sine.InOut'
  1284. });
  1285. }
  1286. scoreTextAnim() {
  1287. this.scoreText = this.add.bitmapText(-100, 40, 'number', this.score.toString(), 32);
  1288. this.scoreText.setOrigin(0, 0);
  1289. this.tweens.add({
  1290. targets: this.scoreText,
  1291. x: 75,
  1292. duration: 300,
  1293. ease: 'Sine.InOut'
  1294. });
  1295. }
  1296. xxxAnim() {
  1297. this.xxxGroup = this.add.container(width + 100, 5);
  1298. this.x = this.add.image(0, 0, 'x');
  1299. this.xx = this.add.image(22, 0, 'xx');
  1300. this.xxx = this.add.image(49, 0, 'xxx');
  1301. this.xxxGroup.add([this.x, this.xx, this.xxx]);
  1302. this.tweens.add({
  1303. targets: this.xxxGroup,
  1304. x: width - 86,
  1305. duration: 300,
  1306. ease: 'Sine.InOut'
  1307. });
  1308. }
  1309. startFruit() {
  1310. // 根据分数动态调整数量:分数越高,生成越多水果
  1311. let min = 1;
  1312. let max = 1;
  1313. if (this.score >= 0 && this.score < 30) {
  1314. min = 1;
  1315. max = 1;
  1316. } else if (this.score >= 30 && this.score < 60) {
  1317. min = 1;
  1318. max = 2;
  1319. } else {
  1320. min = 2;
  1321. max = 3;
  1322. }
  1323. const number = Math.floor(mathTool.randomMinMax(min, max + 1)); // +1是因为randomMinMax的max是 exclusive
  1324. const hasBomb = Math.random() > 0.9;
  1325. const bombIndex = hasBomb ? Math.floor(Math.random() * number) : -1;
  1326. for (let i = 0; i < number; i++) {
  1327. if (i === bombIndex) {
  1328. this.fruits.push(this.randomFruit(false));
  1329. } else {
  1330. this.fruits.push(this.randomFruit(true));
  1331. }
  1332. }
  1333. }
  1334. randomFruit(isFruit) {
  1335. const fruitArray = ["apple", "banana", "basaha", "peach", "sandia"];
  1336. const index = Math.floor(Math.random() * fruitArray.length);
  1337. const x = mathTool.randomPosX();
  1338. const y = mathTool.randomPosY();
  1339. const vx = mathTool.randomVelocityX(x);
  1340. const vy = mathTool.randomVelocityY();
  1341. let fruit;
  1342. if (isFruit) {
  1343. fruit = new Fruit({
  1344. scene: this,
  1345. key: fruitArray[index],
  1346. x: x,
  1347. y: y
  1348. });
  1349. } else {
  1350. fruit = new Bomb({
  1351. scene: this,
  1352. x: x,
  1353. y: y
  1354. });
  1355. }
  1356. console.log("isFruitisFruitisFruit", isFruit)
  1357. fruit.isFruit = isFruit;
  1358. const sprite = fruit.getSprite();
  1359. if (sprite.body) {
  1360. sprite.body.velocity.x = vx;
  1361. sprite.body.velocity.y = vy;
  1362. sprite.body.gravity.y = this.gravity;
  1363. }
  1364. return fruit;
  1365. }
  1366. onOut(fruit) {
  1367. const sprite = fruit.getSprite();
  1368. let x, y;
  1369. // 确定失去标记的位置
  1370. if (sprite.y > height) {
  1371. x = sprite.x;
  1372. y = height - 30;
  1373. } else if (sprite.x < 0) {
  1374. x = 30;
  1375. y = sprite.y;
  1376. } else {
  1377. x = width - 30;
  1378. y = sprite.y;
  1379. }
  1380. // 创建失去标记动画
  1381. const lose = this.add.sprite(x, y, 'lose');
  1382. lose.setOrigin(0.5, 0.5);
  1383. lose.setScale(0);
  1384. const tweenShow = this.tweens.add({
  1385. targets: lose,
  1386. scale: 1,
  1387. duration: 300,
  1388. ease: 'Sine.InOut',
  1389. paused: true
  1390. });
  1391. const tweenHide = this.tweens.add({
  1392. targets: lose,
  1393. scale: 0,
  1394. duration: 300,
  1395. ease: 'Sine.InOut',
  1396. paused: true,
  1397. delay: 1000
  1398. });
  1399. this.tweens.chain({
  1400. targets: lose,
  1401. tweens: [
  1402. {
  1403. scale: 1,
  1404. duration: 300,
  1405. ease: 'Sine.InOut'
  1406. },
  1407. {
  1408. scale: 0,
  1409. duration: 300,
  1410. ease: 'Sine.InOut',
  1411. delay: 1000,
  1412. onComplete: () => {
  1413. lose.destroy();
  1414. }
  1415. }
  1416. ]
  1417. });
  1418. tweenShow.play();
  1419. tweenHide.on('complete', () => {
  1420. lose.destroy();
  1421. });
  1422. this.lostCount++;
  1423. this.loseCount();
  1424. }
  1425. onKill(fruit) {
  1426. const deg = this.blade.collideDeg();
  1427. fruit.half(deg, true);
  1428. this.score++;
  1429. this.scoreText.setText(this.score.toString());
  1430. }
  1431. onBomb(bomb) {
  1432. this.bombExplode = true;
  1433. // 屏幕震动效果
  1434. this.shakeScreen();
  1435. // 停止所有水果的物理运动
  1436. this.fruits.forEach(fruit => {
  1437. if (fruit.getSprite() && fruit.getSprite().body) {
  1438. fruit.getSprite().body.setVelocity(0);
  1439. fruit.getSprite().body.setGravity(0);
  1440. }
  1441. });
  1442. // 炸弹爆炸
  1443. bomb.explode(
  1444. () => {
  1445. // 白屏显示时的回调:销毁所有水果
  1446. this.fruits.forEach(fruit => {
  1447. if (fruit.getSprite()) {
  1448. fruit.getSprite().destroy();
  1449. }
  1450. });
  1451. this.fruits = [];
  1452. },
  1453. () => {
  1454. // 爆炸完成后的回调
  1455. this.gameOver();
  1456. }
  1457. );
  1458. }
  1459. // 添加屏幕震动方法
  1460. shakeScreen() {
  1461. // 获取主相机
  1462. const camera = this.cameras.main;
  1463. // 保存相机初始位置
  1464. const startX = camera.x;
  1465. const startY = camera.y;
  1466. // 震动持续时间(ms)
  1467. const duration = 2000;
  1468. // 震动强度
  1469. const intensity = 8;
  1470. // 震动频率控制
  1471. const frequency = 20;
  1472. // 计算震动次数
  1473. const shakes = duration / frequency;
  1474. let shakeCount = 0;
  1475. // 创建震动定时器
  1476. const shakeInterval = setInterval(() => {
  1477. if (shakeCount < shakes) {
  1478. // 随机生成震动偏移量
  1479. const offsetX = Phaser.Math.Between(-intensity, intensity);
  1480. const offsetY = Phaser.Math.Between(-intensity, intensity);
  1481. // 应用震动
  1482. camera.setPosition(startX + offsetX, startY + offsetY);
  1483. shakeCount++;
  1484. } else {
  1485. // 震动结束,恢复相机位置
  1486. clearInterval(shakeInterval);
  1487. camera.setPosition(startX, startY);
  1488. }
  1489. }, frequency);
  1490. }
  1491. loseCount() {
  1492. if (this.lostCount === 1) {
  1493. this.lostAnim(this.x, 'xf');
  1494. } else if (this.lostCount === 2) {
  1495. this.lostAnim(this.xx, 'xxf');
  1496. } else if (this.lostCount >= 3) {
  1497. this.lostAnim(this.xxx, 'xxxf');
  1498. this.gameOver();
  1499. }
  1500. }
  1501. lostAnim(removeObj, addKey) {
  1502. removeObj.destroy();
  1503. const newObj = this.add.sprite(removeObj.x, removeObj.y, addKey);
  1504. newObj.setOrigin(0, 0);
  1505. newObj.setScale(0);
  1506. this.xxxGroup.add(newObj);
  1507. this.tweens.add({
  1508. targets: newObj,
  1509. scale: 1,
  1510. duration: 300,
  1511. ease: 'Sine.InOut'
  1512. });
  1513. }
  1514. gameOver() {
  1515. this.playing = false;
  1516. // 1. 确保所有其他元素停止更新,避免干扰
  1517. this.blade.allowBlade = false; // 禁用刀光
  1518. // 2. 创建game-over图片,并设置最高层级
  1519. const gameOverSprite = this.add.sprite(width / 2, height / 2, 'game-over');
  1520. gameOverSprite.setOrigin(0.5, 0.5);
  1521. gameOverSprite.setScale(0);
  1522. gameOverSprite.setDepth(1000); // 设置最高层级,确保不被覆盖
  1523. // 3. 优化入场动画,确保平滑显示
  1524. this.tweens.add({
  1525. targets: gameOverSprite,
  1526. scale: 1,
  1527. duration: 500, // 延长动画时间,确保可见
  1528. ease: 'Elastic.Out', // 更明显的弹性动画,增强视觉效果
  1529. onComplete: () => {
  1530. // 动画完成后再设置自动返回,确保用户有足够时间看到画面
  1531. setTimeout(() => {
  1532. console.log('游戏结束,返回首页');
  1533. this.scene.start('main');
  1534. }, 1000); // 延长至3秒,给用户足够时间观察
  1535. }
  1536. });
  1537. // 4. 支持点击立即返回,提升交互体验
  1538. gameOverSprite.setInteractive();
  1539. gameOverSprite.on('pointerdown', () => {
  1540. console.log('点击返回首页');
  1541. this.scene.start('main');
  1542. });
  1543. }
  1544. }
  1545. // 外部方法(如Vue组件中的某个按钮点击事件)
  1546. const externalMethod = (autoX, autoY) => {
  1547. // 1. 获取游戏实例(从之前保存的gameRef中)
  1548. const game = gameRef.value;
  1549. if (!game) {
  1550. console.error("游戏未初始化");
  1551. return;
  1552. }
  1553. // 2. 获取目标场景(根据当前活跃场景选择'main'或'play')
  1554. // 例如:获取PlayScene(场景key为'play')
  1555. const currentScene = getActiveScene();
  1556. const targetScene = game.scene.getScene(currentScene);
  1557. // 若当前在主场景,可改为 game.scene.getScene('main')
  1558. // 3. 检查场景中的Blade实例是否存在且已启用
  1559. if (!targetScene || !targetScene.blade || !targetScene.blade.allowBlade) {
  1560. console.error("Blade实例未初始化或未启用");
  1561. return;
  1562. }
  1563. // 4. 构造模拟的pointer参数(包含x和y)
  1564. const mockPointer = {
  1565. x: autoX, // 外部传入的X坐标
  1566. y: autoY // 外部传入的Y坐标
  1567. };
  1568. // 5. 调用Blade的handleMouseMove方法
  1569. targetScene.blade.handleMouseMove(mockPointer);
  1570. };
  1571. // 新增:区分左右手的输入方法
  1572. const externalLeftHandMethod = (x, y) => {
  1573. const game = gameRef.value;
  1574. if (!game) return;
  1575. const currentScene = getActiveScene();
  1576. const targetScene = game.scene.getScene(currentScene);
  1577. if (targetScene && targetScene.leftBlade && targetScene.leftBlade.allowBlade) {
  1578. targetScene.leftBlade.handleMouseMove({ x, y });
  1579. }
  1580. };
  1581. const externalRightHandMethod = (x, y) => {
  1582. const game = gameRef.value;
  1583. if (!game) return;
  1584. const currentScene = getActiveScene();
  1585. const targetScene = game.scene.getScene(currentScene);
  1586. if (targetScene && targetScene.rightBlade && targetScene.rightBlade.allowBlade) {
  1587. targetScene.rightBlade.handleMouseMove({ x, y });
  1588. }
  1589. };
  1590. const getActiveScene = () => {
  1591. const game = gameRef.value; // 获取游戏实例
  1592. if (!game) return null;
  1593. // 获取所有活跃场景(通常只有一个)
  1594. const activeScenes = game.scene.getScenes(true);
  1595. // 返回第一个活跃场景(如果有)
  1596. return activeScenes.length > 0 ? activeScenes[0].scene.key : null;
  1597. };
  1598. onBeforeMount(() => {
  1599. clientObj.value = {
  1600. width: document.documentElement.clientWidth,
  1601. height: document.documentElement.clientHeight,
  1602. }
  1603. scaleRatio.value = clientObj.value.height / 480
  1604. getInit();
  1605. });
  1606. // 初始化游戏
  1607. onMounted(() => {
  1608. // 获取容器尺寸
  1609. const container = document.getElementById('game');
  1610. // 初始化工具类
  1611. mathTool.init();
  1612. // 创建游戏实例
  1613. game = new Phaser.Game({
  1614. type: Phaser.CANVAS,
  1615. width: width,
  1616. height: height,
  1617. parent: 'game',
  1618. scene: [BootScene, PreloadScene, MainScene, PlayScene],
  1619. physics: {
  1620. default: 'arcade',
  1621. arcade: {
  1622. debug: false
  1623. }
  1624. }
  1625. });
  1626. gameRef.value = game;
  1627. // 模拟自动接收坐标数据(例如WebSocket回调)
  1628. function onReceiveCoordinate(data) {
  1629. // data格式:{ x: 100, y: 200 }
  1630. if (data.x !== undefined && data.y !== undefined) {
  1631. externalMethod(data.x, data.y); // 调用外部方法,传入坐标
  1632. }
  1633. }
  1634. // // 示例:每50ms发送一组随机坐标
  1635. // setInterval(() => {
  1636. // const randomX = Math.random() * width; // width是屏幕宽度
  1637. // const randomY = Math.random() * height; // height是屏幕高度
  1638. // onReceiveCoordinate({ x: randomX, y: randomY });
  1639. // }, 50);
  1640. });
  1641. onBeforeUnmount(() => {
  1642. closeWS();
  1643. });
  1644. </script>
  1645. <style lang="scss" scoped></style>