MapGame.vue 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354
  1. <template>
  2. <div class="title-box">
  3. <!-- 左侧标题部分 -->
  4. <div class="left-container">
  5. <!-- 游戏编号 -->
  6. <div class="game-badge">{{ gameSort }}</div>
  7. </div>
  8. </div>
  9. <div class="content">
  10. <!-- 地图显示区域 -->
  11. <div class="map-section">
  12. <!-- 内容简介提示 -->
  13. <div v-if="currentGameData?.info" class="info-message-container">
  14. <div class="message-item">
  15. <div class="avatar">
  16. <img src="@/assets/images/xiaozhi2.png" alt="头像" class="avatar-image" />
  17. </div>
  18. <p v-if="currentGameData?.info" v-html="currentGameData?.info"></p>
  19. </div>
  20. </div>
  21. <div class="map-container">
  22. <!-- 地图背景 -->
  23. <div class="map-background">
  24. <img :src="mapBackground" alt="地图背景" class="map-image" @load="onMapImageLoad" />
  25. <!-- 可行走区域标记 -->
  26. <div
  27. v-for="(point, index) in walkablePoints"
  28. :key="index"
  29. class="walkable-point"
  30. :style="getPointStyle(point)"
  31. >
  32. </div>
  33. <!-- 玩家角色 -->
  34. <div
  35. class="player"
  36. :style="playerStyle"
  37. :class="{ 'collision': isColliding, 'success': hasReachedEnd }"
  38. >
  39. </div>
  40. <!-- 怀表倒计时容器 -->
  41. <div v-if="showCountdown" class="watch-container" :style="countdownStyle">
  42. <div class="watch-face">
  43. <div class="watch-center"></div>
  44. <div class="watch-hands">
  45. <div class="watch-hand hour-hand"></div>
  46. <div class="watch-hand minute-hand"></div>
  47. </div>
  48. <div class="watch-countdown-number">{{ countdownValue }}</div>
  49. </div>
  50. </div>
  51. <!-- 携带物品容器 -->
  52. <div class="carried-items-container" v-show="gameState.player.carriedItems.length > 0">
  53. <div
  54. v-for="(item, index) in gameState.player.carriedItems"
  55. :key="index"
  56. class="carried-item"
  57. :style="getCarriedItemStyle(index, item)"
  58. ></div>
  59. </div>
  60. </div>
  61. <!-- 游戏状态提示 -->
  62. <div v-if="gameMessage" :class="['game-message', messageType]">
  63. {{ gameMessage }}
  64. </div>
  65. </div>
  66. </div>
  67. <!-- Blockly工作区 -->
  68. <div class="blockly-section">
  69. <div class="toolbox-section" style="display: none;">
  70. <h2>工具箱</h2>
  71. <div id="toolbox">
  72. <!-- 移动控制积木 -->
  73. <category name="移动控制" colour="%{BKY_MOTION_HUE}">
  74. <block type="move_forward"></block>
  75. <block type="turn_left"></block>
  76. <block type="turn_right"></block>
  77. <block type="turn_around"></block>
  78. <block type="pickup_item"></block>
  79. <block type="use_item"></block>
  80. <block type="pause"></block>
  81. </category>
  82. <!-- 逻辑控制积木 -->
  83. <category name="逻辑" colour="%{BKY_LOGIC_HUE}">
  84. <block type="controls_if"></block>
  85. <block type="logic_compare"></block>
  86. <block type="logic_operation"></block>
  87. <block type="logic_boolean"></block>
  88. </category>
  89. <!-- 循环控制积木 -->
  90. <category name="循环" colour="%{BKY_LOOPS_HUE}">
  91. <block type="controls_repeat_ext"></block>
  92. <!-- <blockly type="controls_whileUntil"></blockly>-->
  93. </category>
  94. <!-- 数学运算积木 -->
  95. <category name="数学" colour="%{BKY_MATH_HUE}">
  96. <block type="math_number"></block>
  97. <block type="math_arithmetic"></block>
  98. </category>
  99. </div>
  100. </div>
  101. <div class="workspace-section">
  102. <div class="controls">
  103. <button id="runCode" @click="runCode" :disabled="isRunning">运行代码</button>
  104. <button @click="resetPlayer" >重置玩家</button>
  105. <button @click="clearWorkspace">清空工作区</button>
  106. </div>
  107. <div id="blocklyDiv"></div>
  108. </div>
  109. </div>
  110. </div>
  111. </template>
  112. <script setup>
  113. import {ref, onMounted, onUnmounted, reactive, computed, nextTick, watch, defineEmits} from 'vue';
  114. import { useRouter, useRoute } from 'vue-router';
  115. import { ArrowLeftBold } from '@element-plus/icons-vue';
  116. import * as Blockly from "blockly";
  117. import 'blockly/msg/zh-hans';
  118. import { javascriptGenerator } from "blockly/javascript";
  119. import playerImage from '@/assets/images/blockly/user.png';
  120. // 游戏接口数据
  121. import { getMapGameById } from '@/api/blockly/game.js';
  122. // 定义emits
  123. const emits = defineEmits(['saveProgress'])
  124. // 定义组件属性
  125. const props = defineProps({
  126. // 游戏ID
  127. gameId: {
  128. type: [String, Number],
  129. default: ''
  130. },
  131. // 地图背景
  132. mapBackground: {
  133. type: String,
  134. default: ''
  135. },
  136. // 地图瓦片大小
  137. mapTileSize: {
  138. type: [String, Object],
  139. default: ''
  140. },
  141. // 地图起点
  142. mapStartPoint: {
  143. type: [String, Object],
  144. default: ''
  145. },
  146. // 地图终点
  147. mapEndPoint: {
  148. type: [String, Object],
  149. default: ''
  150. },
  151. // 可行走点
  152. mapWalkablePoints: {
  153. type: [String, Array],
  154. default: ''
  155. },
  156. // 用户方向
  157. userDirection: {
  158. type: Number,
  159. default: 0
  160. },
  161. // 用户图片
  162. userImage: {
  163. type: String,
  164. default: ''
  165. },
  166. // 游戏信息
  167. info: {
  168. type: String,
  169. default: ''
  170. },
  171. // 游戏标题
  172. gameTitle: {
  173. type: String,
  174. default: ''
  175. },
  176. // 课程列表
  177. courseList: {
  178. type: Array,
  179. default: () => []
  180. },
  181. // 当前课程索引
  182. currentIndex: {
  183. type: Number,
  184. default: 0
  185. }
  186. });
  187. // 配置常量
  188. const CONFIG = {
  189. // 动画时长配置(毫秒)
  190. ANIMATION: {
  191. MOVE_DURATION: 500, // 移动动画持续时间
  192. ROTATE_DURATION: 500, // 旋转动画持续时间(左转/右转)
  193. TURN_AROUND_DURATION: 750, // 向后转动画持续时间
  194. },
  195. // 延迟配置(毫秒)
  196. DELAY: {
  197. ACTION_DELAY: 200, // 每次动作后的延迟时间
  198. COLLISION_DELAY: 300, // 碰撞后的延迟时间
  199. RESET_DELAY: 300, // 重置后的延迟时间
  200. MESSAGE_DISPLAY: 2000, // 消息显示时间
  201. COLLISION_RESET: 1000, // 碰撞状态重置时间
  202. LOOP_PREVENTION: 10, // 循环防止UI阻塞的延迟
  203. ITEMS_APPEAR: 300, // 物品出现延迟时间
  204. ITEMS_FLIGHT_ANIMATION_DELAY: 800, // 飞行动画延迟时间
  205. },
  206. // 游戏配置
  207. GAME: {
  208. MAX_LOOP_COUNT: 100, // 最大循环次数
  209. DIRECTIONS: {
  210. UP: 0,
  211. RIGHT: 1,
  212. DOWN: 2,
  213. LEFT: 3
  214. }
  215. },
  216. // 样式配置
  217. STYLES: {
  218. DEFAULT_TILE_SIZE: 143, // 默认瓦片大小
  219. PLAYER_SIZE_RATIO: 0.8, // 玩家大小占瓦片的比例
  220. PLAYER_SIZE_MARGIN: 0.1 // 玩家大小占瓦片的比例
  221. },
  222. //提示语
  223. TIPS: {
  224. NO_ENTRY: '当前位置无通路,无法移动',
  225. UNFINISHED: '任务未完成!',
  226. FINISH: '恭喜你到达终点!',
  227. PICKUP_ITEM: '拾取物品成功!',
  228. NULL_PICKUP_ITEM: '当前位置没有可拾取的物品',
  229. USE_ITEM_SUCCESS: '使用物品成功',
  230. USE_SPECIAL_ITEM: '需要特殊物品才能使用',
  231. NO_USE_ITEM: '当前位置不需要使用物品',
  232. }
  233. };
  234. // 路由和游戏状态
  235. const route = useRoute();
  236. const gameTitle = computed(() => props.gameTitle);
  237. const currentGameData = ref(null);
  238. const playerInitialDirection = ref(0); // 人物初始朝向
  239. const gameSort = ref('Game'); // 默认排序
  240. // 运行控制标志
  241. let shouldStopExecution = false;
  242. let currentExecutionPromise = null;
  243. let executionAbortController = null;
  244. // 添加响应式的容器尺寸
  245. const mapContainerDimensions = ref({ width: 0, height: 0 });
  246. // 用于控制运行/重置按钮状态
  247. const isRunning = ref(false);
  248. // 暂停模块-倒计时相关状态
  249. const showCountdown = ref(false);
  250. const countdownValue = ref(0);
  251. // Blockly相关状态
  252. let workspace = null;
  253. // 使用 Map 存储可行走点及其类型,提高查询效率
  254. let walkablePointsMap = new Map();
  255. // 创建游戏状态的响应式对象
  256. const gameState = reactive({
  257. // 地图配置信息
  258. mapConfig: {
  259. // 地图背景图片路径
  260. background: '',
  261. // 每个瓦片的尺寸(像素)
  262. tileSize: CONFIG.STYLES.DEFAULT_TILE_SIZE,
  263. },
  264. // 玩家相关状态
  265. player: {
  266. // 玩家当前位置坐标
  267. position: {},
  268. // 玩家当前朝向:0=上, 1=右, 2=下, 3=左
  269. direction: 1,
  270. // 是否正在发生碰撞
  271. isColliding: false,
  272. // 是否已到达终点
  273. hasReachedEnd: false,
  274. // 是否正在冰块上滑行
  275. isSliding: false,
  276. // 携带的物品数组
  277. carriedItems: [],
  278. },
  279. // 游戏状态信息
  280. status: {
  281. // 当前显示的游戏消息
  282. message: '',
  283. // 消息类型(如success、error、info等)
  284. messageType: ''
  285. },
  286. // 地图数据信息
  287. mapData: {
  288. // 游戏起点位置
  289. startPoint: {},
  290. // 游戏终点位置
  291. endPoint: {},
  292. // 地图上所有可行走的点坐标集合,添加type属性区分普通点和冰块
  293. walkablePoints: [],
  294. // 保存原始的可行走点数据,用于重置
  295. originalWalkablePoints: [],
  296. }
  297. });
  298. const BLOCKLY_MAP_TYPE_DICT = {
  299. ICE: 'ice',//冰块
  300. TASK: 'task',//钥匙
  301. ITEM: 'item',//物品
  302. TRAP: 'trap',//陷阱
  303. };
  304. // 计算属性 - 提高性能和可读性
  305. const mapBackground = computed(() => gameState.mapConfig.background);
  306. // const tileSize = computed(() => gameState.mapConfig.tileSize);
  307. const walkablePoints = computed(() => gameState.mapData.walkablePoints);
  308. const startPoint = computed(() => gameState.mapData.startPoint);
  309. const endPoint = computed(() => gameState.mapData.endPoint);
  310. const playerPosition = computed(() => gameState.player.position);
  311. const playerDirection = computed(() => gameState.player.direction);
  312. const isColliding = computed(() => gameState.player.isColliding);
  313. const hasReachedEnd = computed(() => gameState.player.hasReachedEnd);
  314. const gameMessage = computed(() => gameState.status.message);
  315. const messageType = computed(() => gameState.status.messageType);
  316. const isSliding = computed(() => gameState.player.isSliding);
  317. // 计算玩家图片路径,优先使用接口数据
  318. const playerImageSrc = computed(() => {
  319. if (currentGameData.value && currentGameData.value.userImage) {
  320. return currentGameData.value.userImage.trim();
  321. }
  322. return playerImage;
  323. });
  324. // 地图图片加载完成后更新容器尺寸
  325. const onMapImageLoad = () => {
  326. updateMapContainerDimensions();
  327. };
  328. // 计算实际瓦片大小(基于容器尺寸和地图数据)
  329. const tileSize = computed(() => {
  330. if (mapContainerDimensions.value.width === 0 || mapContainerDimensions.value.height === 0) {
  331. return gameState.mapConfig.tileSize;
  332. }
  333. // 获取地图数据中的最大坐标
  334. let size = JSON.parse(gameState.mapConfig.tileSize);
  335. // 计算基于容器的瓦片大小,确保地图完全可见
  336. const tileWidth = mapContainerDimensions.value.width / size.x;
  337. const tileHeight = mapContainerDimensions.value.height / size.y;
  338. // 返回较小的值以确保地图完全可见
  339. return Math.min(tileWidth, tileHeight);
  340. });
  341. // 监听props变化,当地图数据变化时更新游戏数据
  342. watch(() => [props.gameId, props.mapBackground, props.mapStartPoint, props.mapEndPoint, props.mapWalkablePoints], async () => {
  343. // 获取游戏数据
  344. await fetchGameData();
  345. // 初始化可行走点集合
  346. initWalkablePointsSet();
  347. // 重置玩家位置
  348. resetPlayer();
  349. await nextTick();
  350. // 更新容器尺寸
  351. updateMapContainerDimensions();
  352. }, { deep: true });
  353. // 生命周期钩子
  354. onMounted(async () => {
  355. // 获取游戏数据
  356. await fetchGameData();
  357. // 初始化可行走点集合
  358. initWalkablePointsSet();
  359. // 注册自定义积木
  360. registerCustomBlocks();
  361. // 注册JavaScript生成器
  362. registerJavaScriptGenerators();
  363. // 初始化Blockly工作区
  364. initBlockly();
  365. // 重置玩家位置
  366. resetPlayer();
  367. await nextTick();
  368. // 添加对窗口大小变化的监听
  369. updateMapContainerDimensions();
  370. window.addEventListener('resize', updateMapContainerDimensions);
  371. });
  372. // 获取游戏数据
  373. const fetchGameData = async () => {
  374. try {
  375. // 优先使用props传递的数据
  376. if (props.gameId && props.mapBackground) {
  377. // 使用props数据构建游戏数据对象
  378. currentGameData.value = {
  379. mapBackground: props.mapBackground,
  380. mapTileSize: props.mapTileSize,
  381. mapStartPoint: props.mapStartPoint,
  382. mapEndPoint: props.mapEndPoint,
  383. mapWalkablePoints: props.mapWalkablePoints,
  384. userDirection: props.userDirection,
  385. userImage: props.userImage,
  386. info: props.info
  387. };
  388. // 直接更新游戏状态
  389. await updateGameStateFromData(currentGameData.value);
  390. // 数据更新后强制刷新容器尺寸(等待DOM更新)
  391. await nextTick();
  392. updateMapContainerDimensions();
  393. } else {
  394. // 如果没有props数据,则从API获取
  395. const gameId = route.query.gameId || props.gameId;
  396. const nameFromRoute = route.query.gameName;
  397. const sortFromRoute = route.query.gameSort;
  398. if (nameFromRoute) {
  399. gameTitle.value = nameFromRoute;
  400. }
  401. if (sortFromRoute) {
  402. gameSort.value = sortFromRoute;
  403. }
  404. let mapGameData = await getMapGameById(gameId);
  405. if (mapGameData.code === 0) {
  406. currentGameData.value = mapGameData?.data;
  407. // 使用接口数据
  408. if (currentGameData.value && currentGameData.value.sort) {
  409. let sortNum = currentGameData.value.sort;
  410. gameSort.value = sortNum > 9 ? `Game${sortNum}` : `Game${sortNum}`;
  411. }
  412. await updateGameStateFromData(currentGameData.value);
  413. // 数据更新后强制刷新容器尺寸(等待DOM更新)
  414. await nextTick();
  415. updateMapContainerDimensions();
  416. }
  417. }
  418. } catch (error) {
  419. console.error('获取游戏数据失败:', error);
  420. }
  421. };
  422. // 根据获取到的数据更新游戏状态
  423. const updateGameStateFromData = (gameData) => {
  424. try {
  425. // 更新地图配置
  426. gameState.mapConfig.background = gameData.mapBackground ? gameData.mapBackground.trim() : '';
  427. gameState.mapConfig.tileSize = gameData.mapTileSize || CONFIG.STYLES.DEFAULT_TILE_SIZE;
  428. // 更新玩家方向
  429. if (gameData.userDirection) {
  430. playerInitialDirection.value = gameData.userDirection;
  431. }
  432. // 更新地图数据
  433. // 地图起点
  434. if (gameData.mapStartPoint) {
  435. const startPoint = JSON.parse(gameData.mapStartPoint);
  436. gameState.mapData.startPoint = { x: startPoint.x, y: startPoint.y };
  437. gameState.player.position = { x: startPoint.x, y: startPoint.y };
  438. }
  439. // 地图终点
  440. if (gameData.mapEndPoint) {
  441. const endPoint = JSON.parse(gameData.mapEndPoint);
  442. gameState.mapData.endPoint = { x: endPoint.x, y: endPoint.y };
  443. }
  444. if (gameData.mapWalkablePoints) {
  445. gameState.mapData.walkablePoints = JSON.parse(gameData.mapWalkablePoints);
  446. }
  447. // 重新初始化可行走点集合
  448. initWalkablePointsSet();
  449. } catch (error) {
  450. console.error('更新游戏状态失败:', error);
  451. }
  452. };
  453. // 初始化可行走点映射
  454. function initWalkablePointsSet() {
  455. walkablePointsMap.clear();
  456. gameState.mapData.walkablePoints.forEach(point => {
  457. walkablePointsMap.set(`${point.x},${point.y}`, point);
  458. });
  459. // 保存原始的可行走点数据,用于重置
  460. gameState.mapData.originalWalkablePoints = JSON.parse(JSON.stringify(gameState.mapData.walkablePoints));
  461. }
  462. // 可行走检查函数
  463. function isWalkable(x, y) {
  464. return walkablePointsMap.has(`${x},${y}`);
  465. }
  466. // 计算点的样式
  467. function getPointStyle(point) {
  468. const style = {
  469. left: point.x * tileSize.value - tileSize.value + 'px',
  470. top: point.y * tileSize.value - tileSize.value + 'px',
  471. width: tileSize.value + 'px',
  472. height: tileSize.value + 'px',
  473. };
  474. // 如果point有img属性,则添加图标
  475. if (point.img) {
  476. const iconSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO;
  477. const marginSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN;
  478. // 重置可能影响背景图显示的样式
  479. style.backgroundColor = 'transparent';
  480. style.backgroundImage = `url(${point.img})`;
  481. style.backgroundSize = 'contain';
  482. style.backgroundPosition = 'center';
  483. style.backgroundRepeat = 'no-repeat';
  484. // 设置与玩家相同的宽高和边距
  485. style.width = iconSize + 'px';
  486. style.height = iconSize + 'px';
  487. style.margin = marginSize + 'px';
  488. }
  489. return style;
  490. }
  491. // 计算玩家样式
  492. const playerStyle = computed(() => ({
  493. left: playerPosition.value.x * tileSize.value - tileSize.value + 'px',
  494. top: playerPosition.value.y * tileSize.value - tileSize.value + 'px',
  495. transform: `rotate(${playerDirection.value * 90}deg)`,
  496. '--player-rotation': `${playerDirection.value * 90}deg`,
  497. '--player-image': `url(${playerImageSrc.value})`,
  498. width: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO) + 'px',
  499. height: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO) + 'px',
  500. margin: (tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN) + 'px',
  501. }));
  502. // 计算携带物品样式
  503. function getCarriedItemStyle(index, item) {
  504. const baseSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO * 0.5;
  505. return {
  506. position: 'relative',
  507. width: baseSize + 'px',
  508. height: baseSize + 'px',
  509. backgroundSize: 'contain',
  510. backgroundPosition: 'center',
  511. backgroundRepeat: 'no-repeat',
  512. backgroundImage: `url(${item.img})`,
  513. animationDelay: index * 0.1 + 's'
  514. };
  515. }
  516. // 倒计时样式计算
  517. const countdownStyle = computed(() => {
  518. return {
  519. position: 'absolute',
  520. left: playerPosition.value.x * tileSize.value - tileSize.value - (tileSize.value * 0.2) + 'px',
  521. top: playerPosition.value.y * tileSize.value - tileSize.value - (tileSize.value * 0.2) + 'px',
  522. width: tileSize.value * 0.5 + 'px',
  523. height: tileSize.value * 0.5 + 'px',
  524. display: 'flex',
  525. justifyContent: 'center',
  526. alignItems: 'center',
  527. zIndex: 100
  528. };
  529. });
  530. // 注册自定义积木
  531. function registerCustomBlocks() {
  532. // 向前移动积木
  533. Blockly.Blocks['move_forward'] = {
  534. init: function() {
  535. this.jsonInit({
  536. "type": "move_forward",
  537. "message0": "向前移动",
  538. "previousStatement": null,
  539. "nextStatement": null,
  540. "colour": 230,
  541. "tooltip": "控制角色向前移动一格",
  542. "helpUrl": ""
  543. });
  544. }
  545. };
  546. // 向左转积木
  547. Blockly.Blocks['turn_left'] = {
  548. init: function() {
  549. this.jsonInit({
  550. "type": "turn_left",
  551. "message0": "向左转",
  552. "previousStatement": null,
  553. "nextStatement": null,
  554. "colour": 230,
  555. "tooltip": "控制角色向左转",
  556. "helpUrl": ""
  557. });
  558. }
  559. };
  560. // 向右转积木
  561. Blockly.Blocks['turn_right'] = {
  562. init: function() {
  563. this.jsonInit({
  564. "type": "turn_right",
  565. "message0": "向右转",
  566. "previousStatement": null,
  567. "nextStatement": null,
  568. "colour": 230,
  569. "tooltip": "控制角色向右转",
  570. "helpUrl": ""
  571. });
  572. }
  573. };
  574. // 向后转积木
  575. Blockly.Blocks['turn_around'] = {
  576. init: function() {
  577. this.jsonInit({
  578. "type": "turn_around",
  579. "message0": "向后转",
  580. "previousStatement": null,
  581. "nextStatement": null,
  582. "colour": 230,
  583. "tooltip": "控制角色向后转",
  584. "helpUrl": ""
  585. });
  586. }
  587. };
  588. // 拾取物品积木
  589. Blockly.Blocks['pickup_item'] = {
  590. init: function() {
  591. this.jsonInit({
  592. "type": "pickup_item",
  593. "message0": "拾取物品",
  594. "previousStatement": null,
  595. "nextStatement": null,
  596. "colour": 30,
  597. "tooltip": "尝试拾取当前位置的物品",
  598. "helpUrl": ""
  599. });
  600. }
  601. };
  602. // 使用物品积木
  603. Blockly.Blocks['use_item'] = {
  604. init: function() {
  605. this.jsonInit({
  606. "type": "use_item",
  607. "message0": "使用物品",
  608. "previousStatement": null,
  609. "nextStatement": null,
  610. "colour": 30,
  611. "tooltip": "在当前位置使用物品",
  612. "helpUrl": ""
  613. });
  614. }
  615. };
  616. // 暂停积木
  617. Blockly.Blocks['pause'] = {
  618. init: function() {
  619. this.jsonInit({
  620. "type": "pause",
  621. "message0": "暂停 %1 秒",
  622. "args0": [
  623. {
  624. "type": "field_number",
  625. "name": "SECONDS",
  626. "value": 1,
  627. "min": 1,
  628. "max": 10,
  629. "precision": 1
  630. }
  631. ],
  632. "previousStatement": null,
  633. "nextStatement": null,
  634. "colour": 0,
  635. "tooltip": "让角色在原地停留指定的秒数",
  636. "helpUrl": ""
  637. });
  638. }
  639. };
  640. }
  641. // 注册JavaScript生成器
  642. function registerJavaScriptGenerators() {
  643. // 向前移动生成器
  644. javascriptGenerator.forBlock['move_forward'] = function(block) {
  645. return 'await moveForward();\n';
  646. };
  647. // 向左转生成器
  648. javascriptGenerator.forBlock['turn_left'] = function(block) {
  649. return 'await turnLeft();\n';
  650. };
  651. // 向右转生成器
  652. javascriptGenerator.forBlock['turn_right'] = function(block) {
  653. return 'await turnRight();\n';
  654. };
  655. // 向后转生成器
  656. javascriptGenerator.forBlock['turn_around'] = function(block) {
  657. return 'await turnAround();\n';
  658. };
  659. // 拾取物品生成器
  660. javascriptGenerator.forBlock['pickup_item'] = function(block) {
  661. return 'await pickupItem();\n';
  662. };
  663. // 使用物品生成器
  664. javascriptGenerator.forBlock['use_item'] = function(block) {
  665. return 'await useItem();\n';
  666. };
  667. // 暂停生成器
  668. javascriptGenerator.forBlock['pause'] = function(block) {
  669. const seconds = block.getFieldValue('SECONDS');
  670. return `await pause(${seconds});\n`;
  671. };
  672. // 为重复循环块注册自定义生成器,确保支持异步操作
  673. javascriptGenerator.forBlock['controls_repeat_ext'] = function(block) {
  674. const repeats = javascriptGenerator.valueToCode(block, 'TIMES', javascriptGenerator.ORDER_ATOMIC) || '0';
  675. // 确保获取到的是数字类型,如果是字符串需要转换
  676. const safeRepeats = `(function() {
  677. const num = Number(${repeats});
  678. return isNaN(num) ? 0 : Math.max(0, Math.floor(num));
  679. })()`;
  680. // 获取循环体代码
  681. const branch = javascriptGenerator.statementToCode(block, 'DO');
  682. // 生成支持异步的循环代码
  683. let code = `for (let i = 0; i < ${safeRepeats}; i++) {\n`;
  684. code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT);
  685. code += '}\n';
  686. return code;
  687. };
  688. // 为while/until循环块注册自定义生成器
  689. // javascriptGenerator.forBlock['controls_whileUntil'] = function(blockly) {
  690. // const until = blockly.getFieldValue('MODE') === 'UNTIL';
  691. // const condition = javascriptGenerator.valueToCode(blockly, 'CONDITION',
  692. // javascriptGenerator.ORDER_NONE) || 'false';
  693. // const branch = javascriptGenerator.statementToCode(blockly, 'DO');
  694. // // 修复变量作用域问题,使用IIFE包装循环
  695. // let code = '(async function() {\n';
  696. // code += ' let loopCount = 0;\n';
  697. // code += until ? ' while (!((' + condition + ')) && loopCount < ' + CONFIG.GAME.MAX_LOOP_COUNT + ') {\n' :
  698. // ' while (((' + condition + ')) && loopCount < ' + CONFIG.GAME.MAX_LOOP_COUNT + ') {\n';
  699. // code += javascriptGenerator.prefixLines(branch, javascriptGenerator.INDENT + ' ');
  700. // code += ' loopCount++';
  701. // code += ' await new Promise(resolve => setTimeout(resolve, ' + CONFIG.DELAY.LOOP_PREVENTION + '));\n'; // 防止UI阻塞
  702. // code += ' }\n';
  703. // code += '})();\n';
  704. // return code;
  705. // };
  706. // 为text_print块添加生成器,用于调试
  707. javascriptGenerator.forBlock['text_print'] = function(block) {
  708. const msg = javascriptGenerator.valueToCode(block, 'TEXT', javascriptGenerator.ORDER_NONE) || '';
  709. return msg;
  710. };
  711. }
  712. const setupBlocklyChineseLocale = () => {
  713. // 覆盖默认的英文文本为中文
  714. if (!Blockly.Msg) Blockly.Msg = {};
  715. // 逻辑积木中文配置
  716. Blockly.Msg.CONTROLS_IF_MSG_IF = "如果";
  717. Blockly.Msg.CONTROLS_IF_MSG_ELSEIF = "否则如果";
  718. Blockly.Msg.CONTROLS_IF_MSG_ELSE = "否则";
  719. Blockly.Msg.CONTROLS_IF_MSG_DO = "执行"; // 添加这行将'do'转换为中文
  720. Blockly.Msg.CONTROLS_IF_TOOLTIP_1 = "如果条件为真,则执行相应的代码。";
  721. Blockly.Msg.CONTROLS_IF_TOOLTIP_2 = "如果条件为真,则执行相应的代码;否则执行其他代码。";
  722. Blockly.Msg.CONTROLS_IF_TOOLTIP_3 = "如果条件为真,则执行相应的代码;否则检查其他条件。";
  723. // 添加设置按钮相关的中文配置
  724. Blockly.Msg.CONTROLS_IF_ELSEIF_TOOLTIP = "否则如果条件为真,则执行相应的代码。";
  725. Blockly.Msg.CONTROLS_IF_ELSE_TOOLTIP = "否则执行相应的代码。";
  726. // 打开/关闭块的提示文本
  727. Blockly.Msg.CONTROLS_IF_TOOLTIP_IF = "添加或删除条件。";
  728. Blockly.Msg.CONTROLS_IF_TOOLTIP_ELSE = "添加或删除否则块。";
  729. // 比较运算符中文配置 - 添加显示文本
  730. Blockly.Msg.LOGIC_COMPARE_EQ = "等于";
  731. Blockly.Msg.LOGIC_COMPARE_NEQ = "不等于";
  732. Blockly.Msg.LOGIC_COMPARE_LT = "小于";
  733. Blockly.Msg.LOGIC_COMPARE_LTE = "小于等于";
  734. Blockly.Msg.LOGIC_COMPARE_GT = "大于";
  735. Blockly.Msg.LOGIC_COMPARE_GTE = "大于等于";
  736. // 比较运算符提示文本(已存在)
  737. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_EQ = "比较两个值是否相等。";
  738. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_NEQ = "比较两个值是否不相等。";
  739. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LT = "比较第一个值是否小于第二个值。";
  740. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_LTE = "比较第一个值是否小于或等于第二个值。";
  741. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GT = "比较第一个值是否大于第二个值。";
  742. Blockly.Msg.LOGIC_COMPARE_TOOLTIP_GTE = "比较第一个值是否大于或等于第二个值。";
  743. // 逻辑运算中文配置 - 添加显示文本
  744. Blockly.Msg.LOGIC_OPERATION_AND = "且";
  745. Blockly.Msg.LOGIC_OPERATION_OR = "或";
  746. // 逻辑运算提示文本(已存在)
  747. Blockly.Msg.LOGIC_OPERATION_TOOLTIP_AND = "如果两个条件都为真,则结果为真。";
  748. Blockly.Msg.LOGIC_OPERATION_TOOLTIP_OR = "如果任一条件为真,则结果为真。";
  749. // 布尔值配置
  750. Blockly.Msg.LOGIC_BOOLEAN_TRUE = "真";
  751. Blockly.Msg.LOGIC_BOOLEAN_FALSE = "假";
  752. Blockly.Msg.LOGIC_BOOLEAN_TOOLTIP = "返回一个布尔值:真或假。";
  753. // 循环积木中文配置(保持不变)
  754. Blockly.Msg.CONTROLS_REPEAT_TITLE = "重复%1次";
  755. Blockly.Msg.CONTROLS_REPEAT_TOOLTIP = "重复执行内部代码指定次数。";
  756. // Blockly.Msg.CONTROLS_WHILEUNTIL_TITLE_WHILE = "当%1时重复";
  757. // Blockly.Msg.CONTROLS_WHILEUNTIL_TITLE_UNTIL = "重复直到%1";
  758. // Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_WHILE = "只要条件为真,就重复执行内部代码。";
  759. // Blockly.Msg.CONTROLS_WHILEUNTIL_TOOLTIP_UNTIL = "重复执行内部代码,直到条件变为真。";
  760. // 数学积木中文配置(保持不变)
  761. Blockly.Msg.MATH_NUMBER_TOOLTIP = "一个数字。在编辑器中双击以更改。";
  762. Blockly.Msg.MATH_ADDITION_SYMBOL = "加";
  763. Blockly.Msg.MATH_SUBTRACTION_SYMBOL = "减";
  764. Blockly.Msg.MATH_MULTIPLICATION_SYMBOL = "乘";
  765. Blockly.Msg.MATH_DIVISION_SYMBOL = "除";
  766. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_ADD = "返回两个数的和。";
  767. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_SUBTRACT = "返回第一个数减去第二个数的差。";
  768. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_MULTIPLY = "返回两个数的积。";
  769. Blockly.Msg.MATH_ARITHMETIC_TOOLTIP_DIVIDE = "返回第一个数除以第二个数的商。";
  770. }
  771. // 初始化Blockly工作区
  772. function initBlockly() {
  773. // 应用中文配置
  774. setupBlocklyChineseLocale();
  775. const toolbox = document.getElementById('toolbox');
  776. workspace = Blockly.inject('blocklyDiv', {
  777. toolbox: toolbox,
  778. collapse: false,
  779. comments: true,
  780. disable: false, // 设为false以允许编辑
  781. maxBlocks: Infinity,
  782. trashcan: true,
  783. horizontalLayout: false,
  784. toolboxPosition: 'start',
  785. toolboxCollapse: false, // 设置工具箱默认展开
  786. toolboxAlwaysExpanded: true, // 确保点击类别后保持展开状态
  787. css: true,
  788. media: 'https://unpkg.com/blockly/media/',
  789. rtl: false,
  790. scrollbars: true,
  791. sounds: false, // 禁用声音以提高性能
  792. oneBasedIndex: true,
  793. grid: {
  794. spacing: 20,
  795. length: 3,
  796. colour: "#ccc",
  797. snap: true
  798. },
  799. zoom: {
  800. controls: true,
  801. wheel: true,
  802. startScale: 1.0,
  803. maxScale: 3,
  804. minScale: 0.3,
  805. scaleSpeed: 1.2
  806. }
  807. });
  808. }
  809. // 平滑移动函数
  810. async function smoothMoveTo(targetX, targetY) {
  811. const startX = playerPosition.value.x;
  812. const startY = playerPosition.value.y;
  813. const startTime = performance.now();
  814. // 使用Promise包装动画过程,使其可以await
  815. return new Promise(resolve => {
  816. function animate(currentTime) {
  817. // 检查是否应该停止执行
  818. if (shouldStopExecution) {
  819. resolve();
  820. return;
  821. }
  822. const elapsed = currentTime - startTime;
  823. const progress = Math.min(elapsed / CONFIG.ANIMATION.MOVE_DURATION, 1); // 计算进度,最大为1
  824. // 线性插值计算当前位置
  825. const currentX = startX + (targetX - startX) * progress;
  826. const currentY = startY + (targetY - startY) * progress;
  827. gameState.player = {
  828. ...gameState.player,
  829. position: { x: currentX, y: currentY },
  830. };
  831. // 检查是否到达终点
  832. if (progress < 1) {
  833. // 继续动画
  834. requestAnimationFrame(animate);
  835. } else {
  836. resolve(); // 动画完成
  837. }
  838. }
  839. // 启动动画
  840. requestAnimationFrame(animate);
  841. });
  842. }
  843. // 处理地图类型逻辑
  844. async function switchMapType(type, isMapType = null) {
  845. //取人物当前位置
  846. let x = playerPosition.value.x;
  847. let y = playerPosition.value.y;
  848. let tileMap = walkablePointsMap.get(`${x},${y}`);
  849. //判断是否是指定地图类型
  850. if (isMapType) {
  851. return isMapType === tileMap.type;
  852. }
  853. //移动前置
  854. if (type === 0) {
  855. //判断方块类型并处理逻辑
  856. switch (tileMap.type) {
  857. case BLOCKLY_MAP_TYPE_DICT.TASK:
  858. await taskLogic(tileMap);
  859. break;
  860. }
  861. }else {//移动后置
  862. //判断方块类型并处理逻辑
  863. switch (tileMap.type) {
  864. case BLOCKLY_MAP_TYPE_DICT.ICE:
  865. do {
  866. showGameMessage(tileMap.tip, 'warning',300)
  867. // 处理方块类型逻辑
  868. await switchMapType(0);
  869. console.log("滑行前位置:" + playerPosition.value.x + "," + playerPosition.value.y);
  870. await slidingLogic();
  871. tileMap = walkablePointsMap.get(`${playerPosition.value.x},${playerPosition.value.y}`);
  872. }while (tileMap.type === BLOCKLY_MAP_TYPE_DICT.ICE && !isColliding.value)
  873. break;
  874. case BLOCKLY_MAP_TYPE_DICT.TRAP:
  875. showGameMessage(tileMap.tip, 'error')
  876. await handleWallCollision(tileMap.tip);
  877. break;
  878. }
  879. }
  880. }
  881. // 处理冰块滑行逻辑
  882. async function slidingLogic() {
  883. if (shouldStopExecution || isColliding.value) {
  884. return;
  885. }
  886. gameState.player.isSliding = true;
  887. try {
  888. // 计算下一个位置
  889. let nextX = playerPosition.value.x;
  890. let nextY = playerPosition.value.y;
  891. // 根据当前方向计算下一个位置
  892. switch(playerDirection.value) {
  893. case CONFIG.GAME.DIRECTIONS.UP: nextY--; break;
  894. case CONFIG.GAME.DIRECTIONS.RIGHT: nextX++; break;
  895. case CONFIG.GAME.DIRECTIONS.DOWN: nextY++; break;
  896. case CONFIG.GAME.DIRECTIONS.LEFT: nextX--; break;
  897. }
  898. // 检查下一个位置是否可行走
  899. if (isWalkable(nextX, nextY)) {
  900. // 执行平滑移动到下一个位置
  901. await smoothMoveTo(nextX, nextY);
  902. } else {
  903. // 使用统一的碰撞处理方法,但不等待延迟(因为slidingLogic不需要这个延迟)
  904. await handleWallCollision();
  905. }
  906. } catch (error) {
  907. console.error('滑行过程中发生错误:', error);
  908. } finally {
  909. // 无论如何都要确保滑行状态被重置
  910. gameState.player.isSliding = false;
  911. }
  912. }
  913. // 处理任务逻辑
  914. async function taskLogic(tileMap) {
  915. if (shouldStopExecution || isColliding.value) {
  916. return;
  917. }
  918. try {
  919. // 判断当前位置是否有特殊需求
  920. if (tileMap && tileMap.type === BLOCKLY_MAP_TYPE_DICT.TASK && tileMap.must === true && tileMap.status !== true) {
  921. await handleWallCollision(tileMap.unfinishedTip);
  922. return;
  923. }
  924. } catch (error) {
  925. console.error('处理任务逻辑发生错误:', error);
  926. }
  927. }
  928. // 物品拾取动画函数
  929. async function animateItemPickup(item, itemX, itemY) {
  930. // 创建临时动画元素
  931. const tempItem = document.createElement('div');
  932. const iconSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO;
  933. const marginSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN;
  934. // 计算物品在地图上的实际位置
  935. const itemLeft = itemX * tileSize.value - tileSize.value + marginSize;
  936. const itemTop = itemY * tileSize.value - tileSize.value + marginSize;
  937. // 平行移动到容器位置,同时调整大小
  938. const finalSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO * 0.5;
  939. // 获取携带物品容器的位置(左上角)
  940. // 注意:这里不需要考虑当前已携带物品数量,因为物品还没被添加
  941. let containerLeft = 30;
  942. let containerTop = 30;
  943. // 如果已经有物品,计算新物品应该出现的位置
  944. if (gameState.player.carriedItems.length > 0) {
  945. let containerSize = finalSize + 10;
  946. containerLeft = 30 + gameState.player.carriedItems.length * containerSize;
  947. }
  948. // 设置临时元素样式
  949. Object.assign(tempItem.style, {
  950. position: 'absolute',
  951. left: itemLeft + 'px',
  952. top: itemTop + 'px',
  953. width: iconSize + 'px',
  954. height: iconSize + 'px',
  955. backgroundImage: `url(${item.img})`,
  956. backgroundSize: 'contain',
  957. backgroundPosition: 'center',
  958. backgroundRepeat: 'no-repeat',
  959. zIndex: '100', // 确保在最上层
  960. opacity: '0', // 初始完全透明
  961. transform: 'scale(1)',
  962. });
  963. // 将临时元素添加到地图容器
  964. const mapBackground = document.querySelector('.map-background');
  965. if (!mapBackground) {
  966. console.error('地图容器未找到');
  967. return;
  968. }
  969. mapBackground.appendChild(tempItem);
  970. // 触发淡入动画
  971. tempItem.offsetHeight;
  972. tempItem.style.transition = 'opacity ' + CONFIG.DELAY.ITEMS_APPEAR + 'ms ease-out';
  973. tempItem.style.opacity = '1'; // 完全显示
  974. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_APPEAR));
  975. // 移动动画
  976. tempItem.style.transition = 'all ' + CONFIG.DELAY.ITEMS_FLIGHT_ANIMATION_DELAY + 'ms ease-out'; // 减慢动画速度
  977. Object.assign(tempItem.style, {
  978. left: containerLeft + 'px',
  979. top: containerTop + 'px',
  980. width: finalSize + 'px',
  981. height: finalSize + 'px',
  982. opacity: '0.8',
  983. transform: 'scale(1)',
  984. });
  985. // 等待动画完成
  986. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_FLIGHT_ANIMATION_DELAY));
  987. // 移除临时元素
  988. if (mapBackground.contains(tempItem)) {
  989. mapBackground.removeChild(tempItem);
  990. }
  991. }
  992. // 物品使用动画函数
  993. async function animateItemUse(item, itemIndex) {
  994. // 创建临时动画元素
  995. const tempItem = document.createElement('div');
  996. const finalSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO * 0.5;
  997. const iconSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_RATIO;
  998. const marginSize = tileSize.value * CONFIG.STYLES.PLAYER_SIZE_MARGIN;
  999. // 计算物品在物品栏中的初始位置
  1000. let startLeft = 30;
  1001. let startTop = 30;
  1002. let containerSize = finalSize + 10;
  1003. // 根据物品索引计算在物品栏中的位置
  1004. if (itemIndex > 0) {
  1005. startLeft = 30 + itemIndex * containerSize;
  1006. }
  1007. // 计算玩家当前位置(物品目标位置)
  1008. const playerLeft = playerPosition.value.x * tileSize.value - tileSize.value + marginSize;
  1009. const playerTop = playerPosition.value.y * tileSize.value - tileSize.value + marginSize;
  1010. // 获取玩家元素
  1011. const playerElement = document.querySelector('.player');
  1012. const originalPlayerZIndex = playerElement ? playerElement.style.zIndex : '';
  1013. // 获取当前位置的任务点元素
  1014. let taskPointElement = null;
  1015. const walkablePointsElements = document.querySelectorAll('.walkable-point');
  1016. walkablePointsElements.forEach(el => {
  1017. const rect = el.getBoundingClientRect();
  1018. const targetRect = {
  1019. left: playerLeft,
  1020. top: playerTop,
  1021. width: iconSize,
  1022. height: iconSize
  1023. };
  1024. // 简单判断元素是否在玩家位置附近
  1025. if (Math.abs(rect.left - targetRect.left) < iconSize &&
  1026. Math.abs(rect.top - targetRect.top) < iconSize) {
  1027. taskPointElement = el;
  1028. }
  1029. });
  1030. // 先将任务图标置顶盖住人物
  1031. if (taskPointElement) {
  1032. taskPointElement.style.zIndex = '150';
  1033. }
  1034. // 设置临时元素初始样式
  1035. Object.assign(tempItem.style, {
  1036. position: 'absolute',
  1037. left: startLeft + 'px',
  1038. top: startTop + 'px',
  1039. width: finalSize + 'px',
  1040. height: finalSize + 'px',
  1041. backgroundImage: `url(${item.img})`,
  1042. backgroundSize: 'contain',
  1043. backgroundPosition: 'center',
  1044. backgroundRepeat: 'no-repeat',
  1045. zIndex: '120',
  1046. transition: 'transform ' + CONFIG.DELAY.ITEMS_APPEAR + 'ms ease-out',
  1047. transform: 'scale(1)',
  1048. });
  1049. // 将临时元素添加到地图容器
  1050. const mapBackground = document.querySelector('.map-background');
  1051. if (!mapBackground) {
  1052. console.error('地图容器未找到');
  1053. return;
  1054. }
  1055. mapBackground.appendChild(tempItem);
  1056. // 准备漂移动画
  1057. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_APPEAR));
  1058. // 设置漂移动画样式
  1059. tempItem.style.transition = 'all 1s ease-out';
  1060. Object.assign(tempItem.style, {
  1061. left: playerLeft + 'px',
  1062. top: playerTop + 'px',
  1063. width: iconSize + 'px',
  1064. height: iconSize + 'px',
  1065. });
  1066. // 等待漂移到玩家位置
  1067. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_FLIGHT_ANIMATION_DELAY));
  1068. // 物品使用效果动画
  1069. tempItem.style.transition = 'transform 0.3s ease-in-out';
  1070. tempItem.style.transform = 'scale(1.2)';
  1071. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_APPEAR));
  1072. // 移除临时元素
  1073. if (mapBackground.contains(tempItem)) {
  1074. mapBackground.removeChild(tempItem);
  1075. }
  1076. // 延迟一段时间后将人物图标置顶,露出完整的人物图标
  1077. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ITEMS_APPEAR));
  1078. // 恢复层级关系
  1079. if (taskPointElement) {
  1080. taskPointElement.style.zIndex = '';
  1081. }
  1082. if (playerElement) {
  1083. playerElement.style.zIndex = originalPlayerZIndex || '';
  1084. }
  1085. }
  1086. // 拾取物品函数
  1087. window.pickupItem = async function() {
  1088. if (shouldStopExecution || isColliding.value || isSliding.value) {
  1089. return;
  1090. }
  1091. //取人物当前位置
  1092. let x = playerPosition.value.x;
  1093. let y = playerPosition.value.y;
  1094. let tileMap = walkablePointsMap.get(`${x},${y}`);
  1095. // 判断是否是要拾取的方块类型
  1096. if (tileMap && tileMap.type === BLOCKLY_MAP_TYPE_DICT.ITEM) {
  1097. showGameMessage(tileMap.tip || CONFIG.TIPS.PICKUP_ITEM, 'warning')
  1098. // 处理携带物品逻辑
  1099. if (tileMap && tileMap.img) {
  1100. // 从地图上移除图标(但保留点的可通行性)
  1101. const pointIndex = gameState.mapData.walkablePoints.findIndex(
  1102. p => p.x === x && p.y === y
  1103. );
  1104. if (pointIndex !== -1) {
  1105. // 保留点但移除img属性
  1106. const updatedPoint = { ...gameState.mapData.walkablePoints[pointIndex] };
  1107. delete updatedPoint.img;
  1108. gameState.mapData.walkablePoints.splice(pointIndex, 1, updatedPoint);
  1109. // 更新映射
  1110. walkablePointsMap.set(`${x},${y}`, updatedPoint);
  1111. // 执行物品拾取动画:放大晃动两下然后移动到左上角物品容器
  1112. await animateItemPickup(tileMap, x, y);
  1113. // 将物品添加到玩家携带物品中
  1114. gameState.player.carriedItems.push({
  1115. ...tileMap,
  1116. originalX: x,
  1117. originalY: y
  1118. });
  1119. }
  1120. }
  1121. } else {
  1122. showGameMessage(CONFIG.TIPS.NULL_PICKUP_ITEM, 'info')
  1123. }
  1124. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1125. }
  1126. // 使用物品函数
  1127. window.useItem = async function() {
  1128. if (shouldStopExecution || isColliding.value || isSliding.value) {
  1129. return;
  1130. }
  1131. //取人物当前位置
  1132. let x = playerPosition.value.x;
  1133. let y = playerPosition.value.y;
  1134. let tileMap = walkablePointsMap.get(`${x},${y}`);
  1135. // 判断当前位置是否有特殊需求
  1136. if (tileMap && tileMap.type === BLOCKLY_MAP_TYPE_DICT.TASK) {
  1137. // 检查玩家是否携带了需要的物品
  1138. const requiredItems = tileMap.type;
  1139. let hasRequiredItem = false;
  1140. let itemIndex = -1;
  1141. if (gameState.player.carriedItems.length > 0) {
  1142. hasRequiredItem = true;
  1143. itemIndex = 0;
  1144. }
  1145. if (hasRequiredItem) {
  1146. // 获取要使用的物品
  1147. const itemToUse = gameState.player.carriedItems[itemIndex];
  1148. // 执行物品使用动画
  1149. await animateItemUse(itemToUse, itemIndex);
  1150. // 从携带物品中移除已使用的物品
  1151. gameState.player.carriedItems.splice(itemIndex, 1);
  1152. // 从地图上移除图标(但保留点的可通行性)
  1153. const pointIndex = gameState.mapData.walkablePoints.findIndex(
  1154. p => p.x === x && p.y === y
  1155. );
  1156. if (pointIndex !== -1) {
  1157. // 保留点但移除img属性并设置完成状态图标
  1158. const updatedPoint = { ...gameState.mapData.walkablePoints[pointIndex] };
  1159. updatedPoint.img = updatedPoint.endImg; // 设置完成状态图标
  1160. updatedPoint.status = true;
  1161. gameState.mapData.walkablePoints.splice(pointIndex, 1, updatedPoint);
  1162. // 更新映射
  1163. walkablePointsMap.set(`${x},${y}`, updatedPoint);
  1164. }
  1165. // 使用物品成功
  1166. showGameMessage(tileMap.finishedTip || CONFIG.TIPS.USE_ITEM_SUCCESS, 'success');
  1167. } else {
  1168. // 提示缺少所需物品
  1169. showGameMessage(tileMap.unfinishedTip || CONFIG.TIPS.USE_SPECIAL_ITEM, 'warning');
  1170. }
  1171. } else {
  1172. showGameMessage(CONFIG.TIPS.NO_USE_ITEM, 'info');
  1173. }
  1174. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1175. }
  1176. // 暂停函数
  1177. window.pause = async function(seconds) {
  1178. if (shouldStopExecution || isSliding.value) {
  1179. return;
  1180. }
  1181. // 显示倒计时
  1182. showCountdown.value = true;
  1183. countdownValue.value = seconds;
  1184. // 倒计时循环
  1185. while (countdownValue.value > 0 && !shouldStopExecution) {
  1186. await new Promise(resolve => setTimeout(resolve, 1000));
  1187. countdownValue.value--;
  1188. }
  1189. // 隐藏倒计时
  1190. showCountdown.value = false;
  1191. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1192. }
  1193. // 向前移动
  1194. window.moveForward = async function() {
  1195. if (shouldStopExecution || isColliding.value || isSliding.value) {
  1196. return;
  1197. }
  1198. let newX = playerPosition.value.x;
  1199. let newY = playerPosition.value.y;
  1200. // 向前移动
  1201. switch(playerDirection.value) {
  1202. case CONFIG.GAME.DIRECTIONS.UP: newY--; break;
  1203. case CONFIG.GAME.DIRECTIONS.RIGHT: newX++; break;
  1204. case CONFIG.GAME.DIRECTIONS.DOWN: newY++; break;
  1205. case CONFIG.GAME.DIRECTIONS.LEFT: newX--; break;
  1206. }
  1207. // 检查是否可以移动
  1208. if (isWalkable(newX, newY)) {
  1209. // 处理方块类型逻辑
  1210. await switchMapType(0);
  1211. // 使用平滑移动动画
  1212. await smoothMoveTo(newX, newY);
  1213. // 处理方块类型逻辑
  1214. await switchMapType(1);
  1215. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1216. } else {
  1217. // 发生碰撞 使用统一的碰撞处理方法
  1218. await handleWallCollision();
  1219. }
  1220. };
  1221. //向左转(逆时针旋转90度)
  1222. window.turnLeft = async function() {
  1223. // 如果已经发生过碰撞,不再执行任何旋转
  1224. if (shouldStopExecution || isColliding.value) {
  1225. return;
  1226. }
  1227. // 记录起始方向和目标方向
  1228. const startDirection = playerDirection.value;
  1229. const targetDirection = (playerDirection.value - 1 + 4) % 4;
  1230. // 实现平滑旋转
  1231. const startTime = performance.now();
  1232. // 使用 requestAnimationFrame 实现平滑动画
  1233. await new Promise(resolve => {
  1234. function animate(currentTime) {
  1235. // 检查是否应该停止执行
  1236. if (shouldStopExecution) {
  1237. resolve();
  1238. return;
  1239. }
  1240. const elapsedTime = currentTime - startTime;
  1241. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.ROTATE_DURATION, 1);
  1242. // 在动画过程中更新方向
  1243. gameState.player.direction = startDirection - progress;
  1244. // 如果动画未完成,继续下一帧
  1245. if (progress < 1) {
  1246. requestAnimationFrame(animate);
  1247. } else {
  1248. // 动画完成后设置最终方向
  1249. gameState.player.direction = targetDirection;
  1250. resolve();
  1251. }
  1252. }
  1253. // 开始动画
  1254. requestAnimationFrame(animate);
  1255. });
  1256. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1257. };
  1258. //向右转(顺时针旋转90度)
  1259. window.turnRight = async function() {
  1260. // 如果已经发生过碰撞,不再执行任何旋转
  1261. if (shouldStopExecution || isColliding.value) {
  1262. return;
  1263. }
  1264. // 记录起始方向和目标方向
  1265. const startDirection = playerDirection.value;
  1266. const targetDirection = (playerDirection.value + 1) % 4;
  1267. // 实现平滑旋转
  1268. const startTime = performance.now();
  1269. // 使用 requestAnimationFrame 实现平滑动画
  1270. await new Promise(resolve => {
  1271. function animate(currentTime) {
  1272. // 检查是否应该停止执行
  1273. if (shouldStopExecution) {
  1274. resolve();
  1275. return;
  1276. }
  1277. const elapsedTime = currentTime - startTime;
  1278. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.ROTATE_DURATION, 1);
  1279. // 处理从3到0的边界情况,确保顺时针旋转
  1280. let currentDirection;
  1281. if (startDirection === 3 && targetDirection === 0) {
  1282. // 对于从3到0的顺时针旋转,我们需要模拟+1的效果而不是-3
  1283. currentDirection = startDirection + progress;
  1284. // 当超过3.99时,设置为0(避免显示4)
  1285. if (currentDirection > 3.99) {
  1286. currentDirection = 0;
  1287. }
  1288. } else {
  1289. // 正常情况下的线性插值
  1290. currentDirection = startDirection + (targetDirection - startDirection) * progress;
  1291. }
  1292. // 在动画过程中更新方向
  1293. gameState.player.direction = currentDirection;
  1294. // 如果动画未完成,继续下一帧
  1295. if (progress < 1) {
  1296. requestAnimationFrame(animate);
  1297. } else {
  1298. // 动画完成后设置最终方向
  1299. gameState.player.direction = targetDirection;
  1300. resolve();
  1301. }
  1302. }
  1303. // 开始动画
  1304. requestAnimationFrame(animate);
  1305. });
  1306. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1307. };
  1308. // 向后转(旋转180度)
  1309. window.turnAround = async function() {
  1310. // 如果已经发生过碰撞,不再执行任何旋转
  1311. if (shouldStopExecution || isColliding.value) {
  1312. return;
  1313. }
  1314. // 记录起始方向和目标方向
  1315. const startDirection = playerDirection.value;
  1316. const targetDirection = (playerDirection.value + 2) % 4;
  1317. // 实现平滑旋转
  1318. const startTime = performance.now();
  1319. // 使用 requestAnimationFrame 实现平滑动画
  1320. await new Promise(resolve => {
  1321. function animate(currentTime) {
  1322. // 检查是否应该停止执行
  1323. if (shouldStopExecution) {
  1324. resolve();
  1325. return;
  1326. }
  1327. const elapsedTime = currentTime - startTime;
  1328. const progress = Math.min(elapsedTime / CONFIG.ANIMATION.TURN_AROUND_DURATION, 1);
  1329. // 在动画过程中更新方向
  1330. gameState.player.direction = startDirection + 2 * progress;
  1331. // 如果动画未完成,继续下一帧
  1332. if (progress < 1) {
  1333. requestAnimationFrame(animate);
  1334. } else {
  1335. // 动画完成后设置最终方向
  1336. gameState.player.direction = targetDirection;
  1337. resolve();
  1338. }
  1339. }
  1340. // 开始动画
  1341. requestAnimationFrame(animate);
  1342. });
  1343. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.ACTION_DELAY));
  1344. };
  1345. //校验是否到达终点
  1346. window.isFinish = async function() {
  1347. // 如果已经发生过碰撞,不再执行任何检查
  1348. if (isColliding.value) {
  1349. return;
  1350. }
  1351. if (gameState.player.position.x === endPoint.value.x && gameState.player.position.y === endPoint.value.y) {
  1352. //检查是否有未完成的任务点
  1353. const pointIndex = gameState.mapData.walkablePoints.findIndex(
  1354. p => p.type === BLOCKLY_MAP_TYPE_DICT.TASK && p.status !== true
  1355. );
  1356. if (pointIndex !== -1) {
  1357. showGameMessage(CONFIG.TIPS.UNFINISHED, 'error');
  1358. return;
  1359. }
  1360. gameState.player.hasReachedEnd = true;
  1361. showGameMessage(CONFIG.TIPS.FINISH, 'success' );
  1362. emits('saveProgress')
  1363. }
  1364. };
  1365. // 运行代码
  1366. const runCode = async () => {
  1367. await resetPlayer();
  1368. isRunning.value = true;
  1369. try {
  1370. await new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.RESET_DELAY));
  1371. // 重置执行标志,允许新的执行
  1372. shouldStopExecution = false;
  1373. // 创建新的AbortController用于取消执行
  1374. executionAbortController = new AbortController();
  1375. const signal = executionAbortController.signal;
  1376. // 确保生成器和工作区都存在
  1377. if (!javascriptGenerator || !workspace) {
  1378. throw new Error('生成器或工作区未正确初始化');
  1379. }
  1380. // 生成JavaScript代码
  1381. const code = javascriptGenerator.workspaceToCode(workspace) + "await isFinish();";
  1382. try {
  1383. // 增强的安全检查
  1384. const unsafePatterns = [
  1385. 'eval(', 'Function(', 'document.write', 'window.location',
  1386. 'document.createElement', 'XMLHttpRequest', 'fetch',
  1387. 'setInterval', 'setTimeout', 'window.',
  1388. 'alert(', 'confirm(', 'prompt(',
  1389. 'document.cookie', 'localStorage', 'sessionStorage'
  1390. ];
  1391. const hasUnsafeCode = unsafePatterns.some(pattern => code.includes(pattern));
  1392. if (hasUnsafeCode) {
  1393. throw new Error('代码包含不安全的操作');
  1394. }
  1395. // 包装代码为异步函数执行,并设置超时保护
  1396. currentExecutionPromise = new Promise(async (resolve, reject) => {
  1397. try {
  1398. // 检查信号是否已中止
  1399. if (signal.aborted) {
  1400. throw new Error('执行已取消');
  1401. }
  1402. // 添加信号监听
  1403. signal.addEventListener('abort', () => {
  1404. reject(new Error('执行已取消'));
  1405. });
  1406. const wrappedCode = `(async () => { ${code} })()`;
  1407. await new Function(wrappedCode)();
  1408. resolve();
  1409. } catch (error) {
  1410. reject(error);
  1411. }
  1412. });
  1413. } catch (error) {
  1414. // 捕获并显示执行错误
  1415. if (error.message !== '执行已取消') {
  1416. const errorMsg = error.message || '未知错误';
  1417. showGameMessage(`代码执行错误: ${errorMsg}`, 'error');
  1418. console.error('代码执行错误:', error);
  1419. }
  1420. } finally {
  1421. // 清除当前执行的Promise引用
  1422. currentExecutionPromise = null;
  1423. }
  1424. } catch (error) {
  1425. showGameMessage(`运行时错误: ${error.message || '未知错误'}`, 'error');
  1426. console.error('运行时错误:', error);
  1427. } finally {
  1428. isRunning.value = false;
  1429. }
  1430. };
  1431. // 重置玩家位置和状态
  1432. const resetPlayer = async () => {
  1433. isRunning.value = false;
  1434. // 设置标志强制停止所有执行
  1435. shouldStopExecution = true;
  1436. // 取消任何正在执行的代码
  1437. if (executionAbortController) {
  1438. executionAbortController.abort();
  1439. executionAbortController = null;
  1440. }
  1441. if (currentExecutionPromise) {
  1442. currentExecutionPromise = null;
  1443. }
  1444. // 重置携带的物品回地图
  1445. if (gameState.mapData.originalWalkablePoints.length > 0) {
  1446. gameState.mapData.walkablePoints = JSON.parse(JSON.stringify(gameState.mapData.originalWalkablePoints));
  1447. }
  1448. // 清空携带物品
  1449. gameState.player.carriedItems = [];
  1450. // 重新初始化可行走点集合
  1451. initWalkablePointsSet();
  1452. gameState.player.position = { ...startPoint.value };
  1453. gameState.player.direction = playerInitialDirection.value; // 重置为初始方向
  1454. gameState.player.isColliding = false; //碰撞标志
  1455. gameState.player.hasReachedEnd = false;
  1456. gameState.player.isSliding = false; // 重置滑行状态
  1457. };
  1458. // 清空工作区
  1459. const clearWorkspace = () => {
  1460. workspace.clear();
  1461. showGameMessage('工作区已清空', 'info');
  1462. };
  1463. // 更新地图容器尺寸的函数
  1464. function updateMapContainerDimensions() {
  1465. const mapContainer = document.querySelector('.map-container');
  1466. if (mapContainer) {
  1467. const rect = mapContainer.getBoundingClientRect();
  1468. // 确保获取到有效的尺寸值
  1469. if (rect.width > 0 && rect.height > 0) {
  1470. mapContainerDimensions.value = {
  1471. width: rect.width,
  1472. height: rect.height
  1473. };
  1474. } else {
  1475. // 若尺寸无效,使用默认容器尺寸(可根据实际情况调整)
  1476. mapContainerDimensions.value = {
  1477. width: 800,
  1478. height: 600
  1479. };
  1480. }
  1481. }
  1482. };
  1483. // 显示游戏消息
  1484. function showGameMessage(message, type = 'info', duration = CONFIG.DELAY.MESSAGE_DISPLAY) {
  1485. gameState.status.message = message;
  1486. gameState.status.messageType = type;
  1487. // 消息显示时间后自动清除消息
  1488. setTimeout(() => {
  1489. gameState.status.message = '';
  1490. }, duration);
  1491. }
  1492. // 统一处理撞到墙时的停止逻辑
  1493. async function handleWallCollision(endMsg = CONFIG.TIPS.NO_ENTRY) {
  1494. // 设置碰撞状态
  1495. gameState.player.isColliding = true;
  1496. // 显示错误消息
  1497. showGameMessage(endMsg, 'error');
  1498. // 立即中止整个代码执行
  1499. if (executionAbortController) {
  1500. executionAbortController.abort();
  1501. }
  1502. // 所有动画和移动操作立即停止
  1503. shouldStopExecution = true;
  1504. // 碰撞状态重置时间后取消碰撞状态
  1505. setTimeout(() => {
  1506. gameState.player.isColliding = false;
  1507. }, CONFIG.DELAY.COLLISION_RESET);
  1508. // 返回一个Promise,允许调用者等待碰撞延迟
  1509. return new Promise(resolve => setTimeout(resolve, CONFIG.DELAY.COLLISION_DELAY));
  1510. }
  1511. // 组件卸载时清理
  1512. onUnmounted(() => {
  1513. if (workspace) {
  1514. workspace.dispose();
  1515. }
  1516. window.removeEventListener('resize', updateMapContainerDimensions);
  1517. });
  1518. </script>
  1519. <style scoped lang="scss">
  1520. @use "sass:math";
  1521. @function rpx($px) {
  1522. @return math.div($px, 750) * 100vw;
  1523. }
  1524. //将tileSize属性绑定到CSS变量上
  1525. :root {
  1526. --tile-size: v-bind('tileSize + "px"');
  1527. }
  1528. /* 游戏简介样式 */
  1529. .info-message-container {
  1530. display: flex;
  1531. flex-direction: column;
  1532. align-items: flex-start;
  1533. }
  1534. .message-item {
  1535. display: flex;
  1536. align-items: flex-start;
  1537. width: 100%;
  1538. margin-bottom: rpx(5);
  1539. }
  1540. /* 头像样式 */
  1541. .avatar {
  1542. margin-right: rpx(4);
  1543. flex-shrink: 0;
  1544. }
  1545. .avatar-image {
  1546. width: rpx(30);
  1547. height: rpx(30);
  1548. object-fit: cover;
  1549. }
  1550. /* 消息内容样式 */
  1551. .message-item {
  1552. flex: 1;
  1553. }
  1554. .message-item p {
  1555. margin: rpx(4) 0;
  1556. line-height: 1.6;
  1557. font-size: rpx(7);
  1558. text-align: left;
  1559. color: black;
  1560. background-color: #e6faff;
  1561. opacity: 0.8;
  1562. border-radius: rpx(4);
  1563. padding: rpx(6);
  1564. max-width: 100%;
  1565. }
  1566. .message-item p:first-child {
  1567. margin-top: 0;
  1568. font-weight: 500;
  1569. }
  1570. .message-item p:last-child {
  1571. margin-bottom: 0;
  1572. }
  1573. .title-box {
  1574. position: relative;
  1575. top: rpx(5);
  1576. padding-left: 15px;
  1577. z-index: 10;
  1578. display: flex;
  1579. justify-content: space-between;
  1580. align-items: center;
  1581. }
  1582. /* 左侧容器样式 */
  1583. .left-container {
  1584. display: flex;
  1585. flex-direction: column;
  1586. align-items: flex-start;
  1587. gap: 10px;
  1588. }
  1589. /* 右侧两个角为圆角的长方形格子样式 */
  1590. .game-badge {
  1591. width: rpx(80);
  1592. height: rpx(20);
  1593. margin-left: rpx(3);
  1594. background-color: #5fb5dc;
  1595. color: #fff;
  1596. border-radius: 0 rpx(20) rpx(20) 0;
  1597. display: flex;
  1598. align-items: center;
  1599. justify-content: center;
  1600. font-size: rpx(15);
  1601. font-weight: bold;
  1602. }
  1603. /* 右侧容器样式 */
  1604. .right-container {
  1605. display: flex;
  1606. gap: 10px;
  1607. padding-right: 20px;
  1608. }
  1609. /* 上下节按钮样式 */
  1610. .section-button {
  1611. padding: rpx(5) rpx(12);
  1612. border: none;
  1613. border-radius: rpx(10);
  1614. background: #3498db;
  1615. color: #fff;
  1616. font-weight: 500;
  1617. cursor: pointer;
  1618. transition: all 0.3s ease;
  1619. font-size: rpx(7);
  1620. }
  1621. .section-button:hover {
  1622. background: #2980b9;
  1623. transform: translateY(-2px);
  1624. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  1625. }
  1626. .previous-btn {
  1627. background-color: rgba(255, 255, 255, 0.8);
  1628. color: #333;
  1629. }
  1630. .previous-btn:hover {
  1631. background-color: rgba(255, 255, 255, 0.9);
  1632. }
  1633. .next-btn {
  1634. background: #5fb5dc;
  1635. }
  1636. .next-btn:hover {
  1637. background: #2980b9;
  1638. }
  1639. .box-icon {
  1640. display: flex;
  1641. align-items: center;
  1642. margin-top: rpx(5);
  1643. gap: 10px;
  1644. padding: 10px 20px;
  1645. background-color: rgba(255, 255, 255, 0.8);
  1646. border-radius: 30px;
  1647. backdrop-filter: blur(10px);
  1648. cursor: pointer;
  1649. transition: all 0.3s ease;
  1650. font-size: 16px;
  1651. color: #333;
  1652. font-weight: 500;
  1653. width: fit-content;
  1654. }
  1655. .box-icon:hover {
  1656. background-color: rgba(255, 255, 255, 0.9);
  1657. transform: translate(-3px);
  1658. }
  1659. .left-icon {
  1660. font-size: 18px;
  1661. }
  1662. .content {
  1663. display: flex;
  1664. flex-wrap: nowrap;
  1665. gap: 20px;
  1666. padding: 20px;
  1667. min-width: 1160px;
  1668. }
  1669. /* 地图区域样式 */
  1670. .map-section {
  1671. flex: 1;
  1672. min-width: 500px;
  1673. background: rgba(248, 249, 250, 0.82);
  1674. padding: 15px;
  1675. border-radius: 15px;
  1676. }
  1677. .map-container {
  1678. position: relative;
  1679. width: 100%;
  1680. height: 100%;
  1681. overflow: hidden; // 防止内容溢出
  1682. }
  1683. .map-background {
  1684. position: relative;
  1685. width: 100%;
  1686. height: 100%;
  1687. background-size: cover;
  1688. background-position: center;
  1689. background-repeat: no-repeat;
  1690. }
  1691. .map-image {
  1692. width: 100%;
  1693. height: 100%;
  1694. object-fit: cover;
  1695. }
  1696. /* 可行走区域样式 */
  1697. .walkable-point {
  1698. position: absolute;
  1699. //background-color: rgba(52, 152, 219, 0.2);
  1700. //border: 1px solid rgba(52, 152, 219, 0.5);
  1701. //box-sizing: border-box;
  1702. //是否显示可行路线
  1703. opacity: 1;
  1704. }
  1705. /* 玩家样式 */
  1706. .player {
  1707. position: absolute;
  1708. background-image: var(--player-image);
  1709. background-size: contain;
  1710. background-repeat: no-repeat;
  1711. background-position: center;
  1712. border-radius: 5px;
  1713. z-index: 10;
  1714. }
  1715. /* 碰撞动画 */
  1716. .player.collision {
  1717. animation: collision 0.5s ease-in-out;
  1718. }
  1719. @keyframes collision {
  1720. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  1721. 25% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  1722. 50% { transform: rotate(var(--player-rotation)) translateX(3px) translateY(2px) scale(1.2); }
  1723. 75% { transform: rotate(var(--player-rotation)) translateX(-3px) translateY(-2px) scale(1.2); }
  1724. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0) scale(1); }
  1725. }
  1726. /* 滑行动画 */
  1727. @keyframes sliding {
  1728. 0% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  1729. 25% { transform: rotate(var(--player-rotation)) translateX(2px) translateY(0); }
  1730. 75% { transform: rotate(var(--player-rotation)) translateX(-2px) translateY(0); }
  1731. 100% { transform: rotate(var(--player-rotation)) translateX(0) translateY(0); }
  1732. }
  1733. /* 携带物品容器 */
  1734. .carried-items-container {
  1735. position: absolute;
  1736. top: 20px;
  1737. left: 20px;
  1738. background: rgba(255, 255, 255, 0.8);
  1739. border: 2px solid #3498db;
  1740. border-radius: 10px;
  1741. padding: 10px;
  1742. display: flex;
  1743. gap: 10px;
  1744. z-index: 15;
  1745. backdrop-filter: blur(10px);
  1746. animation: fadeInScale 0.5s ease-out;
  1747. }
  1748. /* 淡入缩放动画 */
  1749. @keyframes fadeInScale {
  1750. 0% {
  1751. opacity: 0;
  1752. transform: scale(0.5) translateY(-10px);
  1753. }
  1754. 100% {
  1755. opacity: 1;
  1756. transform: scale(1) translateY(0);
  1757. }
  1758. }
  1759. /* 携带物品样式 */
  1760. .carried-item {
  1761. animation: bounceIn 0.3s ease-out forwards;
  1762. }
  1763. /* 【暂停】怀表容器样式 */
  1764. .watch-container {
  1765. animation: fadeInCountdown 0.3s ease-out;
  1766. position: relative;
  1767. }
  1768. /* 【暂停】怀表表盘样式 */
  1769. .watch-face {
  1770. width: 100%;
  1771. height: 100%;
  1772. border-radius: 50%;
  1773. background: linear-gradient(145deg, rgba(240, 240, 240, 0.8), rgba(200, 200, 200, 0.6));
  1774. border: 4px solid rgba(100, 100, 100, 0.8);
  1775. box-shadow:
  1776. 0 0 20px rgba(0, 0, 0, 0.3),
  1777. inset 0 0 20px rgba(0, 0, 0, 0.1);
  1778. position: relative;
  1779. display: flex;
  1780. justify-content: center;
  1781. align-items: center;
  1782. backdrop-filter: blur(5px);
  1783. }
  1784. /* 【暂停】怀表中心圆点 */
  1785. .watch-center {
  1786. width: 10%;
  1787. height: 10%;
  1788. background-color: rgba(100, 50, 20, 0.8);
  1789. border-radius: 50%;
  1790. position: absolute;
  1791. z-index: 10;
  1792. }
  1793. /* 【暂停】表针容器 */
  1794. .watch-hands {
  1795. position: absolute;
  1796. width: 100%;
  1797. height: 100%;
  1798. display: flex;
  1799. justify-content: center;
  1800. align-items: center;
  1801. }
  1802. /* 【暂停】表针基础样式 */
  1803. .watch-hand {
  1804. position: absolute;
  1805. background-color: rgba(100, 50, 20, 0.8);
  1806. transform-origin: bottom center;
  1807. border-radius: 2px;
  1808. }
  1809. /* 【暂停】时针样式 */
  1810. .hour-hand {
  1811. width: 4%;
  1812. height: 30%;
  1813. top: 20%;
  1814. animation: rotateHourHand 12s linear infinite;
  1815. }
  1816. /* 【暂停】分针样式 */
  1817. .minute-hand {
  1818. width: 3%;
  1819. height: 40%;
  1820. top: 10%;
  1821. animation: rotateMinuteHand 1s linear infinite;
  1822. }
  1823. /* 【暂停】怀表中心倒计时数字 */
  1824. .watch-countdown-number {
  1825. font-size: calc(var(--tile-size, 143px) * 0.3);
  1826. font-weight: bold;
  1827. color: rgba(100, 50, 20, 0.9);
  1828. text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.8);
  1829. z-index: 5;
  1830. animation: pulseCountdown 1s infinite;
  1831. }
  1832. /* 【暂停】怀表淡入动画 */
  1833. @keyframes fadeInCountdown {
  1834. 0% {
  1835. opacity: 0;
  1836. transform: scale(0.8) rotate(-30deg);
  1837. }
  1838. 100% {
  1839. opacity: 1;
  1840. transform: scale(1) rotate(0deg);
  1841. }
  1842. }
  1843. /* 【暂停】倒计时数字脉冲动画 */
  1844. @keyframes pulseCountdown {
  1845. 0%, 100% {
  1846. opacity: 0.9;
  1847. transform: scale(1);
  1848. }
  1849. 50% {
  1850. opacity: 0.7;
  1851. transform: scale(1.05);
  1852. }
  1853. }
  1854. /* 【暂停】时针旋转动画 */
  1855. @keyframes rotateHourHand {
  1856. from { transform: rotate(0deg); }
  1857. to { transform: rotate(360deg); }
  1858. }
  1859. /* 【暂停】分针旋转动画 */
  1860. @keyframes rotateMinuteHand {
  1861. from { transform: rotate(0deg); }
  1862. to { transform: rotate(360deg); }
  1863. }
  1864. /* 弹入动画 */
  1865. @keyframes bounceIn {
  1866. 0% {
  1867. opacity: 0;
  1868. transform: scale(0.3) translateY(-20px);
  1869. }
  1870. 50% {
  1871. opacity: 0.7;
  1872. transform: scale(1.1) translateY(5px);
  1873. }
  1874. 80% {
  1875. opacity: 0.9;
  1876. transform: scale(0.95) translateY(-2px);
  1877. }
  1878. 100% {
  1879. opacity: 1;
  1880. transform: scale(1) translateY(0);
  1881. }
  1882. }
  1883. /* 成功到达终点动画 */
  1884. .player.success {
  1885. animation: success 1s ease-in-out;
  1886. }
  1887. @keyframes success {
  1888. 0% { transform: rotate(var(--player-rotation)) scale(1); }
  1889. 10% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  1890. 20% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  1891. 30% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(-5px) translateY(-5px); }
  1892. 40% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(5px) translateY(5px); }
  1893. 50% { transform: rotate(var(--player-rotation)) scale(1.4) translateX(0) translateY(0); }
  1894. 60% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  1895. 70% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  1896. 80% { transform: rotate(var(--player-rotation)) scale(1.3) translateX(-3px) translateY(-3px); }
  1897. 90% { transform: rotate(var(--player-rotation)) scale(1.2) translateX(3px) translateY(3px); }
  1898. 100% { transform: rotate(var(--player-rotation)) scale(1); }
  1899. }
  1900. /* 游戏消息样式 */
  1901. .game-message {
  1902. position: absolute;
  1903. top: 20px;
  1904. left: 50%;
  1905. transform: translateX(-50%);
  1906. padding: 10px 20px;
  1907. border-radius: 5px;
  1908. font-weight: bold;
  1909. z-index: 20;
  1910. min-width: 200px;
  1911. text-align: center;
  1912. }
  1913. .game-message.success {
  1914. background-color: #d4edda;
  1915. color: #155724;
  1916. border: 1px solid #c3e6cb;
  1917. }
  1918. .game-message.error {
  1919. background-color: #f8d7da;
  1920. color: #721c24;
  1921. border: 1px solid #f5c6cb;
  1922. }
  1923. .game-message.info {
  1924. background-color: #d1ecf1;
  1925. color: #0c5460;
  1926. border: 1px solid #bee5eb;
  1927. }
  1928. .game-message.warning {
  1929. background-color: #baeff8;
  1930. color: #035767;
  1931. border: 1px solid #9be9f6;
  1932. }
  1933. /* Blockly区域样式 */
  1934. .blockly-section {
  1935. flex: 1;
  1936. min-width: 600px;
  1937. display: flex;
  1938. flex-direction: column;
  1939. gap: 20px;
  1940. }
  1941. // 合并重复的区块样式
  1942. .map-section, .toolbox-section, .workspace-section {
  1943. background: rgba(248, 249, 250, 0.82);
  1944. padding: 15px;
  1945. border-radius: 15px;
  1946. height: 100%;
  1947. }
  1948. .map-section h2, .toolbox-section h2, .workspace-section h2 {
  1949. margin-bottom: 15px;
  1950. color: #2c3e50;
  1951. border-bottom: 2px solid #3498db;
  1952. padding-bottom: 8px;
  1953. }
  1954. // 合并重复的区块背景样式
  1955. .map-section,
  1956. .toolbox-section,
  1957. .workspace-section {
  1958. background: rgba(248, 249, 250, 0.82);
  1959. padding: 15px;
  1960. border-radius: 15px;
  1961. }
  1962. #blocklyDiv {
  1963. height: 87%;
  1964. min-height: rpx(250);
  1965. width: 100%;
  1966. background: #fff;
  1967. border: 1px solid #ddd;
  1968. border-radius: 8px;
  1969. }
  1970. /* 优化Blockly积木样式 */
  1971. /* 增加积木高度 */
  1972. .blocklyBlockCanvas .blocklyBlock {
  1973. height: 45px; /* 增加默认高度 */
  1974. min-height: 45px;
  1975. }
  1976. /* 增加积木内部元素的行高和间距 */
  1977. .blocklyText {
  1978. font-size: 16px;
  1979. line-height: 20px;
  1980. font-weight: 500;
  1981. }
  1982. /* 增加输入字段的高度 */
  1983. .blocklyHtmlInput {
  1984. height: 30px;
  1985. font-size: 14px;
  1986. padding: 5px;
  1987. }
  1988. /* 增加下拉菜单的高度 */
  1989. .blocklyDropdownMenu {
  1990. line-height: 28px;
  1991. font-size: 14px;
  1992. }
  1993. /* 优化积木圆角和阴影效果 */
  1994. .blocklyBlock {
  1995. border-radius: 8px;
  1996. filter: drop-shadow(0 2px 4px rgba(0, 0, 0, 0.1));
  1997. }
  1998. /* 增加积木之间的连接点间距 */
  1999. .blocklyConnection {
  2000. height: 20px;
  2001. width: 20px;
  2002. }
  2003. /* 增加工具箱中积木的高度 */
  2004. .blocklyTreeRow {
  2005. height: 40px;
  2006. line-height: 40px;
  2007. }
  2008. .controls {
  2009. display: flex;
  2010. gap: 10px;
  2011. margin: 15px 0px;
  2012. flex-wrap: wrap;
  2013. }
  2014. button {
  2015. padding: 10px 20px;
  2016. border: none;
  2017. border-radius: 5px;
  2018. background: #3498db;
  2019. color: #fff;
  2020. font-weight: 700;
  2021. cursor: pointer;
  2022. transition: all 0.3s ease;
  2023. }
  2024. button:hover {
  2025. background: #2980b9;
  2026. transform: translateY(-2px);
  2027. box-shadow: 0 5px 10px rgba(0, 0, 0, 0.1);
  2028. }
  2029. #runCode {
  2030. background: #e74c3c;
  2031. }
  2032. #runCode:hover {
  2033. background: #c0392b;
  2034. }
  2035. /* 响应式布局 */
  2036. @media (max-width: 1200px) {
  2037. .map-section,
  2038. .blockly-section {
  2039. flex: 1;
  2040. min-width: 45%;
  2041. }
  2042. .map-background {
  2043. width: 100%;
  2044. height: 400px;
  2045. }
  2046. }
  2047. </style>