MapGame.vue 45 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624
  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 v-if="currentGameData?.info" 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-if="currentGameData?.info" 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" @load="onMapImageLoad" />
  28. <!-- 可行走区域标记 -->
  29. <div
  30. v-for="(point, index) in walkablePoints"
  31. :key="index"
  32. class="walkable-point"
  33. :style="getPointStyle(point)"
  34. >
  35. </div>
  36. <!-- 玩家角色 -->
  37. <div
  38. class="player"
  39. :style="playerStyle"
  40. :class="{ 'collision': isColliding, 'success': hasReachedEnd }"
  41. >
  42. </div>
  43. <!-- 携带物品容器 - 默认隐藏,有物品时显示 -->
  44. <div class="carried-items-container" v-show="gameState.player.carriedItems.length > 0">
  45. <div
  46. v-for="(item, index) in gameState.player.carriedItems"
  47. :key="index"
  48. class="carried-item"
  49. :style="getCarriedItemStyle(index, item)"
  50. ></div>
  51. </div>
  52. </div>
  53. <!-- 游戏状态提示 -->
  54. <div v-if="gameMessage" :class="['game-message', messageType]">
  55. {{ gameMessage }}
  56. </div>
  57. </div>
  58. </div>
  59. <!-- Blockly工作区 -->
  60. <div class="blockly-section">
  61. <div class="toolbox-section" style="display: none;">
  62. <h2>工具箱</h2>
  63. <div id="toolbox">
  64. <!-- 移动控制积木 -->
  65. <category name="移动控制" colour="%{BKY_MOTION_HUE}">
  66. <block type="move_forward"></block>
  67. <block type="turn_left"></block>
  68. <block type="turn_right"></block>
  69. <block type="turn_around"></block>
  70. <block type="pickup_item"></block>
  71. <block type="use_item"></block>
  72. </category>
  73. <!-- 逻辑控制积木 -->
  74. <category name="逻辑" colour="%{BKY_LOGIC_HUE}">
  75. <block type="controls_if"></block>
  76. <block type="logic_compare"></block>
  77. <block type="logic_operation"></block>
  78. <block type="logic_negate"></block>
  79. <block type="logic_boolean"></block>
  80. </category>
  81. <!-- 循环控制积木 -->
  82. <category name="循环" colour="%{BKY_LOOPS_HUE}">
  83. <block type="controls_repeat_ext">
  84. <value name="TIMES">
  85. <shadow type="math_number">
  86. <field name="NUM"></field>
  87. </shadow>
  88. </value>
  89. </block>
  90. <block type="controls_whileUntil"></block>
  91. </category>
  92. <!-- 数学运算积木 -->
  93. <category name="数学" colour="%{BKY_MATH_HUE}">
  94. <block type="math_number"></block>
  95. <block type="math_arithmetic"></block>
  96. </category>
  97. </div>
  98. </div>
  99. <div class="workspace-section">
  100. <div class="controls">
  101. <button id="runCode" @click="runCode">运行代码</button>
  102. <button @click="clearWorkspace">清空工作区</button>
  103. <button @click="resetPlayer">重置玩家</button>
  104. </div>
  105. <div id="blocklyDiv"></div>
  106. </div>
  107. </div>
  108. </div>
  109. </div>
  110. </template>
  111. <script setup>
  112. import {ref, onMounted, onUnmounted, reactive, computed, nextTick} from 'vue';
  113. import { useRouter, useRoute } from 'vue-router';
  114. import { ArrowLeftBold } from '@element-plus/icons-vue';
  115. import * as Blockly from "blockly";
  116. import 'blockly/msg/zh-hans';
  117. import { javascriptGenerator } from "blockly/javascript";
  118. import playerImage from '@/assets/images/blockly/user.png';
  119. // 游戏接口数据
  120. import { getMapGameById } from '@/api/blockly/game.js';
  121. // 配置常量
  122. const CONFIG = {
  123. // 动画时长配置(毫秒)
  124. ANIMATION: {
  125. MOVE_DURATION: 500, // 移动动画持续时间
  126. ROTATE_DURATION: 500, // 旋转动画持续时间(左转/右转)
  127. TURN_AROUND_DURATION: 750, // 向后转动画持续时间
  128. },
  129. // 延迟配置(毫秒)
  130. DELAY: {
  131. ACTION_DELAY: 200, // 每次动作后的延迟时间
  132. COLLISION_DELAY: 300, // 碰撞后的延迟时间
  133. RESET_DELAY: 300, // 重置后的延迟时间
  134. MESSAGE_DISPLAY: 3000, // 消息显示时间
  135. COLLISION_RESET: 1000, // 碰撞状态重置时间
  136. LOOP_PREVENTION: 10, // 循环防止UI阻塞的延迟
  137. },
  138. // 游戏配置
  139. GAME: {
  140. MAX_LOOP_COUNT: 100, // 最大循环次数
  141. DIRECTIONS: {
  142. UP: 0,
  143. RIGHT: 1,
  144. DOWN: 2,
  145. LEFT: 3
  146. }
  147. },
  148. // 样式配置
  149. STYLES: {
  150. DEFAULT_TILE_SIZE: 143, // 默认瓦片大小
  151. PLAYER_SIZE_RATIO: 0.8, // 玩家大小占瓦片的比例
  152. PLAYER_SIZE_MARGIN: 0.1 // 玩家大小占瓦片的比例
  153. },
  154. //提示语
  155. TIPS: {
  156. NO_ENTRY: '当前位置无通路,无法移动',
  157. FINISH: '恭喜你到达终点!',
  158. }
  159. };
  160. // 路由和游戏状态
  161. const router = useRouter();
  162. const route = useRoute();
  163. const gameTitle = ref('地图游戏编程'); // 默认标题
  164. const currentGameData = ref(null);
  165. const playerInitialDirection = ref(0); // 人物初始朝向
  166. const gameSort = ref('Game1'); // 默认排序
  167. // 运行控制标志
  168. let shouldStopExecution = false;
  169. let currentExecutionPromise = null;
  170. let executionAbortController = null;
  171. // 添加响应式的容器尺寸
  172. const mapContainerDimensions = ref({ width: 0, height: 0 });
  173. // Blockly相关状态
  174. let workspace = null;
  175. // 使用 Map 存储可行走点及其类型,提高查询效率
  176. let walkablePointsMap = new Map();
  177. // 创建游戏状态的响应式对象
  178. const gameState = reactive({
  179. // 地图配置信息
  180. mapConfig: {
  181. // 地图背景图片路径
  182. background: '',
  183. // 每个瓦片的尺寸(像素)
  184. tileSize: CONFIG.STYLES.DEFAULT_TILE_SIZE,
  185. },
  186. // 玩家相关状态
  187. player: {
  188. // 玩家当前位置坐标
  189. position: {},
  190. // 玩家当前朝向:0=上, 1=右, 2=下, 3=左
  191. direction: 1,
  192. // 是否正在发生碰撞
  193. isColliding: false,
  194. // 是否已到达终点
  195. hasReachedEnd: false,
  196. // 是否正在冰块上滑行
  197. isSliding: false,
  198. // 携带的物品数组
  199. carriedItems: [],
  200. },
  201. // 游戏状态信息
  202. status: {
  203. // 当前显示的游戏消息
  204. message: '',
  205. // 消息类型(如success、error、info等)
  206. messageType: ''
  207. },
  208. // 地图数据信息
  209. mapData: {
  210. // 游戏起点位置
  211. startPoint: {},
  212. // 游戏终点位置
  213. endPoint: {},
  214. // 地图上所有可行走的点坐标集合,添加type属性区分普通点和冰块
  215. walkablePoints: [],
  216. // 保存原始的可行走点数据,用于重置
  217. originalWalkablePoints: [],
  218. }
  219. });
  220. const BLOCKLY_MAP_TYPE_DICT = {
  221. ICE: 'ice',//冰块
  222. YC: 'yaoshi',//钥匙
  223. };
  224. // 计算属性 - 提高性能和可读性
  225. const mapBackground = computed(() => gameState.mapConfig.background);
  226. // const tileSize = computed(() => gameState.mapConfig.tileSize);
  227. const walkablePoints = computed(() => gameState.mapData.walkablePoints);
  228. const startPoint = computed(() => gameState.mapData.startPoint);
  229. const endPoint = computed(() => gameState.mapData.endPoint);
  230. const playerPosition = computed(() => gameState.player.position);
  231. const playerDirection = computed(() => gameState.player.direction);
  232. const isColliding = computed(() => gameState.player.isColliding);
  233. const hasReachedEnd = computed(() => gameState.player.hasReachedEnd);
  234. const gameMessage = computed(() => gameState.status.message);
  235. const messageType = computed(() => gameState.status.messageType);
  236. const isSliding = computed(() => gameState.player.isSliding);
  237. // 计算玩家图片路径,优先使用接口数据
  238. const playerImageSrc = computed(() => {
  239. if (currentGameData.value && currentGameData.value.userImage) {
  240. return currentGameData.value.userImage.trim();
  241. }
  242. return playerImage;
  243. });
  244. // 地图图片加载完成后更新容器尺寸
  245. const onMapImageLoad = () => {
  246. updateMapContainerDimensions();
  247. };
  248. // 计算实际瓦片大小(基于容器尺寸和地图数据)
  249. const tileSize = computed(() => {
  250. if (mapContainerDimensions.value.width === 0 || mapContainerDimensions.value.height === 0) {
  251. return gameState.mapConfig.tileSize;
  252. }
  253. // 获取地图数据中的最大坐标
  254. const maxX = Math.max(...walkablePoints.value.map(p => p.x));
  255. const maxY = Math.max(...walkablePoints.value.map(p => p.y));
  256. // 计算基于容器的瓦片大小,确保地图完全可见
  257. const tileWidth = mapContainerDimensions.value.width / maxX;
  258. const tileHeight = mapContainerDimensions.value.height / maxY;
  259. // 返回较小的值以确保地图完全可见
  260. return Math.min(tileWidth, tileHeight);
  261. });
  262. // 生命周期钩子
  263. onMounted(async () => {
  264. // 获取游戏数据
  265. await fetchGameData();
  266. // 初始化可行走点集合
  267. initWalkablePointsSet();
  268. // 注册自定义积木
  269. registerCustomBlocks();
  270. // 注册JavaScript生成器
  271. registerJavaScriptGenerators();
  272. // 初始化Blockly工作区
  273. initBlockly();
  274. // 重置玩家位置
  275. resetPlayer();
  276. await nextTick();
  277. // 添加对窗口大小变化的监听
  278. updateMapContainerDimensions();
  279. window.addEventListener('resize', updateMapContainerDimensions);
  280. });
  281. // 获取游戏数据
  282. const fetchGameData = async () => {
  283. try {
  284. const gameId = route.query.gameId;
  285. const nameFromRoute = route.query.gameName;
  286. const sortFromRoute = route.query.gameSort;
  287. if (nameFromRoute) {
  288. gameTitle.value = nameFromRoute;
  289. }
  290. if (sortFromRoute) {
  291. gameSort.value = sortFromRoute;
  292. }
  293. let mapGameData = await getMapGameById(gameId);
  294. if (mapGameData.code === 0) {
  295. currentGameData.value = mapGameData?.data;
  296. // 使用接口数据
  297. if (currentGameData.value && currentGameData.value.sort) {
  298. let sortNum = currentGameData.value.sort;
  299. gameSort.value = sortNum > 9 ? `Game${sortNum}` : `Game${sortNum}`;
  300. }
  301. await updateGameStateFromData(currentGameData.value);
  302. // 数据更新后强制刷新容器尺寸(等待DOM更新)
  303. await nextTick();
  304. updateMapContainerDimensions();
  305. }
  306. } catch (error) {
  307. console.error('获取游戏数据失败:', error);
  308. }
  309. };
  310. // 根据获取到的数据更新游戏状态
  311. const updateGameStateFromData = (gameData) => {
  312. try {
  313. // 更新地图配置
  314. gameState.mapConfig.background = gameData.mapBackground ? gameData.mapBackground.trim() : '';
  315. gameState.mapConfig.tileSize = gameData.mapTileSize || CONFIG.STYLES.DEFAULT_TILE_SIZE;
  316. // 更新玩家方向
  317. if (gameData.userDirection) {
  318. playerInitialDirection.value = gameData.userDirection;
  319. }
  320. // 更新地图数据
  321. // 地图起点
  322. if (gameData.mapStartPoint) {
  323. const startPoint = JSON.parse(gameData.mapStartPoint);
  324. gameState.mapData.startPoint = { x: startPoint.x, y: startPoint.y };
  325. gameState.player.position = { x: startPoint.x, y: startPoint.y };
  326. }
  327. // 地图终点
  328. if (gameData.mapEndPoint) {
  329. const endPoint = JSON.parse(gameData.mapEndPoint);
  330. gameState.mapData.endPoint = { x: endPoint.x, y: endPoint.y };
  331. }
  332. if (gameData.mapWalkablePoints) {
  333. gameState.mapData.walkablePoints = JSON.parse(gameData.mapWalkablePoints);
  334. }
  335. // 重新初始化可行走点集合
  336. initWalkablePointsSet();
  337. } catch (error) {
  338. console.error('更新游戏状态失败:', error);
  339. }
  340. };
  341. // 初始化可行走点映射
  342. function initWalkablePointsSet() {
  343. walkablePointsMap.clear();
  344. gameState.mapData.walkablePoints.forEach(point => {
  345. walkablePointsMap.set(`${point.x},${point.y}`, point);
  346. });
  347. // 保存原始的可行走点数据,用于重置
  348. gameState.mapData.originalWalkablePoints = JSON.parse(JSON.stringify(gameState.mapData.walkablePoints));
  349. }
  350. // 可行走检查函数
  351. function isWalkable(x, y) {
  352. return walkablePointsMap.has(`${x},${y}`);
  353. }
  354. // 计算点的样式
  355. function getPointStyle(point) {
  356. const style = {
  357. left: point.x * tileSize.value - tileSize.value + 'px',
  358. top: point.y * tileSize.value - tileSize.value + 'px',
  359. width: tileSize.value + 'px',
  360. height: tileSize.value + 'px',
  361. };
  362. // 如果point有img属性,则添加图标
  363. if (point.img) {
  364. const iconSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO;
  365. const marginSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN;
  366. // 重置可能影响背景图显示的样式
  367. style.backgroundColor = 'transparent';
  368. style.backgroundImage = `url(${point.img})`;
  369. style.backgroundSize = 'contain';
  370. style.backgroundPosition = 'center';
  371. style.backgroundRepeat = 'no-repeat';
  372. // 设置与玩家相同的宽高和边距
  373. style.width = iconSize + 'px';
  374. style.height = iconSize + 'px';
  375. style.margin = marginSize + 'px';
  376. }
  377. return style;
  378. }
  379. // 计算玩家样式
  380. const playerStyle = computed(() => ({
  381. left: playerPosition.value.x * tileSize.value - tileSize.value + 'px',
  382. top: playerPosition.value.y * tileSize.value - tileSize.value + 'px',
  383. transform: `rotate(${playerDirection.value * 90}deg)`,
  384. '--player-rotation': `${playerDirection.value * 90}deg`,
  385. '--player-image': `url(${playerImageSrc.value})`,
  386. width: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO) + 'px',
  387. height: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO) + 'px',
  388. margin: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN) + 'px',
  389. }));
  390. // 计算携带物品样式
  391. function getCarriedItemStyle(index, item) {
  392. const baseSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO * 0.3;
  393. return {
  394. position: 'relative',
  395. width: baseSize + 'px',
  396. height: baseSize + 'px',
  397. backgroundSize: 'contain',
  398. backgroundPosition: 'center',
  399. backgroundRepeat: 'no-repeat',
  400. backgroundImage: `url(${item.img})`
  401. };
  402. }
  403. // 导航返回
  404. function navigateBack() {
  405. router.back();
  406. }
  407. // 注册自定义积木
  408. function registerCustomBlocks() {
  409. // 向前移动积木
  410. Blockly.Blocks['move_forward'] = {
  411. init: function() {
  412. this.jsonInit({
  413. "type": "move_forward",
  414. "message0": "向前移动",
  415. "previousStatement": null,
  416. "nextStatement": null,
  417. "colour": 230,
  418. "tooltip": "控制角色向前移动一格",
  419. "helpUrl": ""
  420. });
  421. }
  422. };
  423. // 向左转积木
  424. Blockly.Blocks['turn_left'] = {
  425. init: function() {
  426. this.jsonInit({
  427. "type": "turn_left",
  428. "message0": "向左转",
  429. "previousStatement": null,
  430. "nextStatement": null,
  431. "colour": 230,
  432. "tooltip": "控制角色向左转",
  433. "helpUrl": ""
  434. });
  435. }
  436. };
  437. // 向右转积木
  438. Blockly.Blocks['turn_right'] = {
  439. init: function() {
  440. this.jsonInit({
  441. "type": "turn_right",
  442. "message0": "向右转",
  443. "previousStatement": null,
  444. "nextStatement": null,
  445. "colour": 230,
  446. "tooltip": "控制角色向右转",
  447. "helpUrl": ""
  448. });
  449. }
  450. };
  451. // 向后转积木
  452. Blockly.Blocks['turn_around'] = {
  453. init: function() {
  454. this.jsonInit({
  455. "type": "turn_around",
  456. "message0": "向后转",
  457. "previousStatement": null,
  458. "nextStatement": null,
  459. "colour": 230,
  460. "tooltip": "控制角色向后转",
  461. "helpUrl": ""
  462. });
  463. }
  464. };
  465. // 拾取物品积木
  466. Blockly.Blocks['pickup_item'] = {
  467. init: function() {
  468. this.jsonInit({
  469. "type": "pickup_item",
  470. "message0": "拾取物品",
  471. "previousStatement": null,
  472. "nextStatement": null,
  473. "colour": 30,
  474. "tooltip": "尝试拾取当前位置的物品",
  475. "helpUrl": ""
  476. });
  477. }
  478. };
  479. // 使用物品积木
  480. Blockly.Blocks['use_item'] = {
  481. init: function() {
  482. this.jsonInit({
  483. "type": "use_item",
  484. "message0": "使用物品",
  485. "previousStatement": null,
  486. "nextStatement": null,
  487. "colour": 30,
  488. "tooltip": "在当前位置使用物品",
  489. "helpUrl": ""
  490. });
  491. }
  492. };
  493. }
  494. // 注册JavaScript生成器
  495. function registerJavaScriptGenerators() {
  496. // 向前移动生成器
  497. javascriptGenerator.forBlock['move_forward'] = function(block) {
  498. return 'await moveForward();\n';
  499. };
  500. // 向左转生成器
  501. javascriptGenerator.forBlock['turn_left'] = function(block) {
  502. return 'await turnLeft();\n';
  503. };
  504. // 向右转生成器
  505. javascriptGenerator.forBlock['turn_right'] = function(block) {
  506. return 'await turnRight();\n';
  507. };
  508. // 向后转生成器
  509. javascriptGenerator.forBlock['turn_around'] = function(block) {
  510. return 'await turnAround();\n';
  511. };
  512. // 拾取物品生成器
  513. javascriptGenerator.forBlock['pickup_item'] = function(block) {
  514. return 'await pickupItem();\n';
  515. };
  516. // 使用物品生成器
  517. javascriptGenerator.forBlock['use_item'] = function(block) {
  518. return 'await useItem();\n';
  519. };
  520. // 为重复循环块注册自定义生成器,确保支持异步操作
  521. javascriptGenerator.forBlock['controls_repeat_ext'] = function(block) {
  522. const repeats = javascriptGenerator.valueToCode(block, 'TIMES', javascriptGenerator.ORDER_ATOMIC) || '0';
  523. // 确保获取到的是数字类型,如果是字符串需要转换
  524. const safeRepeats = `(function() {
  525. const num = Number(${repeats});
  526. return isNaN(num) ? 0 : Math.max(0, Math.floor(num));
  527. })()`;
  528. // 获取循环体代码
  529. const branch = javascriptGenerator.statementToCode(block, 'DO');
  530. // 生成支持异步的循环代码
  531. let code = `for (let i = 0; i < ${safeRepeats}; i++) {\n`;
  532. code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT);
  533. code += '}\n';
  534. return code;
  535. };
  536. // 为while/until循环块注册自定义生成器
  537. javascriptGenerator.forBlock['controls_whileUntil'] = function(block) {
  538. const until = block.getFieldValue('MODE') === 'UNTIL';
  539. const condition = javascriptGenerator.valueToCode(block, 'CONDITION',
  540. javascriptGenerator.ORDER_NONE) || 'false';
  541. const branch = javascriptGenerator.statementToCode(block, 'DO');
  542. // 修复变量作用域问题,使用IIFE包装循环
  543. let code = '(async function() {\n';
  544. code += ' let loopCount = 0;\n';
  545. code += until ? ' while (!((' + condition + ')) && loopCount < ' + CONFIG.GAME.MAX_LOOP_COUNT + ') {\n' :
  546. ' while (((' + condition + ')) && loopCount < ' + CONFIG.GAME.MAX_LOOP_COUNT + ') {\n';
  547. code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT + ' ');
  548. code += ' loopCount++';
  549. code += ' await new Promise(resolve => setTimeout(resolve, ' + CONFIG.DELAY.LOOP_PREVENTION + '));\n'; // 防止UI阻塞
  550. code += ' }\n';
  551. code += '})();\n';
  552. return code;
  553. };
  554. // 为text_print块添加生成器,用于调试
  555. javascriptGenerator.forBlock['text_print'] = function(block) {
  556. const msg = javascriptGenerator.valueToCode(block, 'TEXT', javascriptGenerator.ORDER_NONE) || '';
  557. return msg;
  558. };
  559. }
  560. // 初始化Blockly工作区
  561. function initBlockly() {
  562. const toolbox = document.getElementById('toolbox');
  563. workspace = Blockly.inject('blocklyDiv', {
  564. toolbox: toolbox,
  565. collapse: false,
  566. comments: true,
  567. disable: false, // 设为false以允许编辑
  568. maxBlocks: Infinity,
  569. trashcan: true,
  570. horizontalLayout: false,
  571. toolboxPosition: 'start',
  572. toolboxCollapse: false, // 设置工具箱默认展开
  573. toolboxAlwaysExpanded: true, // 确保点击类别后保持展开状态
  574. css: true,
  575. media: 'https://unpkg.com/blockly/media/',
  576. rtl: false,
  577. scrollbars: true,
  578. sounds: false, // 禁用声音以提高性能
  579. oneBasedIndex: true,
  580. grid: {
  581. spacing: 20,
  582. length: 3,
  583. colour: "#ccc",
  584. snap: true
  585. },
  586. zoom: {
  587. controls: true,
  588. wheel: true,
  589. startScale: 1.0,
  590. maxScale: 3,
  591. minScale: 0.3,
  592. scaleSpeed: 1.2
  593. }
  594. });
  595. }
  596. // 平滑移动函数
  597. async function smoothMoveTo(targetX, targetY) {
  598. const startX = playerPosition.value.x;
  599. const startY = playerPosition.value.y;
  600. const startTime = performance.now();
  601. // 使用Promise包装动画过程,使其可以await
  602. return new Promise(resolve => {
  603. function animate(currentTime) {
  604. // 检查是否应该停止执行
  605. if (shouldStopExecution) {
  606. resolve();
  607. return;
  608. }
  609. const elapsed = currentTime - startTime;
  610. const progress = Math.min(elapsed / CONFIG.ANIMATION.MOVE_DURATION, 1); // 计算进度,最大为1
  611. // 线性插值计算当前位置
  612. const currentX = startX + (targetX - startX) * progress;
  613. const currentY = startY + (targetY - startY) * progress;
  614. gameState.player = {
  615. ...gameState.player,
  616. position: { x: currentX, y: currentY },
  617. };
  618. // 检查是否到达终点
  619. if (progress < 1) {
  620. // 继续动画
  621. requestAnimationFrame(animate);
  622. } else {
  623. resolve(); // 动画完成
  624. }
  625. }
  626. // 启动动画
  627. requestAnimationFrame(animate);
  628. });
  629. }
  630. // 处理冰块滑行逻辑(根据人物当前位置判断)
  631. async function switchMapType(isMapType = null) {
  632. //取人物当前位置
  633. let x = playerPosition.value.x;
  634. let y = playerPosition.value.y;
  635. let tileMap = walkablePointsMap.get(`${x},${y}`);
  636. //判断是否是指定地图类型
  637. if (isMapType) {
  638. return isMapType === tileMap.type;
  639. }
  640. //判断方块类型并处理逻辑
  641. switch (tileMap.type) {
  642. case BLOCKLY_MAP_TYPE_DICT.ICE:
  643. do {
  644. showGameMessage(tileMap.tip, 'warning',300)
  645. await handleIceSliding();
  646. tileMap = walkablePointsMap.get(`${playerPosition.value.x},${playerPosition.value.y}`);
  647. }while (tileMap.type === BLOCKLY_MAP_TYPE_DICT.ICE && !isColliding.value)
  648. break;
  649. case BLOCKLY_MAP_TYPE_DICT.YC:
  650. // showGameMessage(tileMap.tip, 'warning', 1000)
  651. // // 处理携带物品逻辑
  652. // if (tileMap && tileMap.img) {
  653. // // 将物品添加到玩家携带物品中
  654. // gameState.player.carriedItems.push({
  655. // ...tileMap,
  656. // originalX: x,
  657. // originalY: y
  658. // });
  659. //
  660. // // 从地图上移除图标(但保留点的可通行性)
  661. // const pointIndex = gameState.mapData.walkablePoints.findIndex(
  662. // p => p.x === x && p.y === y
  663. // );
  664. // if (pointIndex !== -1) {
  665. // // 保留点但移除img属性
  666. // const updatedPoint = { ...gameState.mapData.walkablePoints[pointIndex] };
  667. // delete updatedPoint.img;
  668. // gameState.mapData.walkablePoints.splice(pointIndex, 1, updatedPoint);
  669. // // 更新映射
  670. // walkablePointsMap.set(`${x},${y}`, updatedPoint);
  671. // }
  672. // }
  673. break;
  674. }
  675. }
  676. // 处理冰块滑行逻辑
  677. async function handleIceSliding() {
  678. if (shouldStopExecution || isColliding.value) {
  679. return;
  680. }
  681. gameState.player.isSliding = true;
  682. try {
  683. // 计算下一个位置
  684. let nextX = playerPosition.value.x;
  685. let nextY = playerPosition.value.y;
  686. // 根据当前方向计算下一个位置
  687. switch(playerDirection.value) {
  688. case CONFIG.GAME.DIRECTIONS.UP: nextY--; break;
  689. case CONFIG.GAME.DIRECTIONS.RIGHT: nextX++; break;
  690. case CONFIG.GAME.DIRECTIONS.DOWN: nextY++; break;
  691. case CONFIG.GAME.DIRECTIONS.LEFT: nextX--; break;
  692. }
  693. // 检查下一个位置是否可行走
  694. if (isWalkable(nextX, nextY)) {
  695. // 执行平滑移动到下一个位置
  696. await smoothMoveTo(nextX, nextY);
  697. } else {
  698. // 使用统一的碰撞处理方法,但不等待延迟(因为handleIceSliding不需要这个延迟)
  699. await handleWallCollision();
  700. }
  701. } catch (error) {
  702. console.error('滑行过程中发生错误:', error);
  703. } finally {
  704. // 无论如何都要确保滑行状态被重置
  705. gameState.player.isSliding = false;
  706. }
  707. }
  708. // 拾取物品函数
  709. window.pickupItem = async function() {
  710. //取人物当前位置
  711. let x = playerPosition.value.x;
  712. let y = playerPosition.value.y;
  713. let tileMap = walkablePointsMap.get(`${x},${y}`);
  714. // 判断是否是要拾取的方块类型
  715. if (tileMap && tileMap.type === BLOCKLY_MAP_TYPE_DICT.YC) {
  716. showGameMessage(tileMap.tip || '成功拾取物品!', 'warning', 1000)
  717. // 处理携带物品逻辑
  718. if (tileMap && tileMap.img) {
  719. // 将物品添加到玩家携带物品中
  720. gameState.player.carriedItems.push({
  721. ...tileMap,
  722. originalX: x,
  723. originalY: y
  724. });
  725. // 从地图上移除图标(但保留点的可通行性)
  726. const pointIndex = gameState.mapData.walkablePoints.findIndex(
  727. p => p.x === x && p.y === y
  728. );
  729. if (pointIndex !== -1) {
  730. // 保留点但移除img属性
  731. const updatedPoint = { ...gameState.mapData.walkablePoints[pointIndex] };
  732. delete updatedPoint.img;
  733. gameState.mapData.walkablePoints.splice(pointIndex, 1, updatedPoint);
  734. // 更新映射
  735. walkablePointsMap.set(`${x},${y}`, updatedPoint);
  736. }
  737. }
  738. } else {
  739. showGameMessage('当前位置没有可拾取的物品', 'info', 1000)
  740. }
  741. }
  742. // 使用物品函数
  743. window.useItem = async function() {
  744. //取人物当前位置
  745. let x = playerPosition.value.x;
  746. let y = playerPosition.value.y;
  747. let tileMap = walkablePointsMap.get(`${x},${y}`);
  748. // 判断当前位置是否有特殊需求
  749. if (tileMap && tileMap.need) {
  750. // 检查玩家是否携带了需要的物品
  751. const requiredItems = tileMap.need;
  752. let hasRequiredItem = false;
  753. let itemIndex = -1;
  754. // 检查玩家携带的物品中是否有满足需求的物品
  755. for (let i = 0; i < gameState.player.carriedItems.length; i++) {
  756. const item = gameState.player.carriedItems[i];
  757. if (requiredItems.includes(item.type)) {
  758. hasRequiredItem = true;
  759. itemIndex = i;
  760. break;
  761. }
  762. }
  763. if (hasRequiredItem) {
  764. // 使用物品成功
  765. showGameMessage(tileMap.tip || '物品使用成功!', 'success', 1500);
  766. // 从携带物品中移除已使用的物品
  767. gameState.player.carriedItems.splice(itemIndex, 1);
  768. } else {
  769. // 提示缺少所需物品
  770. showGameMessage(tileMap.tip || `需要特殊物品才能使用`, 'warning', 1500);
  771. }
  772. } else {
  773. showGameMessage('当前位置不需要使用物品', 'info', 1000);
  774. }
  775. }
  776. // 向前移动
  777. window.moveForward = async function() {
  778. if (shouldStopExecution || isColliding.value || isSliding.value) {
  779. return;
  780. }
  781. let newX = playerPosition.value.x;
  782. let newY = playerPosition.value.y;
  783. // 向前移动
  784. switch(playerDirection.value) {
  785. case CONFIG.GAME.DIRECTIONS.UP: newY--; break;
  786. case CONFIG.GAME.DIRECTIONS.RIGHT: newX++; break;
  787. case CONFIG.GAME.DIRECTIONS.DOWN: newY++; break;
  788. case CONFIG.GAME.DIRECTIONS.LEFT: newX--; break;
  789. }
  790. // 检查是否可以移动
  791. if (isWalkable(newX, newY)) {
  792. // 使用平滑移动动画
  793. await smoothMoveTo(newX, newY);
  794. // 处理方块类型逻辑
  795. await switchMapType();
  796. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  797. } else {
  798. // 发生碰撞 使用统一的碰撞处理方法
  799. await handleWallCollision();
  800. }
  801. };
  802. //向左转(逆时针旋转90度)
  803. window.turnLeft = async function() {
  804. // 如果已经发生过碰撞,不再执行任何旋转
  805. if (shouldStopExecution || isColliding.value) {
  806. return;
  807. }
  808. // 记录起始方向和目标方向
  809. const startDirection = playerDirection.value;
  810. const targetDirection = (playerDirection.value - 1 + 4) % 4;
  811. // 实现平滑旋转
  812. const startTime = performance.now();
  813. // 使用 requestAnimationFrame 实现平滑动画
  814. await new Promise(resolve => {
  815. function animate(currentTime) {
  816. // 检查是否应该停止执行
  817. if (shouldStopExecution) {
  818. resolve();
  819. return;
  820. }
  821. const elapsedTime = currentTime - startTime;
  822. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.ROTATE_DURATION, 1);
  823. // 在动画过程中更新方向
  824. gameState.player.direction = startDirection - progress;
  825. // 如果动画未完成,继续下一帧
  826. if (progress < 1) {
  827. requestAnimationFrame(animate);
  828. } else {
  829. // 动画完成后设置最终方向
  830. gameState.player.direction = targetDirection;
  831. resolve();
  832. }
  833. }
  834. // 开始动画
  835. requestAnimationFrame(animate);
  836. });
  837. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  838. };
  839. //向右转(顺时针旋转90度)
  840. window.turnRight = async function() {
  841. // 如果已经发生过碰撞,不再执行任何旋转
  842. if (shouldStopExecution || isColliding.value) {
  843. return;
  844. }
  845. // 记录起始方向和目标方向
  846. const startDirection = playerDirection.value;
  847. const targetDirection = (playerDirection.value + 1) % 4;
  848. // 实现平滑旋转
  849. const startTime = performance.now();
  850. // 使用 requestAnimationFrame 实现平滑动画
  851. await new Promise(resolve => {
  852. function animate(currentTime) {
  853. // 检查是否应该停止执行
  854. if (shouldStopExecution) {
  855. resolve();
  856. return;
  857. }
  858. const elapsedTime = currentTime - startTime;
  859. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.ROTATE_DURATION, 1);
  860. // 处理从3到0的边界情况,确保顺时针旋转
  861. let currentDirection;
  862. if (startDirection === 3 && targetDirection === 0) {
  863. // 对于从3到0的顺时针旋转,我们需要模拟+1的效果而不是-3
  864. currentDirection = startDirection + progress;
  865. // 当超过3.99时,设置为0(避免显示4)
  866. if (currentDirection > 3.99) {
  867. currentDirection = 0;
  868. }
  869. } else {
  870. // 正常情况下的线性插值
  871. currentDirection = startDirection + (targetDirection - startDirection) * progress;
  872. }
  873. // 在动画过程中更新方向
  874. gameState.player.direction = currentDirection;
  875. // 如果动画未完成,继续下一帧
  876. if (progress < 1) {
  877. requestAnimationFrame(animate);
  878. } else {
  879. // 动画完成后设置最终方向
  880. gameState.player.direction = targetDirection;
  881. resolve();
  882. }
  883. }
  884. // 开始动画
  885. requestAnimationFrame(animate);
  886. });
  887. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  888. };
  889. // 向后转(旋转180度)
  890. window.turnAround = async function() {
  891. // 如果已经发生过碰撞,不再执行任何旋转
  892. if (shouldStopExecution || isColliding.value) {
  893. return;
  894. }
  895. // 记录起始方向和目标方向
  896. const startDirection = playerDirection.value;
  897. const targetDirection = (playerDirection.value + 2) % 4;
  898. // 实现平滑旋转
  899. const startTime = performance.now();
  900. // 使用 requestAnimationFrame 实现平滑动画
  901. await new Promise(resolve => {
  902. function animate(currentTime) {
  903. // 检查是否应该停止执行
  904. if (shouldStopExecution) {
  905. resolve();
  906. return;
  907. }
  908. const elapsedTime = currentTime - startTime;
  909. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.TURN_AROUND_DURATION, 1);
  910. // 在动画过程中更新方向
  911. gameState.player.direction = startDirection + 2 * progress;
  912. // 如果动画未完成,继续下一帧
  913. if (progress < 1) {
  914. requestAnimationFrame(animate);
  915. } else {
  916. // 动画完成后设置最终方向
  917. gameState.player.direction = targetDirection;
  918. resolve();
  919. }
  920. }
  921. // 开始动画
  922. requestAnimationFrame(animate);
  923. });
  924. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  925. };
  926. //校验是否到达终点
  927. window.isFinish = async function() {
  928. // 如果已经发生过碰撞,不再执行任何检查
  929. if (isColliding.value) {
  930. return;
  931. }
  932. if (gameState.player.position.x === endPoint.value.x && gameState.player.position.y === endPoint.value.y) {
  933. gameState.player.hasReachedEnd = true;
  934. showGameMessage(CONFIG.TIPS.FINISH, 'success' );
  935. }
  936. };
  937. // 运行代码
  938. const runCode = async () => {
  939. try {
  940. await resetPlayer();
  941. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.RESET_DELAY));
  942. // 重置执行标志,允许新的执行
  943. shouldStopExecution = false;
  944. // 创建新的AbortController用于取消执行
  945. executionAbortController = new AbortController();
  946. const signal = executionAbortController.signal;
  947. // 确保生成器和工作区都存在
  948. if (!javascriptGenerator || !workspace) {
  949. throw new Error('生成器或工作区未正确初始化');
  950. }
  951. // 生成JavaScript代码
  952. const code = javascriptGenerator.workspaceToCode(workspace) + "await isFinish();";
  953. try {
  954. // 增强的安全检查
  955. const unsafePatterns = [
  956. 'eval(', 'Function(', 'document.write', 'window.location',
  957. 'document.createElement', 'XMLHttpRequest', 'fetch',
  958. 'setInterval', 'setTimeout', 'window.',
  959. 'alert(', 'confirm(', 'prompt(',
  960. 'document.cookie', 'localStorage', 'sessionStorage'
  961. ];
  962. const hasUnsafeCode = unsafePatterns.some(pattern => code.includes(pattern));
  963. if (hasUnsafeCode) {
  964. throw new Error('代码包含不安全的操作');
  965. }
  966. // 包装代码为异步函数执行,并设置超时保护
  967. currentExecutionPromise = new Promise(async (resolve, reject) => {
  968. try {
  969. // 检查信号是否已中止
  970. if (signal.aborted) {
  971. throw new Error('执行已取消');
  972. }
  973. // 添加信号监听
  974. signal.addEventListener('abort', () => {
  975. reject(new Error('执行已取消'));
  976. });
  977. const wrappedCode = `(async () => { ${code} })()`;
  978. await new Function(wrappedCode)();
  979. resolve();
  980. } catch (error) {
  981. reject(error);
  982. }
  983. });
  984. } catch (error) {
  985. // 捕获并显示执行错误
  986. if (error.message !== '执行已取消') {
  987. const errorMsg = error.message || '未知错误';
  988. showGameMessage(`代码执行错误: ${errorMsg}`, 'error');
  989. console.error('代码执行错误:', error);
  990. }
  991. } finally {
  992. // 清除当前执行的Promise引用
  993. currentExecutionPromise = null;
  994. }
  995. } catch (error) {
  996. showGameMessage(`运行时错误: ${error.message || '未知错误'}`, 'error');
  997. console.error('运行时错误:', error);
  998. }
  999. };
  1000. // 清空工作区
  1001. const clearWorkspace = () => {
  1002. workspace.clear();
  1003. showGameMessage('工作区已清空', 'info');
  1004. };
  1005. // 重置玩家位置和状态
  1006. const resetPlayer = () => {
  1007. // 设置标志强制停止所有执行
  1008. shouldStopExecution = true;
  1009. // 取消任何正在执行的代码
  1010. if (executionAbortController) {
  1011. executionAbortController.abort();
  1012. executionAbortController = null;
  1013. }
  1014. if (currentExecutionPromise) {
  1015. currentExecutionPromise = null;
  1016. }
  1017. // 重置携带的物品回地图
  1018. if (gameState.mapData.originalWalkablePoints.length > 0) {
  1019. gameState.mapData.walkablePoints = JSON.parse(JSON.stringify(gameState.mapData.originalWalkablePoints));
  1020. }
  1021. // 清空携带物品
  1022. gameState.player.carriedItems = [];
  1023. // 重新初始化可行走点集合
  1024. initWalkablePointsSet();
  1025. gameState.player.position = { ...startPoint.value };
  1026. gameState.player.direction = playerInitialDirection.value; // 重置为初始方向
  1027. gameState.player.isColliding = false; //碰撞标志
  1028. gameState.player.hasReachedEnd = false;
  1029. gameState.player.isSliding = false; // 重置滑行状态
  1030. };
  1031. // 更新地图容器尺寸的函数
  1032. function updateMapContainerDimensions() {
  1033. const mapContainer = document.querySelector('.map-container');
  1034. if (mapContainer) {
  1035. const rect = mapContainer.getBoundingClientRect();
  1036. // 确保获取到有效的尺寸值
  1037. if (rect.width > 0 && rect.height > 0) {
  1038. mapContainerDimensions.value = {
  1039. width: rect.width,
  1040. height: rect.height
  1041. };
  1042. } else {
  1043. // 若尺寸无效,使用默认容器尺寸(可根据实际情况调整)
  1044. mapContainerDimensions.value = {
  1045. width: 800,
  1046. height: 600
  1047. };
  1048. }
  1049. }
  1050. };
  1051. // 显示游戏消息
  1052. function showGameMessage(message, type = 'info', duration = CONFIG.DELAY.MESSAGE_DISPLAY) {
  1053. gameState.status.message = message;
  1054. gameState.status.messageType = type;
  1055. // 消息显示时间后自动清除消息
  1056. setTimeout(() => {
  1057. gameState.status.message = '';
  1058. }, duration);
  1059. }
  1060. // 统一处理撞到墙时的停止逻辑
  1061. async function handleWallCollision() {
  1062. // 设置碰撞状态
  1063. gameState.player.isColliding = true;
  1064. // 显示错误消息
  1065. showGameMessage(CONFIG.TIPS.NO_ENTRY, 'error');
  1066. // 立即中止整个代码执行
  1067. if (executionAbortController) {
  1068. executionAbortController.abort();
  1069. }
  1070. // 碰撞状态重置时间后取消碰撞状态
  1071. setTimeout(() => {
  1072. gameState.player.isColliding = false;
  1073. }, CONFIG.DELAY.COLLISION_RESET);
  1074. // 返回一个Promise,允许调用者等待碰撞延迟
  1075. return new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.COLLISION_DELAY));
  1076. }
  1077. // 组件卸载时清理
  1078. onUnmounted(() => {
  1079. if (workspace) {
  1080. workspace.dispose();
  1081. }
  1082. window.removeEventListener('resize', updateMapContainerDimensions);
  1083. });
  1084. </script>
  1085. <style scoped lang="scss">
  1086. @use "sass:math";
  1087. @function rpx($px) {
  1088. @return math.div($px, 750) * 100vw;
  1089. }
  1090. //将tileSize属性绑定到CSS变量上
  1091. :root {
  1092. --tile-size: v-bind('tileSize + "px"');
  1093. }
  1094. .map-game-container {
  1095. position: fixed;
  1096. top: 0;
  1097. left: 0;
  1098. right: 0;
  1099. bottom: 0;
  1100. background: transparent;
  1101. overflow-y: auto;
  1102. }
  1103. /* 自定义滚动条样式 */
  1104. .map-game-container::-webkit-scrollbar {
  1105. width: rpx(2); /* 滚动条宽度 */
  1106. }
  1107. .map-game-container::-webkit-scrollbar-track {
  1108. background: #f1effd; /* 滚动条轨道背景色 */
  1109. border-radius: rpx(4);
  1110. }
  1111. .map-game-container::-webkit-scrollbar-thumb {
  1112. background: #e2ddfc; /* 滚动条滑块颜色 */
  1113. border-radius: rpx(4);
  1114. }
  1115. .map-game-container::-webkit-scrollbar-thumb:hover {
  1116. background: #e2ddfc; /* 滚动条滑块 hover 状态颜色 */
  1117. }
  1118. /* 游戏简介样式 */
  1119. .info-message-container {
  1120. display: flex;
  1121. flex-direction: column;
  1122. align-items: flex-start;
  1123. }
  1124. .message-item {
  1125. display: flex;
  1126. align-items: flex-start;
  1127. width: 100%;
  1128. margin-bottom: rpx(5);
  1129. }
  1130. /* 头像样式 */
  1131. .avatar {
  1132. margin-right: rpx(4);
  1133. flex-shrink: 0;
  1134. }
  1135. .avatar-image {
  1136. width: rpx(30);
  1137. height: rpx(30);
  1138. object-fit: cover;
  1139. }
  1140. /* 消息内容样式 */
  1141. .message-item {
  1142. flex: 1;
  1143. }
  1144. .message-item p {
  1145. margin: rpx(4) 0;
  1146. line-height: 1.6;
  1147. font-size: rpx(7);
  1148. text-align: left;
  1149. color: black;
  1150. background-color: #e6faff;
  1151. opacity: 0.8;
  1152. border-radius: rpx(4);
  1153. padding: rpx(6);
  1154. max-width: 100%;
  1155. }
  1156. .message-item p:first-child {
  1157. margin-top: 0;
  1158. font-weight: 500;
  1159. }
  1160. .message-item p:last-child {
  1161. margin-bottom: 0;
  1162. }
  1163. .title-box {
  1164. position: relative;
  1165. top: rpx(5);
  1166. padding-left: 15px;
  1167. z-index: 10;
  1168. display: flex;
  1169. flex-direction: column;
  1170. }
  1171. /* 右侧两个角为圆角的长方形格子样式 */
  1172. .game-badge {
  1173. width: rpx(80);
  1174. height: rpx(20);
  1175. margin-left: rpx(10);
  1176. background-color: #5fb5dc;
  1177. color: #fff;
  1178. border-radius: 0 rpx(20) rpx(20) 0;
  1179. display: flex;
  1180. align-items: center;
  1181. justify-content: center;
  1182. font-size: rpx(15);
  1183. font-weight: bold;
  1184. }
  1185. .box-icon {
  1186. display: flex;
  1187. align-items: center;
  1188. gap: 10px;
  1189. padding: 10px 20px;
  1190. background-color: rgba(255, 255, 255, 0.8);
  1191. border-radius: 30px;
  1192. backdrop-filter: blur(10px);
  1193. cursor: pointer;
  1194. transition: all 0.3s ease;
  1195. font-size: 16px;
  1196. color: #333;
  1197. font-weight: 500;
  1198. width: fit-content;
  1199. }
  1200. .box-icon:hover {
  1201. background-color: rgba(255, 255, 255, 0.9);
  1202. transform: translate(-3px);
  1203. }
  1204. .left-icon {
  1205. font-size: 18px;
  1206. }
  1207. .content {
  1208. display: flex;
  1209. flex-wrap: nowrap;
  1210. gap: 20px;
  1211. padding: 20px;
  1212. min-width: 1160px;
  1213. }
  1214. /* 地图区域样式 */
  1215. .map-section {
  1216. flex: 1;
  1217. min-width: 500px;
  1218. background: rgba(248, 249, 250, 0.82);
  1219. padding: 15px;
  1220. border-radius: 15px;
  1221. }
  1222. .map-container {
  1223. position: relative;
  1224. width: 100%;
  1225. height: 100%;
  1226. overflow: hidden; // 防止内容溢出
  1227. }
  1228. .map-background {
  1229. position: relative;
  1230. width: 100%;
  1231. height: 100%;
  1232. background-size: cover;
  1233. background-position: center;
  1234. background-repeat: no-repeat;
  1235. }
  1236. .map-image {
  1237. width: 100%;
  1238. height: 100%;
  1239. object-fit: cover;
  1240. }
  1241. /* 可行走区域样式 */
  1242. .walkable-point {
  1243. position: absolute;
  1244. //background-color: rgba(52, 152, 219, 0.2);
  1245. //border: 1px solid rgba(52, 152, 219, 0.5);
  1246. //box-sizing: border-box;
  1247. //是否显示可行路线
  1248. opacity: 1;
  1249. }
  1250. /* 玩家样式 */
  1251. .player {
  1252. position: absolute;
  1253. background-image: var(--player-image);
  1254. background-size: contain;
  1255. background-repeat: no-repeat;
  1256. background-position: center;
  1257. border-radius: 5px;
  1258. z-index: 10;
  1259. }
  1260. /* 碰撞动画 */
  1261. .player.collision {
  1262. animation: collision 0.5s ease-in-out;
  1263. }
  1264. @keyframes collision {
  1265. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  1266. 25% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  1267. 50% { transform: rotate(var(--player-rotation)) translateX(3px) translateY(2px) scale(1.2); }
  1268. 75% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  1269. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  1270. }
  1271. /* 滑行动画 */
  1272. @keyframes sliding {
  1273. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  1274. 25% { transform: rotate(var(--player-rotation)) translateX(2px) translateY(0); }
  1275. 75% { transform: rotate(var(--player-rotation)) translateX(-2px) translateY(0); }
  1276. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  1277. }
  1278. /* 携带物品容器 */
  1279. .carried-items-container {
  1280. position: absolute;
  1281. top: 20px;
  1282. left: 20px;
  1283. background: rgba(255, 255, 255, 0.8);
  1284. border: 2px solid #3498db;
  1285. border-radius: 10px;
  1286. padding: 10px;
  1287. display: flex;
  1288. gap: 10px;
  1289. z-index: 15;
  1290. backdrop-filter: blur(10px);
  1291. }
  1292. /* 成功到达终点动画 */
  1293. .player.success {
  1294. animation: success 1s ease-in-out;
  1295. }
  1296. @keyframes success {
  1297. 0% { transform: rotate(var(--player-rotation)) scale(1); }
  1298. 10% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  1299. 20% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  1300. 30% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  1301. 40% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  1302. 50% { transform: rotate(var(--player-rotation)) scale(1.4) translateX(0) translateY(0); }
  1303. 60% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  1304. 70% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  1305. 80% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  1306. 90% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  1307. 100% { transform: rotate(var(--player-rotation)) scale(1); }
  1308. }
  1309. /* 游戏消息样式 */
  1310. .game-message {
  1311. position: absolute;
  1312. top: 20px;
  1313. left: 50%;
  1314. transform: translateX(-50%);
  1315. padding: 10px 20px;
  1316. border-radius: 5px;
  1317. font-weight: bold;
  1318. z-index: 20;
  1319. min-width: 200px;
  1320. text-align: center;
  1321. }
  1322. .game-message.success {
  1323. background-color: #d4edda;
  1324. color: #155724;
  1325. border: 1px solid #c3e6cb;
  1326. }
  1327. .game-message.error {
  1328. background-color: #f8d7da;
  1329. color: #721c24;
  1330. border: 1px solid #f5c6cb;
  1331. }
  1332. .game-message.info {
  1333. background-color: #d1ecf1;
  1334. color: #0c5460;
  1335. border: 1px solid #bee5eb;
  1336. }
  1337. .game-message.warning {
  1338. background-color: #baeff8;
  1339. color: #035767;
  1340. border: 1px solid #9be9f6;
  1341. }
  1342. /* Blockly区域样式 */
  1343. .blockly-section {
  1344. flex: 1;
  1345. min-width: 600px;
  1346. display: flex;
  1347. flex-direction: column;
  1348. gap: 20px;
  1349. }
  1350. // 合并重复的区块样式
  1351. .map-section, .toolbox-section, .workspace-section {
  1352. background: rgba(248, 249, 250, 0.82);
  1353. padding: 15px;
  1354. border-radius: 15px;
  1355. height: 100%;
  1356. }
  1357. .map-section h2, .toolbox-section h2, .workspace-section h2 {
  1358. margin-bottom: 15px;
  1359. color: #2c3e50;
  1360. border-bottom: 2px solid #3498db;
  1361. padding-bottom: 8px;
  1362. }
  1363. // 合并重复的区块背景样式
  1364. .map-section,
  1365. .toolbox-section,
  1366. .workspace-section {
  1367. background: rgba(248, 249, 250, 0.82);
  1368. padding: 15px;
  1369. border-radius: 15px;
  1370. }
  1371. #blocklyDiv {
  1372. height: rpx(300);
  1373. // min-height: 500px;
  1374. width: 100%;
  1375. background: #fff;
  1376. border: 1px solid #ddd;
  1377. border-radius: 8px;
  1378. }
  1379. .controls {
  1380. display: flex;
  1381. gap: 10px;
  1382. margin: 15px 0px;
  1383. flex-wrap: wrap;
  1384. }
  1385. button {
  1386. padding: 10px 20px;
  1387. border: none;
  1388. border-radius: 5px;
  1389. background: #3498db;
  1390. color: #fff;
  1391. font-weight: 700;
  1392. cursor: pointer;
  1393. transition: all 0.3s ease;
  1394. }
  1395. button:hover {
  1396. background: #2980b9;
  1397. transform: translateY(-2px);
  1398. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  1399. }
  1400. #runCode {
  1401. background: #e74c3c;
  1402. }
  1403. #runCode:hover {
  1404. background: #c0392b;
  1405. }
  1406. /* 响应式布局 */
  1407. @media (max-width: 1200px) {
  1408. .map-section,
  1409. .blockly-section {
  1410. flex: 1;
  1411. min-width: 45%;
  1412. }
  1413. .map-background {
  1414. width: 100%;
  1415. height: 400px;
  1416. }
  1417. }
  1418. </style>