var canvas, stage, exportRoot, anim_container, dom_overlay_container, fnStartAnimation; const obj = { lib: null, holes: [], // 洞洞的实例集合 radishes: [], // 萝卜的集合 rabbit: null, // 兔子对象 timeBg: null, // 倒计时背景对象 timeText: null, // 倒计时文本对象 totalTime: 60, // 总时长 s scoreText: null, // 得分文本对象 totalScore: 0, // 总分 满分100分 每拔一个萝卜+5分 pulledRadishNum: 0, // 已经拔了的萝卜的数量 timerId: null, // 倒计时计时器的id btnBegin: null, // 开始游戏的按钮 btnAgain: null, // 再玩一次的按钮 bgModalBegin: null, // 开始倒计时面板 countTimer: null, // 开始游戏的倒计时的 计时器id initCount: 5, // 默认倒计时时长 count: 5, // 开始游戏时的倒计时 music: { bgm: null, // 背景音乐 excitation: null, // 拔出一个萝卜的激励声音 amazing: null, unbelievable: null, // }, gameStart: false, // 游戏时候开始 lock: false, // 锁 拔的过程中不能出发下一次拔的动作 }; function init() { initMessage(); canvas = document.getElementById("canvas"); anim_container = document.getElementById("animation_container"); dom_overlay_container = document.getElementById("dom_overlay_container"); var comp = AdobeAn.getComposition("94CA090E719F4688AE0D01901C9EA0D7"); var lib = comp.getLibrary(); var loader = new createjs.LoadQueue(false); loader.addEventListener("fileload", function (evt) { handleFileLoad(evt, comp) }); loader.addEventListener("complete", function (evt) { handleComplete(evt, comp) }); var lib = comp.getLibrary(); loader.loadManifest(lib.properties.manifest); } function handleFileLoad(evt, comp) { var images = comp.getImages(); if (evt && (evt.item.type == "image")) { images[evt.item.id] = evt.result; } } function handleComplete(evt, comp) { //This function is always called, irrespective of the content. You can use the variable "stage" after it is created in token create_stage. var lib = comp.getLibrary(); var ss = comp.getSpriteSheet(); var queue = evt.target; var ssMetadata = lib.ssMetadata; for (i = 0; i < ssMetadata.length; i++) { ss[ssMetadata[i].name] = new createjs.SpriteSheet({ "images": [queue.getResult(ssMetadata[i].name)], "frames": ssMetadata[i].frames }) } exportRoot = new lib.pullRadishv16(); stage = new lib.Stage(canvas); //Registers the "tick" event listener. fnStartAnimation = function () { stage.addChild(exportRoot); obj.lib = lib; initStage(lib); createjs.Ticker.framerate = lib.properties.fps; createjs.Ticker.addEventListener("tick", stage); } //Code to support hidpi screens and responsive scaling. AdobeAn.makeResponsive(true, 'both', true, 1, [canvas, anim_container, dom_overlay_container]); AdobeAn.compositionLoaded(lib.properties.id); fnStartAnimation(); } // 初始绘制舞台相关元素 function initStage(lib) { initSound(); initRadishes(lib); initRabbit(lib); initHoles(lib); initTime(lib); initScore(lib); initBeginBtn(); initBackBtn(); // test(); } // 初始化音频资源 function initSound() { createjs.Sound.alternateExtensions = ["mp3"]; const sounds = [ { src: './sounds/bgmMusic.mp3', id: 'bgm'}, { src: './sounds/excitationMusic.mp3', id: 'excitation'}, { src: './sounds/amazing.mp3', id: 'amazing'}, { src: './sounds/unbelievable.mp3', id: 'unbelievable'}, ]; createjs.Sound.addEventListener('fileload', function (event) { obj.music[event.id] = createjs.Sound.createInstance(event.id); }); createjs.Sound.registerSounds(sounds, './'); } // 初始化开始按钮 function initBeginBtn() { obj.btnBegin = new obj.lib.btnBegin(); obj.btnBegin.x = obj.lib.properties.width / 2; obj.btnBegin.y = obj.lib.properties.height / 2; // 点了以后开始游戏 obj.btnBegin.addEventListener('click', function() { send() }, false); stage.addChild(obj.btnBegin); } // 初始 开始倒计时面板 function initBeginCount() { obj.music.bgm && obj.music.bgm.play({ loop: -1, volume: 0.3 }); // 播放背景音乐 obj.bgModalBegin = new obj.lib.bgModalBegin(); obj.bgModalBegin.x = obj.lib.properties.width / 2; obj.bgModalBegin.y = obj.lib.properties.height / 2; stage.addChild(obj.bgModalBegin); // 显示开始游戏的倒计时面板 stage.removeChild(obj.btnBegin); // 移除开始游戏的按钮 const startTime = +gameInfo.startTime; const endCountTime = startTime + obj.initCount * 1000; obj.count = Math.floor((endCountTime - Date.now()) / 1000); changeBeginTime(obj.count); // 开始开始游戏的 倒计时 obj.countTimer = setInterval(function() { obj.count = Math.floor((endCountTime - Date.now()) / 1000) stage.removeChild(obj.beginTimeText); changeBeginTime(obj.count); }, 1000); } // 修改开始倒计时 function changeBeginTime(time) { if (time === 0) { console.log(time); // 发送倒计时结束的消息 clearInterval(obj.countTimer); stage.removeChild(obj.beginTimeText); stage.removeChild(obj.bgModalBegin); sendEndCountRequest(); return; } const text = new createjs.Text(time, "bold 100px Arial", "#87431c"); text.x = obj.lib.properties.width / 2; text.y = obj.lib.properties.height / 2 + 20; text.textAlign = 'center'; text.textBaseline = "alphabetic"; obj.beginTimeText = text; stage.addChild(text); } // 收到倒计时结束的消息 function onCountdownMessage() { obj.gameStart = true; interval(); } /** * 初始绘制holes 洞洞 * @param {object} lib */ function initHoles(lib) { const deltaX = 185; // 列偏移 const deltaY = 132; // 行偏移 const initX = 108; // 第一个坑X const initY = 290; // 第一个坑Y for (let j = 0; j < 4; j++) { for (let i = 0; i < 5; i++) { const holeInstance = new lib.hole(); holeInstance.x = initX + deltaX * i; holeInstance.y = initY + deltaY * j; obj.holes.push(holeInstance); stage.addChild(holeInstance); } } } /** * 初始绘制radishes 萝卜 * @param {object} lib */ function initRadishes(lib) { const deltaX = 185; // 列偏移 const deltaY = 132; // 行偏移 const initX = 150; // 第一个坑X const initY = 260; // 第一个坑Y for (let j = 0; j < 4; j++) { for (let i = 0; i < 5; i++) { const radishInstance = new lib.radish_1(); radishInstance.x = initX + deltaX * i; radishInstance.y = initY + deltaY * j; obj.radishes.push(radishInstance); stage.addChild(radishInstance); } } } /** * 初始绘制兔子 * @param {object} lib */ function initRabbit(lib) { const initX = 100; const initY = 250; const deltaX = 185; const deltaY = 132; const rabbitInstance = new lib.rabbitCell(); rabbitInstance.x = initX + deltaX * (obj.pulledRadishNum % 5); rabbitInstance.y = initY + deltaY * Math.floor(obj.pulledRadishNum / 5); obj.rabbit = rabbitInstance; stage.addChild(rabbitInstance); } /** * 初始绘制倒计时 * @param {object} lib */ function initTime(lib) { const initX = 920; const initY = 80; const instance = new lib.timeBg(); instance.x = initX; instance.y = initY; obj.timeBg = instance; stage.addChild(instance); changeTime(obj.totalTime); } /** * 修改倒计时 * @param {number} totalTime 游戏剩余秒数 */ function changeTime(totalTime) { const text = new createjs.Text(totalTime, "bold 40px Arial", "#823d16"); text.x = 922; text.y = 100; text.textAlign = 'center'; text.textBaseline = "alphabetic"; obj.timeText = text; stage.addChild(text); } /** * 修改得分 * @param {number} score 得分 */ function changeScore(score) { const text = new createjs.Text(score, "bold 32px Arial", "#FFF"); text.x = obj.lib.properties.width / 2 + 50; text.y = 97; text.textAlign = 'center'; text.textBaseline = "alphabetic"; obj.scoreText = text; stage.addChild(text); } /** * 初始绘制得分 * @param {object} lib */ function initScore(lib) { const initX = obj.lib.properties.width / 2; const initY = 80; const instance = new lib.scoreBg(); instance.x = initX; instance.y = initY; instance.scaleX = 1.5; instance.scaleY = 1.5; obj.timeBg = instance; stage.addChild(instance); changeScore(obj.totalScore); } // 测试 function test() { document.addEventListener('click', handlePull, false); } // 一次拔萝卜的动作 // 测试函数 // 1. 萝卜动画 // 2. 兔子动画 // 3. 动画结束后 洞洞变状态 // 4. 分数+5 // 5. 兔子跑到下一个洞洞附近 // 时间到游戏结束 // 拔完了20个萝卜游戏结束 function handlePull() { if (obj.lock || !obj.gameStart) return; obj.lock = true; if (obj.totalTime <= 0 || obj.pulledRadishNum >= 20) return; // 1. 设置萝卜的动画及状态 obj.radishes[obj.pulledRadishNum].gotoAndPlay('radish_start'); // 2. 兔子的动画 obj.rabbit.gotoAndPlay('rabbit_start'); // 3. 延时修改洞洞的状态 // 没找到动画的回调 目前只能用延时来处理 setTimeout(function () { // obj.holes[obj.pulledRadishNum].gotoAndPlay('hole_active'); if (obj.pulledRadishNum >= 20) { // 游戏结束 gameOver(); return } obj.rabbit && stage.removeChild(obj.rabbit); initRabbit(obj.lib); for (let i = 0; i < obj.pulledRadishNum; i++) { obj.holes[i].gotoAndStop('hole_active'); obj.radishes[i].gotoAndStop('radish_bomb_end'); } obj.lock = false; }, 1250); } // 收到了计分的消息 function onScoreMessage(score, times) { console.log('score, times',score, times) obj.totalScore = score; obj.pulledRadishNum = times; playExcitationMusic(); // 播放激励音乐 obj.scoreText && stage.removeChild(obj.scoreText); // 清除原有的分数 changeScore(obj.totalScore); // 显示新的分数 } // 播放激励音乐 function playExcitationMusic() { switch (obj.pulledRadishNum % 5) { case 0: obj.music.unbelievable.play(); break; case 3: case 4: obj.music.amazing.play(); break; default: obj.music.excitation.play(); break; } } // 游戏结束 function gameOver() { console.log('game over', obj); obj.rabbit && stage.removeChild(obj.rabbit); obj.timerId && clearInterval(obj.timerId); obj.timerId = null; sendEndRequest(); // 发送结束http请求 showEndModal(); } // 发送倒计时结束http请求 function sendEndCountRequest() { const data = { "param": { "id": gameInfo.patientId, "recordId": gameInfo.recordId } } fetch('//www.tall.wiki/gateway/recovery/patient/countdown', { method: 'POST', mode: 'cors', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => { if (response && response.code === 200) { // 结束成功 } else { alert('网络异常, 请检查网络刷新重试'); console.error(response.msg); } }) .catch(error => console.error('Error:', error)); } // 发送结束http请求 function sendEndRequest() { /** gameId: "1" patientId: "1" recordId: "1400659869853421568" */ const data = { "param": { "id": gameInfo.recordId, "patientId": gameInfo.patientId, "score": obj.totalScore } }; fetch('//www.tall.wiki/gateway/recovery/patient/end', { method: 'POST', mode: 'cors', body: JSON.stringify(data), headers: { 'Content-Type': 'application/json' } }) .then(res => res.json()) .then(response => { if (response && response.code === 200) { // 结束成功 } else { console.error(response.msg); } }) .catch(error => console.error('Error:', error)); } // 处理倒计时 function interval() { if (obj.timerId) return; const endTime = +gameInfo.startTime + obj.initCount * 1000 + +gameInfo.duration; obj.timerId = setInterval(function () { if (obj.totalTime === 0) { gameOver(); return; } obj.totalTime = Math.floor((endTime - Date.now()) / 1000); obj.timeText && stage.removeChild(obj.timeText); changeTime(obj.totalTime); }, 1000); } // 显示结束游戏面板 及得分 function showEndModal() { obj.endModal = new obj.lib.bgModalEnd(); obj.endModal.x = obj.lib.properties.width / 2; obj.endModal.y = obj.lib.properties.height / 2 stage.addChild(obj.endModal); const text = new createjs.Text(obj.totalScore, "bold 100px Arial", "#793b18"); text.x = obj.lib.properties.width / 2; text.y = obj.lib.properties.height / 2 + 70; text.textAlign = 'center'; text.textBaseline = "alphabetic"; obj.endText = text; stage.addChild(text); showAgainBtn(); } // 显示再玩一次的按钮 function showAgainBtn() { const btnAgain = new obj.lib.btnAgain(); btnAgain.x = obj.lib.properties.width / 2; btnAgain.y = obj.lib.properties.height / 2 + 150; obj.btnAgain = btnAgain; obj.btnAgain.addEventListener('click', function() { location.reload(); }, false); stage.addChild(btnAgain); } // 初始化返回按钮/退出游戏按钮 function initBackBtn() { obj.btnBack = new obj.lib.btnBack(); obj.btnBack.x = 40; obj.btnBack.y = 80; obj.btnBack.scaleX = 1.3; obj.btnBack.scaleY = 1.3; stage.addChild(obj.btnBack); }