MapGame.vue 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261
  1. <template>
  2. <div class="map-game-container">
  3. <!-- 标题栏 -->
  4. <div class="title-box">
  5. <div class="box-icon" @click="navigateBack">
  6. <el-icon class="left-icon"><ArrowLeftBold /></el-icon>
  7. {{ gameTitle }}
  8. </div>
  9. <!-- 游戏编号 -->
  10. <div class="game-badge">{{ gameSort }}</div>
  11. </div>
  12. <div class="content">
  13. <!-- 地图显示区域 -->
  14. <div class="map-section">
  15. <!-- 内容简介提示 -->
  16. <div class="info-message-container">
  17. <div class="message-item">
  18. <div class="avatar">
  19. <img src="@/assets/images/xiaozhi2.png" alt="头像" class="avatar-image" />
  20. </div>
  21. <p v-html="currentGameData?.info"></p>
  22. </div>
  23. </div>
  24. <div class="map-container">
  25. <!-- 地图背景 -->
  26. <div class="map-background">
  27. <img :src="mapBackground" alt="地图背景" class="map-image" />
  28. <!-- 可行走区域标记 -->
  29. <div
  30. v-for="(point, index) in walkablePoints"
  31. :key="index"
  32. class="walkable-point"
  33. :style="getPointStyle(point)"
  34. ></div>
  35. <!-- 玩家角色 -->
  36. <div
  37. class="player"
  38. :style="playerStyle"
  39. :class="{ 'collision': isColliding, 'success': hasReachedEnd }"
  40. ></div>
  41. </div>
  42. <!-- 游戏状态提示 -->
  43. <div v-if="gameMessage" :class="['game-message', messageType]">
  44. {{ gameMessage }}
  45. </div>
  46. </div>
  47. </div>
  48. <!-- Blockly工作区 -->
  49. <div class="blockly-section">
  50. <div class="toolbox-section" style="display: none;">
  51. <h2>工具箱</h2>
  52. <div id="toolbox">
  53. <!-- 移动控制积木 -->
  54. <category name="移动控制" colour="%{BKY_MOTION_HUE}">
  55. <block type="move_forward"></block>
  56. <block type="move_backward"></block>
  57. <block type="turn_left"></block>
  58. <block type="turn_right"></block>
  59. <block type="turn_around"></block>
  60. </category>
  61. <!-- 逻辑控制积木 -->
  62. <category name="逻辑" colour="%{BKY_LOGIC_HUE}">
  63. <block type="controls_if"></block>
  64. <block type="logic_compare"></block>
  65. <block type="logic_operation"></block>
  66. <block type="logic_negate"></block>
  67. <block type="logic_boolean"></block>
  68. </category>
  69. <!-- 循环控制积木 -->
  70. <category name="循环" colour="%{BKY_LOOPS_HUE}">
  71. <block type="controls_repeat_ext">
  72. <value name="TIMES">
  73. <shadow type="math_number">
  74. <field name="NUM"></field>
  75. </shadow>
  76. </value>
  77. </block>
  78. <block type="controls_whileUntil"></block>
  79. </category>
  80. <!-- 数学运算积木 -->
  81. <category name="数学" colour="%{BKY_MATH_HUE}">
  82. <block type="math_number"></block>
  83. <block type="math_arithmetic"></block>
  84. </category>
  85. </div>
  86. </div>
  87. <div class="workspace-section">
  88. <div class="controls">
  89. <button id="runCode" @click="runCode">运行代码</button>
  90. <button @click="clearWorkspace">清空工作区</button>
  91. <button @click="resetPlayer">重置玩家</button>
  92. </div>
  93. <div id="blocklyDiv"></div>
  94. </div>
  95. </div>
  96. </div>
  97. </div>
  98. </template>
  99. <script setup>
  100. import { ref, onMounted, onUnmounted, reactive, computed } from 'vue';
  101. import { useRouter, useRoute } from 'vue-router';
  102. import { ArrowLeftBold } from '@element-plus/icons-vue';
  103. import * as Blockly from "blockly";
  104. import 'blockly/msg/zh-hans';
  105. import { javascriptGenerator } from "blockly/javascript";
  106. import mapBackgroundImage from '@/assets/images/blockly/mapGame.png';
  107. import playerImage from '@/assets/images/blockly/user.png';
  108. // 游戏接口数据
  109. import { getMapGameById } from '@/api/blockly/game.js';
  110. const router = useRouter();
  111. const route = useRoute();
  112. const gameTitle = ref('地图游戏编程'); // 默认标题
  113. const gameSort = ref('Game1'); // 默认排序
  114. const currentGameData = ref(null);
  115. //人物初始朝向
  116. const playerInitialDirection = ref(0);
  117. onMounted(async () => {
  118. //数据
  119. await fetchGameData();
  120. // 初始化可行走点集合
  121. initWalkablePointsSet();
  122. // 注册自定义积木
  123. registerCustomBlocks();
  124. // 注册JavaScript生成器
  125. registerJavaScriptGenerators();
  126. // 初始化Blockly工作区
  127. initBlockly();
  128. // 重置玩家位置
  129. resetPlayer();
  130. // 获取路由参数中的gameName
  131. const nameFromRoute = route.query.gameName;
  132. if (nameFromRoute) {
  133. gameTitle.value = nameFromRoute;
  134. }
  135. })
  136. // 获取游戏数据
  137. const fetchGameData = async () => {
  138. try {
  139. const gameId = route.query.gameId;
  140. const nameFromRoute = route.query.gameName;
  141. const sortFromRoute = route.query.gameSort;
  142. if (nameFromRoute) {
  143. gameTitle.value = nameFromRoute;
  144. }
  145. // 优先使用路由参数中的排序信息
  146. if (sortFromRoute) {
  147. gameSort.value = sortFromRoute;
  148. }
  149. let mapGameData = await getMapGameById(gameId);
  150. if (mapGameData.code === 0) {
  151. currentGameData.value = mapGameData?.data;
  152. // 使用接口数据
  153. if (currentGameData.value && currentGameData.value.sort) {
  154. let sortNum = currentGameData.value.sort;
  155. gameSort.value = sortNum > 9 ? `Game${sortNum}` : `Game${sortNum}`;
  156. }
  157. updateGameStateFromData(currentGameData.value);
  158. }
  159. } catch (error) {
  160. console.error('获取游戏数据失败:', error);
  161. }
  162. };
  163. // 根据获取到的数据更新游戏状态
  164. const updateGameStateFromData = (gameData) => {
  165. try {
  166. // 更新地图配置
  167. gameState.mapConfig.background = gameData.mapBackground ? gameData.mapBackground.trim() : mapBackgroundImage;
  168. gameState.mapConfig.tileSize = gameData.mapTileSize;
  169. // 更新玩家位置和方向
  170. if (gameData.userDirection) {
  171. playerInitialDirection.value = gameData.userDirection;
  172. }
  173. // 更新地图数据
  174. // 地图起点
  175. if (gameData.mapStartPoint) {
  176. const startPoint = JSON.parse(gameData.mapStartPoint);
  177. gameState.mapData.startPoint = { x: startPoint.x, y: startPoint.y };
  178. gameState.player.position = { x: startPoint.x, y: startPoint.y };
  179. }
  180. // 地图终点
  181. if (gameData.mapEndPoint) {
  182. const endPoint = JSON.parse(gameData.mapEndPoint);
  183. gameState.mapData.endPoint = { x: endPoint.x, y: endPoint.y };
  184. }
  185. if (gameData.mapWalkablePoints) {
  186. gameState.mapData.walkablePoints = JSON.parse(gameData.mapWalkablePoints);
  187. }
  188. // 重新初始化可行走点集合
  189. initWalkablePointsSet();
  190. } catch (error) {
  191. console.error('更新游戏状态失败:', error);
  192. }
  193. };
  194. // 创建游戏状态的响应式对象
  195. const gameState = reactive({
  196. // 地图配置信息
  197. mapConfig: {
  198. // 地图背景图片路径
  199. background: mapBackgroundImage,
  200. // 每个瓦片的尺寸(像素)
  201. tileSize: 110,
  202. },
  203. // 玩家相关状态
  204. player: {
  205. // 玩家当前位置坐标
  206. position: { x: 1, y: 1 },
  207. // 玩家当前朝向:0=上, 1=右, 2=下, 3=左
  208. direction: 1,
  209. // 是否正在发生碰撞
  210. isColliding: false,
  211. // 是否已到达终点
  212. hasReachedEnd: false,
  213. // 是否正在冰块上滑行
  214. isSliding: false,
  215. },
  216. // 游戏状态信息
  217. status: {
  218. // 当前显示的游戏消息
  219. message: '',
  220. // 消息类型(如success、error、info等)
  221. messageType: ''
  222. },
  223. // 地图数据信息
  224. mapData: {
  225. // 游戏起点位置
  226. startPoint: { x: 1, y: 1 },
  227. // 游戏终点位置
  228. endPoint: { x: 4, y: 3 },
  229. // 地图上所有可行走的点坐标集合,添加type属性区分普通点和冰块
  230. walkablePoints: [
  231. { x: 1, y: 1, type: 'ice' }, { x: 2, y: 1, type: 'ice' }, { x: 3, y: 1 }, { x: 4, y: 1 },
  232. { x: 1, y: 2 }, { x: 2, y: 2 }, { x: 3, y: 2, type: 'ice' }, { x: 4, y: 2 },
  233. { x: 1, y: 3 }, { x: 2, y: 3 }, { x: 3, y: 3 }, { x: 4, y: 3 },
  234. { x: 4, y: 3 },
  235. ],
  236. }
  237. });
  238. // 计算属性 - 提高性能和可读性
  239. const mapBackground = computed(() => gameState.mapConfig.background);
  240. const tileSize = computed(() => gameState.mapConfig.tileSize);
  241. const walkablePoints = computed(() => gameState.mapData.walkablePoints);
  242. const startPoint = computed(() => gameState.mapData.startPoint);
  243. const endPoint = computed(() => gameState.mapData.endPoint);
  244. const playerPosition = computed(() => gameState.player.position);
  245. const playerDirection = computed(() => gameState.player.direction);
  246. const isColliding = computed(() => gameState.player.isColliding);
  247. const hasReachedEnd = computed(() => gameState.player.hasReachedEnd);
  248. const gameMessage = computed(() => gameState.status.message);
  249. const messageType = computed(() => gameState.status.messageType);
  250. // 计算玩家图片路径,优先使用接口数据
  251. const playerImageSrc = computed(() => {
  252. if (currentGameData.value && currentGameData.value.userImage) {
  253. return currentGameData.value.userImage.trim();
  254. }
  255. return playerImage;
  256. });
  257. const isSliding = computed(() => gameState.player.isSliding);
  258. // Blockly相关状态
  259. let workspace = null;
  260. // 使用 Map 存储可行走点及其类型,提高查询效率
  261. let walkablePointsMap = new Map();
  262. // 初始化可行走点映射
  263. function initWalkablePointsSet() {
  264. walkablePointsMap.clear();
  265. gameState.mapData.walkablePoints.forEach(point => {
  266. walkablePointsMap.set(`${point.x},${point.y}`, point.type);
  267. });
  268. }
  269. // 可行走检查函数
  270. function isWalkable(x, y) {
  271. return walkablePointsMap.has(`${x},${y}`);
  272. }
  273. // 检查是否是冰块点 - 基于walkablePoints中的type属性
  274. function isIce(x, y) {
  275. return walkablePointsMap.get(`${x},${y}`) === 'ice';
  276. }
  277. // 计算点的样式
  278. function getPointStyle(point) {
  279. // 检查是否是冰块点,添加不同的样式
  280. const isIcePoint = isIce(point.x, point.y);
  281. return {
  282. left: point.x * tileSize.value - tileSize.value + 'px',
  283. top: point.y * tileSize.value - tileSize.value + 'px',
  284. width: tileSize.value + 'px',
  285. height: tileSize.value + 'px',
  286. backgroundColor: isIcePoint ? 'rgba(144, 202, 249, 0.5)' : 'rgba(52, 152, 219, 0.2)',
  287. border: isIcePoint ? '1px solid rgba(33, 150, 243, 0.8)' : '1px solid rgba(52, 152, 219, 0.5)',
  288. boxShadow: isIcePoint ? '0 0 10px rgba(33, 150, 243, 0.5)' : 'none',
  289. };
  290. }
  291. // 计算玩家样式
  292. const playerStyle = computed(() => ({
  293. left: playerPosition.value.x * tileSize.value - tileSize.value + 'px',
  294. top: playerPosition.value.y * tileSize.value - tileSize.value + 'px',
  295. transform: `rotate(${playerDirection.value * 90}deg)`,
  296. '--player-rotation': `${playerDirection.value * 90}deg`,
  297. '--player-image': `url(${playerImageSrc.value})`,
  298. width: (tileSize.value * 0.8) + 'px',
  299. height: (tileSize.value * 0.8) + 'px',
  300. margin: (tileSize.value * 0.1) + 'px',
  301. }));
  302. // 显示游戏消息
  303. function showGameMessage(message, type = 'info') {
  304. gameState.status.message = message;
  305. gameState.status.messageType = type;
  306. // 3秒后自动清除消息
  307. setTimeout(() => {
  308. gameState.status.message = '';
  309. }, 3000);
  310. }
  311. // 导航返回
  312. function navigateBack() {
  313. router.back();
  314. }
  315. // 注册自定义积木
  316. function registerCustomBlocks() {
  317. // 向前移动积木
  318. Blockly.Blocks['move_forward'] = {
  319. init: function() {
  320. this.jsonInit({
  321. "type": "move_forward",
  322. "message0": "向前移动",
  323. "previousStatement": null,
  324. "nextStatement": null,
  325. "colour": 230,
  326. "tooltip": "控制角色向前移动一格",
  327. "helpUrl": ""
  328. });
  329. }
  330. };
  331. // 向后移动积木
  332. Blockly.Blocks['move_backward'] = {
  333. init: function() {
  334. this.jsonInit({
  335. "type": "move_backward",
  336. "message0": "向后移动",
  337. "previousStatement": null,
  338. "nextStatement": null,
  339. "colour": 230,
  340. "tooltip": "控制角色向后移动一格",
  341. "helpUrl": ""
  342. });
  343. }
  344. };
  345. // 向左转积木
  346. Blockly.Blocks['turn_left'] = {
  347. init: function() {
  348. this.jsonInit({
  349. "type": "turn_left",
  350. "message0": "向左转",
  351. "previousStatement": null,
  352. "nextStatement": null,
  353. "colour": 230,
  354. "tooltip": "控制角色向左转",
  355. "helpUrl": ""
  356. });
  357. }
  358. };
  359. // 向右转积木
  360. Blockly.Blocks['turn_right'] = {
  361. init: function() {
  362. this.jsonInit({
  363. "type": "turn_right",
  364. "message0": "向右转",
  365. "previousStatement": null,
  366. "nextStatement": null,
  367. "colour": 230,
  368. "tooltip": "控制角色向右转",
  369. "helpUrl": ""
  370. });
  371. }
  372. };
  373. // 向后转积木
  374. Blockly.Blocks['turn_around'] = {
  375. init: function() {
  376. this.jsonInit({
  377. "type": "turn_around",
  378. "message0": "向后转",
  379. "previousStatement": null,
  380. "nextStatement": null,
  381. "colour": 230,
  382. "tooltip": "控制角色向后转",
  383. "helpUrl": ""
  384. });
  385. }
  386. };
  387. }
  388. // 注册JavaScript生成器
  389. function registerJavaScriptGenerators() {
  390. // 向前移动生成器
  391. javascriptGenerator.forBlock['move_forward'] = function(block) {
  392. return 'await moveForward();\n';
  393. };
  394. // 向后移动生成器
  395. javascriptGenerator.forBlock['move_backward'] = function(block) {
  396. return 'await moveBackward();\n';
  397. };
  398. // 向左转生成器
  399. javascriptGenerator.forBlock['turn_left'] = function(block) {
  400. return 'await turnLeft();\n';
  401. };
  402. // 向右转生成器
  403. javascriptGenerator.forBlock['turn_right'] = function(block) {
  404. return 'await turnRight();\n';
  405. };
  406. // 向后转生成器
  407. javascriptGenerator.forBlock['turn_around'] = function(block) {
  408. return 'await turnAround();\n';
  409. };
  410. // 为重复循环块注册自定义生成器,确保支持异步操作
  411. javascriptGenerator.forBlock['controls_repeat_ext'] = function(block) {
  412. const repeats = javascriptGenerator.valueToCode(block, 'TIMES', javascriptGenerator.ORDER_ATOMIC) || '0';
  413. // 确保获取到的是数字类型,如果是字符串需要转换
  414. const safeRepeats = `(function() {
  415. const num = Number(${repeats});
  416. return isNaN(num) ? 0 : Math.max(0, Math.floor(num));
  417. })()`;
  418. // 获取循环体代码
  419. const branch = javascriptGenerator.statementToCode(block, 'DO');
  420. // 生成支持异步的循环代码
  421. let code = `for (let i = 0; i < ${safeRepeats}; i++) {\n`;
  422. code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT);
  423. code += '}\n';
  424. return code;
  425. };
  426. // 为while/until循环块注册自定义生成器
  427. javascriptGenerator.forBlock['controls_whileUntil'] = function(block) {
  428. const until = block.getFieldValue('MODE') === 'UNTIL';
  429. const condition = javascriptGenerator.valueToCode(block, 'CONDITION',
  430. javascriptGenerator.ORDER_NONE) || 'false';
  431. const branch = javascriptGenerator.statementToCode(block, 'DO');
  432. // 修复变量作用域问题,使用IIFE包装循环
  433. let code = '(async function() {\n';
  434. code += ' let loopCount = 0;\n';
  435. code += until ? ' while (!((' + condition + ')) && loopCount < 100) {\n' :
  436. ' while (((' + condition + ')) && loopCount < 100) {\n';
  437. code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT + ' ');
  438. code += ' loopCount++';
  439. code += ' await new Promise(resolve => setTimeout(resolve, 10));\n'; // 防止UI阻塞
  440. code += ' }\n';
  441. code += '})();\n';
  442. return code;
  443. };
  444. // 为text_print块添加生成器,用于调试
  445. javascriptGenerator.forBlock['text_print'] = function(block) {
  446. const msg = javascriptGenerator.valueToCode(block, 'TEXT', javascriptGenerator.ORDER_NONE) || '';
  447. return msg;
  448. };
  449. }
  450. // 初始化Blockly工作区
  451. function initBlockly() {
  452. const toolbox = document.getElementById('toolbox');
  453. workspace = Blockly.inject('blocklyDiv', {
  454. toolbox: toolbox,
  455. collapse: true,
  456. comments: true,
  457. disable: false, // 设为false以允许编辑
  458. maxBlocks: Infinity,
  459. trashcan: true,
  460. horizontalLayout: false,
  461. toolboxPosition: 'start',
  462. css: true,
  463. media: 'https://unpkg.com/blockly/media/',
  464. rtl: false,
  465. scrollbars: true,
  466. sounds: false, // 禁用声音以提高性能
  467. oneBasedIndex: true,
  468. grid: {
  469. spacing: 20,
  470. length: 3,
  471. colour: "#ccc",
  472. snap: true
  473. },
  474. zoom: {
  475. controls: true,
  476. wheel: true,
  477. startScale: 1.0,
  478. maxScale: 3,
  479. minScale: 0.3,
  480. scaleSpeed: 1.2
  481. }
  482. });
  483. }
  484. // 平滑移动函数
  485. async function smoothMoveTo(targetX, targetY) {
  486. const startX = playerPosition.value.x;
  487. const startY = playerPosition.value.y;
  488. const duration = 500; // 移动动画持续时间(毫秒)
  489. const startTime = performance.now();
  490. // 使用 requestAnimationFrame 实现平滑动画
  491. return new Promise(resolve => {
  492. function animate(currentTime) {
  493. const elapsedTime = currentTime - startTime;
  494. // 计算进度,确保不会超过1
  495. const progress = Math.min(elapsedTime / duration, 1);
  496. // 使用缓动函数使动画更自然
  497. const easedProgress = progress * (2 - progress); // easeOutQuad 缓动
  498. // 计算当前位置
  499. const currentX = startX + (targetX - startX) * easedProgress;
  500. const currentY = startY + (targetY - startY) * easedProgress;
  501. // 更新玩家位置
  502. gameState.player.position = { x: currentX, y: currentY };
  503. // 如果动画未完成,继续下一帧
  504. if (progress < 1) {
  505. requestAnimationFrame(animate);
  506. } else {
  507. // 动画完成后解析Promise
  508. resolve();
  509. }
  510. }
  511. // 开始动画
  512. requestAnimationFrame(animate);
  513. });
  514. }
  515. // 创建通用的移动函数
  516. async function move(direction) {
  517. if (isColliding.value || isSliding.value) {
  518. return;
  519. }
  520. let newX = playerPosition.value.x;
  521. let newY = playerPosition.value.y;
  522. // 根据当前方向和移动类型计算新位置
  523. if (direction === 1) {
  524. // 向前移动
  525. switch(playerDirection.value) {
  526. case 0: newY--; break;
  527. case 1: newX++; break;
  528. case 2: newY++; break;
  529. case 3: newX--; break;
  530. }
  531. } else {
  532. // 向后移动
  533. switch(playerDirection.value) {
  534. case 0: newY++; break;
  535. case 1: newX--; break;
  536. case 2: newY--; break;
  537. case 3: newX++; break;
  538. }
  539. }
  540. // 检查是否可以移动
  541. if (isWalkable(newX, newY)) {
  542. // 使用平滑移动动画
  543. await smoothMoveTo(newX, newY);
  544. // 检查新位置是否是冰块,如果是则触发滑行
  545. if (isIce(newX, newY)) {
  546. await handleIceSliding();
  547. }
  548. } else {
  549. // 发生碰撞
  550. gameState.player.isColliding = true;
  551. showGameMessage('哎呀,撞到墙了!', 'error');
  552. // 立即中止整个代码执行
  553. if (executionAbortController) {
  554. executionAbortController.abort();
  555. }
  556. // 1秒后取消碰撞状态
  557. setTimeout(() => {
  558. gameState.player.isColliding = false;
  559. }, 1000);
  560. // 添加碰撞延迟
  561. await new Promise(resolve => setTimeout(resolve, 500));
  562. }
  563. }
  564. // 处理冰块滑行逻辑
  565. async function handleIceSliding() {
  566. gameState.player.isSliding = true;
  567. try {
  568. // 循环检查是否可以继续滑行
  569. while (true) {
  570. // 计算下一个位置
  571. let nextX = playerPosition.value.x;
  572. let nextY = playerPosition.value.y;
  573. // 根据当前方向计算下一个位置
  574. switch(playerDirection.value) {
  575. case 0: nextY--; break;
  576. case 1: nextX++; break;
  577. case 2: nextY++; break;
  578. case 3: nextX--; break;
  579. }
  580. // 检查下一个位置是否可行走
  581. if (isWalkable(nextX, nextY)) {
  582. // 执行平滑移动到下一个位置
  583. await smoothMoveTo(nextX, nextY);
  584. // 检查下一个位置是否还是冰块
  585. if (!isIce(nextX, nextY)) {
  586. // 如果不是冰块,结束滑行
  587. break;
  588. }
  589. // 添加滑行间隔时间
  590. await new Promise(resolve => setTimeout(resolve, 500));
  591. } else {
  592. // 下一个位置不可行走,检查是否是墙体
  593. gameState.player.isColliding = true;
  594. showGameMessage('哎呀,撞到墙了!', 'error');
  595. // 立即中止整个代码执行
  596. if (executionAbortController) {
  597. executionAbortController.abort();
  598. }
  599. // 1秒后取消碰撞状态
  600. setTimeout(() => {
  601. gameState.player.isColliding = false;
  602. }, 1000);
  603. // 添加碰撞延迟
  604. await new Promise(resolve => setTimeout(resolve, 500));
  605. break;
  606. }
  607. }
  608. } catch (error) {
  609. console.error('滑行过程中发生错误:', error);
  610. } finally {
  611. // 无论如何都要确保滑行状态被重置
  612. gameState.player.isSliding = false;
  613. }
  614. }
  615. // 保留原有的API接口
  616. window.moveForward = async function() {
  617. await move(1);
  618. };
  619. window.moveBackward = async function() {
  620. await move(-1);
  621. };
  622. //向左转(逆时针旋转90度)
  623. window.turnLeft = async function() {
  624. // 如果已经发生过碰撞,不再执行任何旋转
  625. if (isColliding.value) {
  626. return;
  627. }
  628. // 向左转(逆时针旋转90度)
  629. gameState.player.direction = (playerDirection.value - 1 + 4) % 4;
  630. // 添加旋转延迟
  631. await new Promise(resolve => setTimeout(resolve, 500));
  632. };
  633. //向右转(顺时针旋转90度)
  634. window.turnRight = async function() {
  635. // 如果已经发生过碰撞,不再执行任何旋转
  636. if (isColliding.value) {
  637. return;
  638. }
  639. // 向右转(顺时针旋转90度)
  640. gameState.player.direction = (playerDirection.value + 1) % 4;
  641. // 添加旋转延迟
  642. await new Promise(resolve => setTimeout(resolve, 500));
  643. };
  644. // 向后转(旋转180度)
  645. window.turnAround = async function() {
  646. // 如果已经发生过碰撞,不再执行任何旋转
  647. if (isColliding.value) {
  648. return;
  649. }
  650. // 向后转(旋转180度)
  651. gameState.player.direction = (playerDirection.value + 2) % 4;
  652. // 添加旋转延迟
  653. await new Promise(resolve => setTimeout(resolve, 500));
  654. };
  655. //校验是否到达终点
  656. window.isFinish = async function() {
  657. // 如果已经发生过碰撞,不再执行任何旋转
  658. if (isColliding.value) {
  659. return;
  660. }
  661. if (gameState.player.position.x === endPoint.value.x && gameState.player.position.y === endPoint.value.y) {
  662. gameState.player.hasReachedEnd = true;
  663. showGameMessage('恭喜你到达终点!', 'success' );
  664. }
  665. };
  666. // 添加一个变量来跟踪当前执行的代码
  667. let currentExecutionPromise = null;
  668. let executionAbortController = null;
  669. // 运行代码
  670. const runCode = async () => {
  671. try {
  672. await resetPlayer();
  673. await new Promise(resolve => setTimeout(resolve, 500));
  674. // 创建新的AbortController用于取消执行
  675. executionAbortController = new AbortController();
  676. const signal = executionAbortController.signal;
  677. // 确保生成器和工作区都存在
  678. if (!javascriptGenerator || !workspace) {
  679. throw new Error('生成器或工作区未正确初始化');
  680. }
  681. // 生成JavaScript代码
  682. const code = javascriptGenerator.workspaceToCode(workspace) + "await isFinish();";
  683. try {
  684. // 增强的安全检查
  685. const unsafePatterns = [
  686. 'eval(', 'Function(', 'document.write', 'window.location',
  687. 'document.createElement', 'XMLHttpRequest', 'fetch',
  688. 'setInterval', 'setTimeout', 'window.',
  689. 'alert(', 'confirm(', 'prompt(',
  690. 'document.cookie', 'localStorage', 'sessionStorage'
  691. ];
  692. const hasUnsafeCode = unsafePatterns.some(pattern => code.includes(pattern));
  693. if (hasUnsafeCode) {
  694. throw new Error('代码包含不安全的操作');
  695. }
  696. // 包装代码为异步函数执行,并设置超时保护
  697. currentExecutionPromise = new Promise(async (resolve, reject) => {
  698. try {
  699. // 检查信号是否已中止
  700. if (signal.aborted) {
  701. throw new Error('执行已取消');
  702. }
  703. // 添加信号监听
  704. signal.addEventListener('abort', () => {
  705. reject(new Error('执行已取消'));
  706. });
  707. const wrappedCode = `(async () => { ${code} })()`;
  708. await new Function(wrappedCode)();
  709. resolve();
  710. } catch (error) {
  711. reject(error);
  712. }
  713. });
  714. } catch (error) {
  715. // 捕获并显示执行错误
  716. if (error.message !== '执行已取消') {
  717. const errorMsg = error.message || '未知错误';
  718. showGameMessage(`代码执行错误: ${errorMsg}`, 'error');
  719. console.error('代码执行错误:', error);
  720. }
  721. } finally {
  722. // 清除当前执行的Promise引用
  723. currentExecutionPromise = null;
  724. }
  725. } catch (error) {
  726. showGameMessage(`运行时错误: ${error.message || '未知错误'}`, 'error');
  727. console.error('运行时错误:', error);
  728. }
  729. };
  730. // 清空工作区
  731. const clearWorkspace = () => {
  732. workspace.clear();
  733. showGameMessage('工作区已清空', 'info');
  734. };
  735. // 重置玩家位置和状态
  736. const resetPlayer = () => {
  737. // 取消任何正在执行的代码
  738. if (executionAbortController) {
  739. executionAbortController.abort();
  740. executionAbortController = null;
  741. }
  742. if (currentExecutionPromise) {
  743. currentExecutionPromise = null;
  744. }
  745. gameState.player.position = { ...startPoint.value };
  746. gameState.player.direction = playerInitialDirection.value; // 重置为向上方向
  747. gameState.player.isColliding = false; //碰撞标志
  748. gameState.player.hasReachedEnd = false;
  749. gameState.player.isSliding = false; // 重置滑行状态
  750. };
  751. // 组件卸载时清理
  752. onUnmounted(() => {
  753. if (workspace) {
  754. workspace.dispose();
  755. }
  756. });
  757. </script>
  758. <style scoped lang="scss">
  759. @use "sass:math";
  760. @function rpx($px) {
  761. @return math.div($px, 750) * 100vw;
  762. }
  763. /* 信息提示框样式 */
  764. .info-message-container {
  765. display: flex;
  766. flex-direction: column;
  767. align-items: flex-start;
  768. }
  769. .message-item {
  770. display: flex;
  771. align-items: flex-start;
  772. width: 100%;
  773. margin-bottom: rpx(5);
  774. }
  775. /* 头像样式 */
  776. .avatar {
  777. margin-right: rpx(4);
  778. flex-shrink: 0;
  779. }
  780. .avatar-image {
  781. width: rpx(30);
  782. height: rpx(30);
  783. object-fit: cover;
  784. }
  785. /* 消息内容样式 */
  786. .message-item {
  787. flex: 1;
  788. }
  789. .message-item p {
  790. margin: rpx(4) 0;
  791. line-height: 1.6;
  792. font-size: rpx(7);
  793. text-align: left;
  794. color: black;
  795. background-color: #e6faff;
  796. opacity: 0.8;
  797. border-radius: rpx(4);
  798. padding: rpx(6);
  799. max-width: 100%;
  800. }
  801. .message-item p:first-child {
  802. margin-top: 0;
  803. font-weight: 500;
  804. }
  805. .message-item p:last-child {
  806. margin-bottom: 0;
  807. }
  808. //将tileSize属性绑定到CSS变量上
  809. :root {
  810. --tile-size: v-bind('tileSize + "px"');
  811. }
  812. .map-game-container {
  813. position: fixed;
  814. top: 0;
  815. left: 0;
  816. right: 0;
  817. bottom: 0;
  818. background: transparent;
  819. overflow-y: auto;
  820. }
  821. /* 自定义滚动条样式 */
  822. .map-game-container::-webkit-scrollbar {
  823. width: rpx(2); /* 滚动条宽度 */
  824. }
  825. .map-game-container::-webkit-scrollbar-track {
  826. background: #f1effd; /* 滚动条轨道背景色 */
  827. border-radius: rpx(4);
  828. }
  829. .map-game-container::-webkit-scrollbar-thumb {
  830. background: #e2ddfc; /* 滚动条滑块颜色 */
  831. border-radius: rpx(4);
  832. }
  833. .map-game-container::-webkit-scrollbar-thumb:hover {
  834. background: #e2ddfc; /* 滚动条滑块 hover 状态颜色 */
  835. }
  836. .title-box {
  837. position: relative;
  838. top: rpx(5);
  839. padding-left: 15px;
  840. // margin-bottom: 20px;
  841. z-index: 10;
  842. display: flex;
  843. flex-direction: column;
  844. }
  845. /* 右侧两个角为圆角的长方形格子样式 */
  846. .game-badge {
  847. width: rpx(80);
  848. height: rpx(20);
  849. margin-left: rpx(10);
  850. background-color: #5fb5dc;
  851. color: #fff;
  852. border-radius: 0 rpx(20) rpx(20) 0;
  853. display: flex;
  854. align-items: center;
  855. justify-content: center;
  856. font-size: rpx(15);
  857. font-weight: bold;
  858. }
  859. .box-icon {
  860. display: flex;
  861. align-items: center;
  862. gap: 10px;
  863. padding: 10px 20px;
  864. background-color: rgba(255, 255, 255, 0.8);
  865. border-radius: 30px;
  866. backdrop-filter: blur(10px);
  867. cursor: pointer;
  868. transition: all 0.3s ease;
  869. font-size: 16px;
  870. color: #333;
  871. font-weight: 500;
  872. width: fit-content;
  873. }
  874. .box-icon:hover {
  875. background-color: rgba(255, 255, 255, 0.9);
  876. transform: translate(-3px);
  877. }
  878. .left-icon {
  879. font-size: 18px;
  880. }
  881. .content {
  882. display: flex;
  883. flex-wrap: wrap;
  884. gap: 20px;
  885. padding: 20px;
  886. }
  887. /* 地图区域样式 */
  888. .map-section {
  889. flex: 1;
  890. min-width: 500px;
  891. background: rgba(248, 249, 250, 0.82);
  892. padding: 15px;
  893. border-radius: 15px;
  894. }
  895. .map-section h2 {
  896. margin-bottom: 15px;
  897. color: #2c3e50;
  898. border-bottom: 2px solid #3498db;
  899. padding-bottom: 8px;
  900. }
  901. .map-container {
  902. //position: relative;
  903. //width: 100%;
  904. //height: 100% ;
  905. //display: flex;
  906. //justify-content: center;
  907. //align-items: center;
  908. }
  909. .map-background {
  910. position: relative;
  911. width: 100%;
  912. height: 100%;
  913. background-size: cover;
  914. background-position: center;
  915. background-repeat: no-repeat;
  916. //margin: 0 auto;
  917. //border: 2px solid #ddd;
  918. //border-radius: 8px;
  919. //overflow: hidden;
  920. //background-color: #f0f0f0;
  921. }
  922. .map-image {
  923. width: 100%;
  924. height: 100%;
  925. object-fit: cover;
  926. }
  927. /* 可行走区域样式 */
  928. .walkable-point {
  929. position: absolute;
  930. background-color: rgba(52, 152, 219, 0.2);
  931. border: 1px solid rgba(52, 152, 219, 0.5);
  932. box-sizing: border-box;
  933. //是否显示可行路线
  934. opacity: 0;
  935. }
  936. /* 玩家样式 */
  937. .player {
  938. position: absolute;
  939. background-image: var(--player-image);
  940. background-size: contain;
  941. background-repeat: no-repeat;
  942. background-position: center;
  943. border-radius: 5px;
  944. transition: all 0.3s ease;
  945. z-index: 10;
  946. }
  947. /* 碰撞动画 */
  948. .player.collision {
  949. animation: collision 0.5s ease-in-out;
  950. }
  951. @keyframes collision {
  952. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  953. 25% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  954. 50% { transform: rotate(var(--player-rotation)) translateX(3px) translateY(2px) scale(1.2); }
  955. 75% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  956. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  957. }
  958. /* 滑行动画 */
  959. @keyframes sliding {
  960. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  961. 25% { transform: rotate(var(--player-rotation)) translateX(2px) translateY(0); }
  962. 75% { transform: rotate(var(--player-rotation)) translateX(-2px) translateY(0); }
  963. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  964. }
  965. /* 成功到达终点动画 */
  966. .player.success {
  967. animation: success 1s ease-in-out;
  968. }
  969. @keyframes success {
  970. 0% { transform: rotate(var(--player-rotation)) scale(1); }
  971. 10% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  972. 20% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  973. 30% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  974. 40% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  975. 50% { transform: rotate(var(--player-rotation)) scale(1.4) translateX(0) translateY(0); }
  976. 60% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  977. 70% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  978. 80% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  979. 90% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  980. 100% { transform: rotate(var(--player-rotation)) scale(1); }
  981. }
  982. /* 游戏消息样式 */
  983. .game-message {
  984. position: absolute;
  985. top: 20px;
  986. left: 50%;
  987. transform: translateX(-50%);
  988. padding: 10px 20px;
  989. border-radius: 5px;
  990. font-weight: bold;
  991. z-index: 20;
  992. min-width: 200px;
  993. text-align: center;
  994. }
  995. .game-message.success {
  996. background-color: #d4edda;
  997. color: #155724;
  998. border: 1px solid #c3e6cb;
  999. }
  1000. .game-message.error {
  1001. background-color: #f8d7da;
  1002. color: #721c24;
  1003. border: 1px solid #f5c6cb;
  1004. }
  1005. .game-message.info {
  1006. background-color: #d1ecf1;
  1007. color: #0c5460;
  1008. border: 1px solid #bee5eb;
  1009. }
  1010. /* Blockly区域样式 */
  1011. .blockly-section {
  1012. flex: 1;
  1013. min-width: 600px;
  1014. display: flex;
  1015. flex-direction: column;
  1016. gap: 20px;
  1017. }
  1018. .toolbox-section {
  1019. background: rgba(248, 249, 250, 0.82);
  1020. padding: 15px;
  1021. border-radius: 15px;
  1022. }
  1023. // 合并重复的区块标题样式
  1024. .map-section h2,
  1025. .toolbox-section h2,
  1026. .workspace-section h2 {
  1027. margin-bottom: 15px;
  1028. color: #2c3e50;
  1029. border-bottom: 2px solid #3498db;
  1030. padding-bottom: 8px;
  1031. }
  1032. // 合并重复的区块背景样式
  1033. .map-section,
  1034. .toolbox-section,
  1035. .workspace-section {
  1036. background: rgba(248, 249, 250, 0.82);
  1037. padding: 15px;
  1038. border-radius: 15px;
  1039. height: 100%;
  1040. }
  1041. .workspace-section h2 {
  1042. margin-bottom: 15px;
  1043. color: #2c3e50;
  1044. border-bottom: 2px solid #3498db;
  1045. padding-bottom: 8px;
  1046. }
  1047. #blocklyDiv {
  1048. height: 80%;
  1049. min-height: 500px;
  1050. width: 100%;
  1051. background: #fff;
  1052. border: 1px solid #ddd;
  1053. border-radius: 8px;
  1054. }
  1055. .controls {
  1056. display: flex;
  1057. gap: 10px;
  1058. margin: 15px 0px;
  1059. flex-wrap: wrap;
  1060. }
  1061. button {
  1062. padding: 10px 20px;
  1063. border: none;
  1064. border-radius: 5px;
  1065. background: #3498db;
  1066. color: #fff;
  1067. font-weight: 700;
  1068. cursor: pointer;
  1069. transition: all 0.3s ease;
  1070. }
  1071. button:hover {
  1072. background: #2980b9;
  1073. transform: translateY(-2px);
  1074. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  1075. }
  1076. #runCode {
  1077. background: #e74c3c;
  1078. }
  1079. #runCode:hover {
  1080. background: #c0392b;
  1081. }
  1082. /* 响应式布局 */
  1083. @media (max-width: 1200px) {
  1084. .content {
  1085. flex-direction: column;
  1086. }
  1087. .map-section,
  1088. .blockly-section {
  1089. min-width: 100%;
  1090. }
  1091. .map-background {
  1092. width: 100%;
  1093. height: 400px;
  1094. }
  1095. }
  1096. </style>