Commit 977794bd authored by rockyl's avatar rockyl

init

parents
# Created by .ignore support plugin (hsz.mobi)
design/origin/
node_modules
libs/
bin-debug/
bin-release/
design/sheetModifyTime.json
.wing/
!/design/images/fonts/
!/src/game/
{
"engineVersion": "5.2.9",
"compilerVersion": "5.2.9",
"template": {},
"target": {
"current": "web"
},
"eui": {
"exmlRoot": "resource/skins",
"themes": [
"resource/default.thm.json"
],
"exmlPublishPolicy": "commonjs"
},
"modules": [
{
"name": "egret"
},
{
"name": "eui"
},
{
"name": "assetsmanager"
},
{
"name": "tween"
},
{
"name": "game"
},
{
"name": "promise"
},
{
"name": "md5",
"path": "/Users/rockyl/WorkSpaces/egret_third_part/md5"
},
{
"name": "physics",
"path": "/Users/rockyl/WorkSpaces/egret-game-library/physics/libsrc"
}
],
"version": {
"main": "1.0.0",
"build": 588
}
}
\ No newline at end of file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Egret</title>
<meta name="viewport"
content="width=device-width,initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"/>
<meta name="apple-mobile-web-app-capable" content="yes"/>
<meta name="full-screen" content="true"/>
<meta name="screen-orientation" content="portrait"/>
<meta name="x5-fullscreen" content="true"/>
<meta name="360-fullscreen" content="true"/>
<style>
html, body {
-ms-touch-action: none;
background: #0a0047;
padding: 0;
border: 0;
margin: 0;
height: 100%;
}
</style>
</head>
<body>
<div style="margin: auto;width: 100%;height: 100%;" class="egret-player"
data-entry-class="Main"
data-orientation="auto"
data-scale-mode="fixedWidth"
data-frame-rate="60"
data-content-width="750"
data-content-height="1206"
data-multi-fingered="2"
data-show-fps="false" data-show-log="false"
data-show-fps-style="x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9">
</div>
<script>
var loadScript = function (list, callback) {
var loaded = 0;
var loadNext = function () {
loadSingleScript(list[loaded], function () {
loaded++;
if (loaded >= list.length) {
callback();
}
else {
loadNext();
}
})
};
loadNext();
};
var loadSingleScript = function (src, callback) {
var s = document.createElement('script');
s.async = false;
s.src = src;
s.addEventListener('load', function () {
s.parentNode.removeChild(s);
s.removeEventListener('load', arguments.callee, false);
callback();
}, false);
document.body.appendChild(s);
};
var xhr = new XMLHttpRequest();
xhr.open('GET', './manifest.json?v=' + Math.random(), true);
xhr.addEventListener("load", function () {
var manifest = JSON.parse(xhr.response);
var list = manifest.initial.concat(manifest.game);
loadScript(list, function () {
/**
* {
* "renderMode":, //Engine rendering mode, "canvas" or "webgl"
* "audioType": 0 //Use the audio type, 0: default, 2: web audio, 3: audio
* "antialias": //Whether the anti-aliasing is enabled in WebGL mode, true: on, false: off, defaults to false
* "calculateCanvasScaleFactor": //a function return canvas scale factor
* }
**/
egret.runEgret({
renderMode: "webgl", audioType: 0, calculateCanvasScaleFactor: function (context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
}
});
});
});
xhr.send(null);
var gameId = 1;
var revivePluginId = 1;
var CFG = {
appInfo: {
"appId": 1,
"earnCreditsUrl": "https://www.baidu.com/",
"loginProgram": "",
"open": false,
"openLogin": false
},
gameInfo: {
"id": 1317,
"oaId": 19951,
"offDate": "2018-04-17 11:00",
"openTotalScoreSwitch": false,
"rankPrize": true,
"skincontent": ""
},
extra: {
"embedDomain": "//embedlog.duibatest.com.cn"
},
defenseStrategy: {
"scoreUnit": 500
}
}
var recordUrl = 'record/';
function devil(a) {
return eval(a);
}
</script>
</body>
</html>
\ No newline at end of file
{
"initial": [
"libs/modules/egret/egret.js",
"libs/modules/egret/egret.web.js",
"libs/modules/eui/eui.js",
"libs/modules/assetsmanager/assetsmanager.js",
"libs/modules/tween/tween.js",
"libs/modules/game/game.js",
"libs/modules/promise/promise.js",
"libs/modules/md5/md5.js",
"libs/modules/physics/physics.js"
],
"game": [
"bin-debug/bundle.js"
]
}
\ No newline at end of file
{
"file": "font_yellow.png",
"frames": {
"0": {
"x": 91,
"y": 127,
"w": 42,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 42,
"sourceH": 61
},
"1": {
"x": 1,
"y": 190,
"w": 40,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 40,
"sourceH": 61
},
"2": {
"x": 93,
"y": 64,
"w": 43,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 43,
"sourceH": 61
},
"3": {
"x": 95,
"y": 1,
"w": 44,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 44,
"sourceH": 61
},
"4": {
"x": 1,
"y": 1,
"w": 46,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 46,
"sourceH": 61
},
"5": {
"x": 49,
"y": 1,
"w": 44,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 44,
"sourceH": 61
},
"6": {
"x": 47,
"y": 64,
"w": 44,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 44,
"sourceH": 61
},
"7": {
"x": 1,
"y": 127,
"w": 43,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 43,
"sourceH": 61
},
"8": {
"x": 46,
"y": 127,
"w": 43,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 43,
"sourceH": 61
},
"9": {
"x": 1,
"y": 64,
"w": 44,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 44,
"sourceH": 61
},
"+": {
"x": 43,
"y": 190,
"w": 39,
"h": 61,
"offX": 0,
"offY": 0,
"sourceW": 39,
"sourceH": 61
}
}
}
\ No newline at end of file
{
"file": "sheet_body.png",
"frames": {
"body_head": {
"x": 1,
"y": 1,
"w": 126,
"h": 126,
"offX": 0,
"offY": 0,
"sourceW": 126,
"sourceH": 126
},
"body_leg": {
"x": 129,
"y": 1,
"w": 35,
"h": 43,
"offX": 0,
"offY": 0,
"sourceW": 35,
"sourceH": 43
},
"body_hand": {
"x": 129,
"y": 46,
"w": 26,
"h": 44,
"offX": 0,
"offY": 0,
"sourceW": 26,
"sourceH": 44
},
"body_body": {
"x": 1,
"y": 129,
"w": 81,
"h": 65,
"offX": 0,
"offY": 0,
"sourceW": 81,
"sourceH": 65
},
"body_ear": {
"x": 84,
"y": 129,
"w": 70,
"h": 65,
"offX": 0,
"offY": 0,
"sourceW": 70,
"sourceH": 65
}
}
}
\ No newline at end of file
{
"file": "sheet_common.png",
"frames": {
"common_high_light": {
"x": 1,
"y": 1,
"w": 656,
"h": 656,
"offX": 0,
"offY": 0,
"sourceW": 656,
"sourceH": 656
},
"common_btn_close": {
"x": 659,
"y": 1,
"w": 50,
"h": 50,
"offX": 0,
"offY": 0,
"sourceW": 50,
"sourceH": 50
},
"common_btn_confirm": {
"x": 1,
"y": 659,
"w": 391,
"h": 106,
"offX": 0,
"offY": 0,
"sourceW": 391,
"sourceH": 106
},
"common_panel_bg": {
"x": 394,
"y": 659,
"w": 174,
"h": 224,
"offX": 0,
"offY": 0,
"sourceW": 174,
"sourceH": 224
}
}
}
\ No newline at end of file
{
"file": "sheet_loading.png",
"frames": {
"loading_logo": {
"x": 1,
"y": 1,
"w": 589,
"h": 228,
"offX": 0,
"offY": 0,
"sourceW": 589,
"sourceH": 228
}
}
}
\ No newline at end of file
{
"file": "sheet_menu.png",
"frames": {
"menu_bg_part_top": {
"x": 1,
"y": 1,
"w": 750,
"h": 192,
"offX": 0,
"offY": 0,
"sourceW": 750,
"sourceH": 192
},
"menu_bg_part_logo": {
"x": 753,
"y": 1,
"w": 554,
"h": 232,
"offX": 0,
"offY": 0,
"sourceW": 554,
"sourceH": 232
},
"menu_bg": {
"x": 1,
"y": 195,
"w": 728,
"h": 897,
"offX": 0,
"offY": 0,
"sourceW": 728,
"sourceH": 897
},
"menu_bg_part_right": {
"x": 1,
"y": 1094,
"w": 171,
"h": 843,
"offX": 0,
"offY": 0,
"sourceW": 171,
"sourceH": 843
},
"menu_btn_rank": {
"x": 1,
"y": 1939,
"w": 100,
"h": 99,
"offX": 0,
"offY": 0,
"sourceW": 100,
"sourceH": 99
},
"menu_btn_rule": {
"x": 103,
"y": 1939,
"w": 91,
"h": 92,
"offX": 0,
"offY": 0,
"sourceW": 91,
"sourceH": 92
},
"menu_bg_part_left": {
"x": 174,
"y": 1094,
"w": 188,
"h": 841,
"offX": 0,
"offY": 0,
"sourceW": 188,
"sourceH": 841
},
"menu_moon": {
"x": 364,
"y": 1094,
"w": 657,
"h": 657,
"offX": 0,
"offY": 0,
"sourceW": 657,
"sourceH": 657
},
"menu_btn_start": {
"x": 731,
"y": 1753,
"w": 277,
"h": 280,
"offX": 0,
"offY": 0,
"sourceW": 277,
"sourceH": 280
},
"menu_sprite": {
"x": 1023,
"y": 235,
"w": 154,
"h": 130,
"offX": 0,
"offY": 0,
"sourceW": 154,
"sourceH": 130
}
}
}
\ No newline at end of file
{
"file": "sheet_play.png",
"frames": {
"play_bg_ground": {
"x": 1,
"y": 1,
"w": 750,
"h": 954,
"offX": 0,
"offY": 0,
"sourceW": 750,
"sourceH": 954
},
"play_go": {
"x": 753,
"y": 1,
"w": 211,
"h": 116,
"offX": 0,
"offY": 0,
"sourceW": 211,
"sourceH": 116
},
"play_block_0": {
"x": 753,
"y": 119,
"w": 208,
"h": 134,
"offX": 0,
"offY": 0,
"sourceW": 208,
"sourceH": 134
},
"play_block_2": {
"x": 753,
"y": 255,
"w": 208,
"h": 134,
"offX": 0,
"offY": 0,
"sourceW": 208,
"sourceH": 134
},
"play_block_3": {
"x": 753,
"y": 391,
"w": 208,
"h": 134,
"offX": 0,
"offY": 0,
"sourceW": 208,
"sourceH": 134
},
"play_block_4": {
"x": 753,
"y": 527,
"w": 208,
"h": 134,
"offX": 0,
"offY": 0,
"sourceW": 208,
"sourceH": 134
},
"play_block_1": {
"x": 753,
"y": 663,
"w": 208,
"h": 134,
"offX": 0,
"offY": 0,
"sourceW": 208,
"sourceH": 134
},
"play_ready": {
"x": 1,
"y": 957,
"w": 333,
"h": 92,
"offX": 0,
"offY": 0,
"sourceW": 333,
"sourceH": 92
},
"play_block_5": {
"x": 336,
"y": 957,
"w": 218,
"h": 144,
"offX": 0,
"offY": 0,
"sourceW": 218,
"sourceH": 144
}
}
}
\ No newline at end of file
{
"file": "sheet_rank.png",
"frames": {
"rank_bg": {
"x": 1,
"y": 1,
"w": 453,
"h": 138,
"offX": 0,
"offY": 0,
"sourceW": 453,
"sourceH": 138
},
"rank_title": {
"x": 1,
"y": 141,
"w": 382,
"h": 105,
"offX": 0,
"offY": 0,
"sourceW": 382,
"sourceH": 105
}
}
}
\ No newline at end of file
{
"file": "sheet_result.png",
"frames": {
"result_btn_revive": {
"x": 1,
"y": 1,
"w": 391,
"h": 106,
"offX": 0,
"offY": 0,
"sourceW": 391,
"sourceH": 106
},
"result_title": {
"x": 1,
"y": 109,
"w": 382,
"h": 105,
"offX": 0,
"offY": 0,
"sourceW": 382,
"sourceH": 105
},
"result_btn_get_reward": {
"x": 1,
"y": 216,
"w": 257,
"h": 91,
"offX": 0,
"offY": 0,
"sourceW": 257,
"sourceH": 91
},
"result_btn_retry": {
"x": 1,
"y": 309,
"w": 257,
"h": 91,
"offX": 0,
"offY": 0,
"sourceW": 257,
"sourceH": 91
}
}
}
\ No newline at end of file
{
"need_login": "请先登录!",
"net_error": "网络开了个小差",
"current_score": "本局分数\n{0}分",
"max_score": "历史最佳\n{0}分",
"score_unit": "分",
"free": "免费",
"my_credit": "我的",
"no_more_credits": "不足",
"revive_cost": "是否愿意花费{0}{1}在当前游戏复活一次?",
"revive_failed": "复活失败",
"rank_first": "冠军",
"rank_second": "亚军",
"rank_third": "季军",
"rank_num": "第{0}名",
"rank_out": "未上榜",
"me": "我",
"rank_max_score": "我的历史最高分: {0}分",
"rank_reward_content": "您的排名: {0}\n您的奖品: {1}\n您的ID: {2}"
}
{
"groups": [
{
"keys": "lang,sheet_loading",
"name": "loading"
},
{
"keys": "sheet_menu,bg",
"name": "menu"
},
{
"keys": "sheet_rank",
"name": "panel_rank"
},
{
"keys": "sheet_result",
"name": "panel_result"
},
{
"keys": "sheet_common",
"name": "common"
},
{
"keys": "bg_ground,bg_loop",
"name": "play"
},
{
"keys": "bg",
"name": "preload"
}
],
"resources": [
{
"url": "configs/lang.json",
"type": "json",
"name": "lang"
},
{
"url": "assets/fonts/font_yellow.fnt",
"type": "font",
"name": "font_yellow"
},
{
"url": "assets/sheets/sheet_body.json",
"type": "sheet",
"name": "sheet_body",
"subkeys": "body_body,body_ear,body_hand,body_head,body_leg"
},
{
"url": "assets/sheets/sheet_common.json",
"type": "sheet",
"name": "sheet_common",
"subkeys": "common_btn_close,common_btn_confirm,common_high_light,common_panel_bg"
},
{
"url": "assets/sheets/sheet_loading.json",
"type": "sheet",
"name": "sheet_loading",
"subkeys": "loading_logo"
},
{
"url": "assets/sheets/sheet_menu.json",
"type": "sheet",
"name": "sheet_menu",
"subkeys": "menu_bg,menu_bg_part_left,menu_bg_part_logo,menu_bg_part_right,menu_bg_part_top,menu_btn_rank,menu_btn_rule,menu_btn_start,menu_moon,menu_sprite"
},
{
"url": "assets/sheets/sheet_play.json",
"type": "sheet",
"name": "sheet_play",
"subkeys": "play_bg_ground,play_block_0,play_block_1,play_block_2,play_block_3,play_block_4,play_block_5,play_go,play_ready"
},
{
"url": "assets/sheets/sheet_rank.json",
"type": "sheet",
"name": "sheet_rank",
"subkeys": "rank_bg,rank_title"
},
{
"url": "assets/sheets/sheet_result.json",
"type": "sheet",
"name": "sheet_result",
"subkeys": "result_btn_get_reward,result_btn_retry,result_btn_revive,result_title"
},
{
"url": "assets/singles/bg_loop.png",
"type": "image",
"name": "bg_loop"
},
{
"url": "assets/singles/bg_ground.png",
"type": "image",
"name": "bg_ground"
},
{
"url": "assets/singles/bg.png",
"type": "image",
"name": "bg"
}
]
}
\ No newline at end of file
{
"skins": {},
"autoGenerateExmlsList": true,
"exmls": [
"resource/skins/components/PlayerSkin.exml",
"resource/skins/components/RankItemSkin.exml",
"resource/skins/components/ReadyGoSkin.exml",
"resource/skins/components/ScoreEffectSkin.exml",
"resource/skins/components/ToastSkin.exml",
"resource/skins/LoadingViewSkin.exml",
"resource/skins/MainStageSkin.exml",
"resource/skins/ui/IconButtonSkin.exml",
"resource/skins/panels/PanelAlertSkin.exml",
"resource/skins/panels/PanelRankRewardSkin.exml",
"resource/skins/panels/PanelRankSkin.exml",
"resource/skins/panels/PanelResultSkin.exml",
"resource/skins/panels/PanelReviveSkin.exml",
"resource/skins/panels/PanelRuleSkin.exml",
"resource/skins/scenes/SceneFinalRewardSkin.exml",
"resource/skins/scenes/SceneMenuSkin.exml",
"resource/skins/scenes/ScenePlaySkin.exml"
],
"path": "resource/default.thm.json"
}
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="LoadingViewSkin" width="750" height="1206" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" states="loading,blank" >
<e:Rect width="100%" height="100%" fillColor="0x0a0047"/>
<e:Group verticalCenter="0" includeIn="loading" horizontalCenter="0">
<e:Image id="sp" source="loading_logo"/>
</e:Group>
</e:Skin>
\ No newline at end of file
<?xml version='1.0' encoding='utf-8'?>
<e:Skin class="MainStageSkin" width="750" height="1334" xmlns:e="http://ns.egret.com/eui" xmlns:ns1="*" xmlns:w="http://ns.egret.com/wing">
<e:Group id="sceneContainer" width="100%" height="100%"/>
<e:Group id="popLayer" width="100%" height="100%" touchEnabled="false"/>
<ns1:Toast id="toast" skinName="component.ToastSkin" width="100%" height="100%" touchEnabled="false" touchChildren="false"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="component.RankItemSkin" width="415" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" states="other,me" >
<e:Label id="labNum" text="0" horizontalCenter="-140" verticalCenter="0" textColor="0xa9572c"/>
<e:Label id="labName" text="用户" textColor="0xa9572c" x="136" verticalCenter="0" />
<e:Label id="labScore" text="得分" textColor="0xa9572c" horizontalCenter="142.5"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="component.ReadyGoSkin" width="750" height="109" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" xmlns:tween="egret.tween.*">
<w:Declarations>
<tween:TweenGroup id="ready">
<tween:TweenItem target="{imgReady}">
<tween:To duration="350" ease="cubicOut">
<tween:props>
<e:Object horizontalCenter="{0}"/>
</tween:props>
</tween:To>
<tween:Wait duration="150"/>
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object horizontalCenter="{542}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
<tween:TweenGroup id="go">
<tween:TweenItem target="{imgGo}">
<tween:To duration="500" ease="cubicOut">
<tween:props>
<e:Object horizontalCenter="{0}"/>
</tween:props>
</tween:To>
<tween:Wait duration="250"/>
<tween:To duration="400" ease="cubicIn">
<tween:props>
<e:Object horizontalCenter="{542}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
</w:Declarations>
<e:Image id="imgReady" horizontalCenter="-542" y="9" source="play_ready"/>
<e:Image id="imgGo" horizontalCenter="-541" y="-3" source="play_go"/>
</e:Skin>
\ No newline at end of file
<?xml version='1.0' encoding='utf-8'?>
<e:Skin class="component.ToastSkin" width="750" height="400" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Group id="grp" horizontalCenter="0.5" verticalCenter="-100">
<e:Rect ellipseWidth="20" ellipseHeight="20" fillAlpha="0.7" left="-20" right="-20" top="-20" bottom="-20"/>
<e:Label id="labContent" text="标签" strokeColor="0xc96914" horizontalCenter="0" verticalCenter="0" size="28" textColor="0xffffff"/>
</e:Group>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelAlertSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" width="585">
<e:Image source="common_panel_bg" scale9Grid="89,111,3,14" width="100%" height="100%" locked="true"/>
<e:Label id="labContent" text="Label" textAlign="center" lineSpacing="10" size="45" multiline="true" stroke="3" strokeColor="0x000000" textColor="0xffffff" top="150" bottom="270" width="485" x="50"/>
<e:Button id="btnOk" skinName="ui.IconButtonSkin" icon="common_btn_confirm" bottom="39" width="391" height="106" x="97"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelRankRewardSkin" width="500" height="350" xmlns:e="http://ns.egret.com/eui">
<e:Label id="labContent" text="Label" textColor="0x8e481a" lineSpacing="20" size="45" multiline="true" stroke="2"
strokeColor="0xffffff" x="46" y="20" />
<e:Button id="btnShowRank" skinName="ui.IconButtonSkin" icon="result_btn_show_rank" width="401" height="122" horizontalCenter="0.5" bottom="0"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelRankSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" xmlns:ns1="*" width="545" height="655">
<e:Image source="common_panel_bg" scale9Grid="89,111,3,14" width="100%" height="100%"/>
<e:Image y="-51" source="rank_title" x="82"/>
<e:Button id="btnClose" skinName="ui.IconButtonSkin" icon="common_btn_close" y="-10" width="50" height="50" x="505"/>
<e:Image y="65" source="rank_bg" x="46" anchorOffsetY="0" height="545" scale9Grid="73,66,324,3"/>
<e:Label text="排名" textColor="0xA9572C" x="103" y="86"/>
<e:Label text="用户名" textColor="0xA9572C" x="200" y="86"/>
<e:Label text="分数" textColor="0xA9572C" x="384" y="86"/>
<e:Scroller width="415" height="385" y="145" anchorOffsetY="0" anchorOffsetX="0" x="65">
<e:List id="list" x="-3" y="-13" locked="true">
<e:itemRendererSkinName>
<e:Skin states="up,down,disabled" xmlns:w="http://ns.egret.com/wing">
<ns1:RankItem id="rankItem" skinName="component.RankItemSkin"/>
</e:Skin>
</e:itemRendererSkinName>
<e:ArrayCollection>
<e:Array>
<e:Object a="null"/>
<e:Object a="null"/>
<e:Object a="null"/>
<e:Object a="null"/>
</e:Array>
</e:ArrayCollection>
<e:layout>
<e:VerticalLayout gap="10"/>
</e:layout>
</e:List>
</e:Scroller>
<ns1:RankItem id="rankSelf" skinName="component.RankItemSkin" x="65" y="560.33"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelResultSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing"
states="normal,reward" width="600">
<e:Image source="common_panel_bg" scale9Grid="89,111,3,14" width="100%" height="100%" locked="true"/>
<e:Button id="btnClose" skinName="ui.IconButtonSkin" icon="common_btn_close" width="50" height="50" y="-10" x="560"/>
<e:Group top="78" bottom="50" horizontalCenter="0">
<e:Group x="126" y="20">
<e:Label id="labScore" text="本局分数\n0分" y="0" size="50" textAlign="center" lineSpacing="10" textColor="0xFEF191" x="0"/>
<e:Label id="labMaxScore" text="历史最佳\n0分" y="61" size="50" textAlign="center" lineSpacing="10" x="0" textColor="0xfcce3a"/>
<e:layout>
<e:HorizontalLayout gap="67"/>
</e:layout>
</e:Group>
<e:Group y="430" includeIn="reward" horizontalCenter="0">
<e:Rect fillColor="0xffffff" left="-4" right="-4" top="-4" bottom="-4" ellipseWidth="10" ellipseHeight="10" />
<e:Image id="imgReward" scaleX="0.6" scaleY="0.6" width="640" height="300"/>
</e:Group>
<e:Label id="labRewardIntro" includeIn="reward" text="..." y="675" size="30" textAlign="center" horizontalCenter="0.5" />
<e:Group id="grpButtons" x="35" bottom="60">
<e:Button id="btnRetry" x.reward="264" icon="result_btn_retry" skinName="ui.IconButtonSkin" width="275" height="103" name="retry" x.normal="0"/>
<e:Button x="0" icon="result_btn_get_reward" skinName="ui.IconButtonSkin" width="275" height="103"
name="get_reward" includeIn="reward"/>
<e:Label id="labCost" text="1/1" y="108" size="30" textAlign="center" lineSpacing="20" horizontalCenter="150.5" horizontalCenter.normal="0" horizontalCenter.reward="135.5"/>
</e:Group>
<e:layout>
<e:VerticalLayout gap="20" horizontalAlign="center" gap.normal="50"/>
</e:layout>
</e:Group>
<e:Image source="result_title" x="102" y="-45.45"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelReviveSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" width="585" height="388">
<e:Image source="common_panel_bg" scale9Grid="89,111,3,14" width="100%" height="100%"/>
<e:Button id="btnClose" skinName="ui.IconButtonSkin" icon="common_btn_close" width="50" height="50" y="-10" x="545"/>
<e:Button id="btnConfirm" y="220.5" icon="result_btn_revive" skinName="ui.IconButtonSkin" width="413" height="114" x="86"/>
<e:Label id="labContent" text="是否愿意花费20积分在当前游戏复活一次?" y="73" stroke="2" width="416" size="41" textAlign="center" lineSpacing="20" x="85"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelRuleSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" width="585" height="555">
<e:Image source="common_panel_bg" scale9Grid="89,111,3,14" width="100%" height="100%"/>
<e:Label text="游戏说明" x="212.5" y="51" size="40" textColor="0xfbe193"/>
<e:Scroller id="scroller" height="396" y="110" width="485" x="50">
<e:Group width="100%">
<e:Label id="labContent" width="100%" text="" lineSpacing="10" size="30" multiline="true" textColor="0xfbe193"/>
</e:Group>
</e:Scroller>
<e:Button id="btnClose" skinName="ui.IconButtonSkin" icon="common_btn_close"
width="50" height="50" y="-10" x="545"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="scene.SceneFinalRewardSkin" width="400" height="300" xmlns:e="http://ns.egret.com/eui">
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="scene.SceneMenuSkin" width="750" height="1206" xmlns:e="http://ns.egret.com/eui"
xmlns:w="http://ns.egret.com/wing" xmlns:tween="egret.tween.*">
<w:Declarations>
<tween:TweenGroup id="enter">
<tween:TweenItem target="{grpButtons}">
<tween:To duration="500" ease="cubicOut">
<tween:props>
<e:Object bottom="{300}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartLeft}">
<tween:To duration="300" ease="cubicOut">
<tween:props>
<e:Object x="{0}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartRight}">
<tween:To duration="300" ease="cubicOut">
<tween:props>
<e:Object right="{0}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartTop}">
<tween:Wait duration="100"/>
<tween:To duration="300" ease="cubicOut">
<tween:props>
<e:Object y="{0}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgLogo}">
<tween:Wait duration="200"/>
<tween:To duration="400" ease="backOut">
<tween:props>
<e:Object y="{-20}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
<tween:TweenGroup id="leave">
<tween:TweenItem target="{grpButtons}">
<tween:Wait duration="150"/>
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object bottom="{-438}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartLeft}">
<tween:Wait duration="100"/>
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object x="{-188}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartRight}">
<tween:Wait duration="100"/>
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object right="{-171}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgPartTop}">
<tween:Wait duration="200"/>
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object y="{-192}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{imgLogo}">
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object y="{-232}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
</w:Declarations>
<e:Group id="grpBg" width="100%">
<e:Image id="imgPartLeft" source="menu_bg_part_left" x="-188"/>
<e:Image id="imgPartRight" source="menu_bg_part_right" right="-171"/>
<e:Image id="imgPartTop" source="menu_bg_part_top" y="-192"/>
<e:Image id="imgLogo" source="menu_bg_part_logo" x="109" y="-232"/>
</e:Group>
<e:Group id="grpButtons" bottom="-438" x="180">
<e:Button id="btnStart" skinName="ui.IconButtonSkin" icon="menu_btn_start" width="277" height="280" y="59" x="57" name="start"/>
<e:Button id="btnRank" skinName="ui.IconButtonSkin" icon="menu_btn_rank" width="100" height="99" name="rank"/>
<e:Button id="btnRule" skinName="ui.IconButtonSkin" icon="menu_btn_rule" x="300" width="91" height="92" name="rule"/>
<e:Image x="237" y="205.96" source="menu_sprite" touchEnabled="false"/>
<e:Label id="labCost" text="Label" y="362" horizontalCenter="0" touchEnabled="false"/>
<e:Label id="labCredit" text="Label" y="407.45" horizontalCenter="0.5" touchEnabled="false"/>
</e:Group>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="scene.ScenePlaySkin" width="750" height="1206" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" xmlns:tween="egret.tween.*" xmlns:ns1="*">
<w:Declarations>
<tween:TweenGroup id="enter">
<tween:TweenItem target="{labScore}">
<tween:To duration="200" ease="cubicOut">
<tween:props>
<e:Object y="{20}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
<tween:TweenGroup id="leave">
<tween:TweenItem target="{labScore}">
<tween:To duration="200" ease="cubicIn">
<tween:props>
<e:Object y="{-61}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
</w:Declarations>
<e:Rect id="touchLayer" width="100%" height="100%" fillAlpha="0.01" fillColor="0xffffff"/>
<ns1:ScoreLabel id="labScore" text="0" font="font_yellow" touchEnabled="false" y="-61" horizontalCenter="0"/>
<e:BitmapLabel id="labScoreAdd" text="+0" font="font_yellow" touchEnabled="false" horizontalCenter="0" verticalCenter="-300" scaleX="2" scaleY="2"/>
<ns1:ReadyGo id="readyGo" skinName="component.ReadyGoSkin" verticalCenter="0"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="ui.IconButtonSkin" xmlns:e="http://ns.egret.com/eui" xmlns:ns1="*" states="up,down" >
<e:Image id="iconDisplay" source="" horizontalCenter="0" verticalCenter="0" scaleX.down="0.95" scaleY.down="0.95"/>
</e:Skin>
\ No newline at end of file
/**
* ResourceManager 配置文件
*/
type ResourceManagerConfig = {
/**
* 构建与发布配置
*/
buildConfig: (param: BuildConfigParam) => UserConfig,
/**
* 设置资源类型
*/
typeSelector: (path: string) => (string | null | undefined)
/**
* 设置资源的合并策略
*/
mergeSelector?: (path: string) => (string | null | undefined),
/**
* 设置资源的命名策略
* beta 功能,请勿随意使用
*/
nameSelector?: (path: string) => (string | null | undefined)
}
/**
* 构建配置
*/
type UserConfig = {
/**
* 输出路径
*/
outputDir: string,
/**
* 插件
*/
commands: (string | plugins.Command)[]
}
type BuildConfigParam = {
/**
* 当前命令,build 或者 command
*/
readonly command: string;
/**
* 发布平台
*/
readonly target: string;
/**
* 开发者指定的版本号
*/
readonly version: string;
/**
* 项目名称
*/
readonly projectName: string;
/**
* 项目路径
*/
readonly projectRoot: string;
/**
* 项目配置
*/
readonly projectConfig: ProjectConfig;
}
type ProjectConfig = {
entryClassName: string;
orientation: string;
frameRate: number;
scaleMode: string;
contentWidth: number;
contentHeight: number;
showFPS: boolean;
fpsStyles: string;
showLog: boolean;
maxTouches: number;
}
/**
* 匹配机制,将满足 from 的文件输出为 to 格式的文件
* from 采用 glob 表达式 , to 包含 [path][name][hash][ext]四个变量
* 示例:{ from:"resource/**.*" , to:"[path][name]_[hash].[ext]" }
*/
type Matcher = {
from: string,
to: string
}
declare namespace plugins {
interface CommandContext {
/**
* 可以用此接口进行文件创建
*/
createFile(relativeFilePath: string, contents: Buffer);
/**
* 构建配置
*/
buildConfig: BuildConfigParam;
/**
* 项目绝对路径
*/
projectRoot: string;
/**
* 项目输出绝对路径
*/
outputDir: string;
}
/**
* 构建管线命令
*/
interface Command {
/**
* 项目中的每个文件都会执行此函数,返回 file 表示保留此文件,返回 null 表示将此文件从构建管线中删除,即不会发布
*/
onFile?(file: File): Promise<File | null>
/**
* 项目中所有文件均执行完后,最终会执行此函数。
* 这个函数主要被用于创建新文件
*/
onFinish?(pluginContext?: CommandContext): Promise<void>
[options: string]: any;
}
interface File {
/**
* 文件内容的二进制流,如果开发者需要修改文件内容,请修改此属性
*/
contents: Buffer;
/**
* 文件绝对路径,如果开发者需要对文件进行重命名,请修改此属性
*/
path: string;
/**
* 文件所在的项目的项目路径
*/
readonly base: string;
/**
* 文件的相对于 base 属性的相对路径
*/
readonly relative: string;
/**
* 文件变更历史,history[0] 即 origin 属性
*/
readonly history: ReadonlyArray<string>;
/**
* 文件所在的文件夹的绝对路径
*/
readonly dirname: string;
/**
* 文件的文件名
*/
readonly basename: string;
/**
* 文件的扩展名
*/
readonly extname: string;
/**
* 文件的初始文件名
*/
readonly origin: string;
/**
* 其他自定义属性
*/
[customProperty: string]: any;
}
}
declare module 'built-in' {
/**
* 混淆插件参数,设置源代码和目标代码
*/
type UglifyPluginOption = { sources: string[], target: string };
type UglifyPluginOptions = UglifyPluginOption[];
/**
* 混淆插件
*/
export class UglifyPlugin implements plugins.Command {
constructor(mergeSelector: UglifyPluginOptions);
}
type LibraryType = "debug" | "release";
type CompilePluginOptions = { libraryType: LibraryType, defines?: any };
/**
* 编译命令
*/
export class CompilePlugin implements plugins.Command {
constructor(options: CompilePluginOptions);
}
/**
* EXML 插件,用于发布 EXML 文件
*/
export class ExmlPlugin implements plugins.Command {
constructor(publishPolicy: EXML_Publish_Policy);
}
/**
* 发布策略
* * default : 使用 egretProperties.json 中的 exmlPublishPolicy 中的策略
* * debug : 默认策略,用于开发环境
* * contents : 将 EXML 的内容写入到主题文件中
* * gjs : 将生成的JS文件写入到主题文件中
* * commonjs : 将EXML合并为一个 CommonJS 风格的文件
* * commonjs2 : 将EXML合并为一个含有解析方法和皮肤定义的文件,且皮肤抽离为一份配置
* * json : 将每个EXML文件生成一份配置
*/
type EXML_Publish_Policy = "default" | "debug" | "contents" | "gjs" | "commonjs" | "commonjs2" | "json"
/**
* 生成 manifest 文件,这个文件会被用于记录 JavaScript 文件的版本号
*/
export class ManifestPlugin implements plugins.Command {
constructor(options?: ManifestPluginOptions)
}
/**
* 生成文件的文件名
* 支持 json 与 js 两种格式
*/
type ManifestPluginOptions = {
output: string,
hash?: "crc32",
/**
* 是否输出转换过程
*/
verbose?: boolean
}
/**
* EmitResConfigFilePlugin 的参数
* * output: 生成路径,可以指定生成为 *.res.js 文件或者 *.res.json 文件
* * typeSelector: 根据文件路径决定文件类型
* * nameSelector: 根据文件路径决定文件的资源名
* * groupSelector: 根据文件路径决定资源所述的资源组
*/
type EmitResConfigFilePluginOptions = {
output: string,
typeSelector: (path: string) => string | null | undefined,
nameSelector: (path: string) => string | null | undefined,
groupSelector: (path: string) => string | null | undefined,
}
/**
* 生成 res.json 文件或者 res.js 文件
*/
export class EmitResConfigFilePlugin implements plugins.Command {
constructor(options: EmitResConfigFilePluginOptions)
}
export type ConvertResourceConfigPluginOption = {
resourceConfigFiles: { filename: string, root: string }[];
nameSelector: (url: string) => string;
TM_Verbose: boolean;
}
export class ConvertResConfigFilePlugin implements plugins.Command {
constructor(options: ConvertResourceConfigPluginOption);
}
/**
* 增量编译
* 这个插件生成的 JavaScript 代码不会被添加到构建管线中,后续其他插件无法获取生成的 js 文件
* 这个功能将会在未来被 watch 模式代替掉
*/
export class IncrementCompilePlugin implements plugins.Command {
}
type TextureMergerOptions = {
textureMergerRoot: string[];
}
/**
* 使用 TextureMerger 实现纹理自动合并,依赖 TextureMerger 1.7 以上的版本
*/
export class TextureMergerPlugin implements plugins.Command {
constructor(options: TextureMergerOptions);
}
type CleanPluginOptions = {
matchers: string[]
}
export class CleanPlugin implements plugins.Command {
constructor(options: CleanPluginOptions);
}
type RenamePluginOptions = {
/**
* 是否输出日志
*/
verbose?: boolean
/**
* 采用何种 hash 算法,目前暂时只支持 crc32
*/
hash?: "crc32"
/**
* 设置匹配规则,将指定文件进行改名
* 该参数是个数组,允许设置多个匹配规则
*/
matchers: Matcher[]
}
/**
* 修改文件名插件
*/
export class RenamePlugin implements plugins.Command {
constructor(options: RenamePluginOptions);
}
type ResSplitPluginOptions = {
/**
* 是否输出日志
*/
verbose?: boolean
/**
* 设置匹配规则,将指定文件拷贝至其他文件夹
* 该参数是个数组,允许设置多个匹配规则
*/
matchers: Matcher[]
}
export class ResSplitPlugin implements plugins.Command {
constructor(options: ResSplitPluginOptions);
}
type ZipPluginOptions = {
mergeSelector: (p: string) => string
}
export class ZipPlugin implements plugins.Command {
constructor(option: ZipPluginOptions);
}
type MergeEuiJsonPluginOptions = {
mergeSelector?: (p: string) => string | null,
createConfig?: boolean
}
export class MergeEuiJsonPlugin implements plugins.Command {
constructor(option?: MergeEuiJsonPluginOptions);
}
}
\ No newline at end of file
import * as fs from 'fs';
import * as path from 'path';
type ManifestConfig = {
initial: string[],
game: string[]
}
export class BricksPlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
const filename = file.basename;
if (filename == 'manifest.json') {
const contents = file.contents.toString();
const jsonData: ManifestConfig = JSON.parse(contents);
let content = '';
content += `BK.Script.loadlib("GameRes://js/promise.js");\n`;
for (let item of jsonData.initial) {
if (item != 'js/promise.js' && item != 'js/promise.min.js') {
content += `BK.Script.loadlib("GameRes://${item}");\n`
}
}
for (let item of jsonData.game) {
content += `BK.Script.loadlib("GameRes://${item}");\n`
}
content += `BK.Script.loadlib("GameRes://egret.bricks.js");\n`
file.path = file.dirname + '/manifest.js'
file.contents = new Buffer(content);
} else if (filename == 'main.js') {
const content = file.contents.toString();
let result = content.replace(/RES\.loadConfig\("resource\/default\.res\.json", "resource\/"\)/gm, 'RES.loadConfig("GameRes://resource/default.res.json", "GameRes://resource/")');
result = result.replace(/eui\.Theme\("resource\/default\.thm\.json", _this\.stage\)/gm, 'eui.Theme("GameRes://resource/default.thm.json", _this.stage)');
result += ";global.Main = Main;";
file.path = file.dirname + '/main.js'
file.contents = new Buffer(result);
} else if (filename == 'promise.js') {
return null;
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步index.html 配置到main.js
let mainJSPath = path.join(pluginContext.outputDir, 'main.js');
let mainJSContent = fs.readFileSync(mainJSPath, { encoding: "utf8" });
let projectConfig = pluginContext.buildConfig.projectConfig;
mainJSContent = mainJSContent.replace(/frameRate: 30/gm, `frameRate: ${projectConfig.frameRate}`);
mainJSContent = mainJSContent.replace(/contentWidth: 640/gm, `contentWidth: ${projectConfig.contentWidth}`);
mainJSContent = mainJSContent.replace(/contentHeight: 1136/gm, `contentHeight: ${projectConfig.contentHeight}`);
mainJSContent = mainJSContent.replace(/entryClassName: "Main"/gm, `entryClassName: ${projectConfig.entryClassName}`);
mainJSContent = mainJSContent.replace(/scaleMode: "showAll"/gm, `scaleMode: ${projectConfig.scaleMode}`);
mainJSContent = mainJSContent.replace(/orientation: "auto"/gm, `orientation: ${projectConfig.orientation}`);
fs.writeFileSync(mainJSPath, mainJSContent);
}
}
declare var egret;
\ No newline at end of file
/**
* Created by rockyl on 2018/9/10.
*/
import * as minimatch from "minimatch"
export class ConcatPlugin implements plugins.Command {
private codeMap = {};
private matchers: { sources: string[], target: string }[];
private showLog;
constructor(matchers, showLog = false) {
this.matchers = matchers;
this.showLog = showLog;
}
async onFile(file) {
const filename = file.origin;
if (file.extname != ".js") {
return file;
}
for (let matcher of this.matchers) {
let codes = this.codeMap[matcher.target];
if (!codes) {
codes = this.codeMap[matcher.target] = [];
}
for (let mat of matcher.sources) {
if (minimatch(filename, mat)) {
if (this.showLog) console.log(filename, file.contents.byteLength);
codes.push(file.contents.toString());
return null;
}
}
}
return file;
}
async onFinish(pluginContext) {
for (let matcher of this.matchers) {
let codeMap = this.codeMap;
let codes = [] = codeMap[matcher.target];
let jscode = codes.join('\n');
pluginContext.createFile(matcher.target, new Buffer(jscode));
}
}
[options: string]: any;
}
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
import { BricksPlugin } from './bricks/bricks';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_android/assets/game`;
return {
outputDir,
commands: [
// new CompilePlugin({ libraryType: "debug", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}]),
new ManifestPlugin({ output: 'manifest.json' })
]
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { BricksPlugin } from './bricks/bricks';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_bricks/PublicBrickEngineGame/Res`;
if (command == 'build') {
return {
outputDir,
commands: [
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' }),
new BricksPlugin()
]
}
}
else if (command == 'publish') {
console.log('执行publish')
return {
outputDir,
commands: [
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new ManifestPlugin({ output: 'manifest.json' }),
new UglifyPlugin([{
sources: ["main.js"],
target: "js/main.min.js"
}
]),
new BricksPlugin(),
]
}
} else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin } from 'built-in';
import { BricksPlugin } from './bricks/bricks';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_ios/assets/game`;
return {
outputDir,
commands: [
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}]),
new ManifestPlugin({ output: 'manifest.json' })
]
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import {
UglifyPlugin,
ExmlPlugin,
} from 'built-in';
import {ResultNotificationPlugin} from "./result-notification-plugin";
import {ConcatPlugin} from "./concat-plugin";
import {RollupCompilePlugin} from "./rollup-compile-plugin";
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const {target, command, projectName, version} = params;
if (command == 'build') {
const outputDir = '.';
return {
outputDir,
commands: [
new ExmlPlugin('debug'), // 非 EUI 项目关闭此设置
new RollupCompilePlugin({
publishPolicy: 'debug',
}),
new ResultNotificationPlugin('Build'),
]
}
}
else if (command == 'publish') {
const outputDir = `bin-release/web/${version}`;
return {
outputDir,
commands: [
new RollupCompilePlugin({
publishPolicy: 'release',
libraryType: 'release',
defines: {DEBUG: false, RELEASE: true}
}),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new UglifyPlugin([{
sources: ["resource/default.thm.js"],
target: "resource/default.thm.min.js"
}]),
new ConcatPlugin([
{
sources: [
"libs/modules/**/*.min.js",
"resource/default.thm.min.js",
"bundle.min.js",
],
target: "all.js"
}
]),
new ResultNotificationPlugin('Publish', version),
]
}
}
else {
throw `unknown command : ${params.command}`
}
},
mergeSelector: (path) => {
if (path.indexOf("assets/bitmap/") >= 0) {
return "assets/bitmap/sheet.sheet"
}
else if (path.indexOf("armature") >= 0 && path.indexOf(".json") >= 0) {
return "assets/armature/1.zip";
}
},
typeSelector: (path) => {
const ext = path.substr(path.lastIndexOf(".") + 1);
const typeMap = {
"jpg": "image",
"png": "image",
"webp": "image",
"json": "json",
"fnt": "font",
"pvr": "pvr",
"mp3": "sound",
"zip": "zip",
"sheet": "sheet",
"exml": "text"
}
let type = typeMap[ext];
if (type == "json") {
if (path.indexOf("sheet") >= 0) {
type = "sheet";
} else if (path.indexOf("movieclip") >= 0) {
type = "movieclip";
}
;
}
return type;
}
}
export = config;
/// 阅读 api.d.ts 查看文档
///<reference path="api.d.ts"/>
import * as path from 'path';
import { UglifyPlugin, CompilePlugin, ManifestPlugin, ExmlPlugin, EmitResConfigFilePlugin, TextureMergerPlugin, CleanPlugin } from 'built-in';
import { WxgamePlugin } from './wxgame/wxgame';
import { CustomPlugin } from './myplugin';
import * as defaultConfig from './config';
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const { target, command, projectName, version } = params;
const outputDir = `../${projectName}_wxgame`;
if (command == 'build') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "debug", defines: { DEBUG: true, RELEASE: false } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else if (command == 'publish') {
return {
outputDir,
commands: [
new CleanPlugin({ matchers: ["js", "resource"] }),
new CompilePlugin({ libraryType: "release", defines: { DEBUG: false, RELEASE: true } }),
new ExmlPlugin('commonjs'), // 非 EUI 项目关闭此设置
new WxgamePlugin(),
new UglifyPlugin([{
sources: ["main.js"],
target: "main.min.js"
}
]),
new ManifestPlugin({ output: 'manifest.js' })
]
}
}
else {
throw `unknown command : ${params.command}`;
}
},
mergeSelector: defaultConfig.mergeSelector,
typeSelector: defaultConfig.typeSelector
}
export = config;
/**
* 示例自定义插件,您可以查阅 http://developer.egret.com/cn/github/egret-docs/Engine2D/projectConfig/cmdExtensionPlugin/index.html
* 了解如何开发一个自定义插件
*/
export class CustomPlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
return file;
}
async onFinish(commandContext: plugins.CommandContext) {
}
}
\ No newline at end of file
This diff is collapsed.
{
"name": "scripts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"dependencies": {
"compare-versions": "^3.4.0",
"glob": "^7.1.3",
"minimatch": "^3.0.4",
"node-notifier": "^5.2.1",
"rollup": "^0.65.2",
"rollup-plugin-commonjs": "^9.1.6",
"rollup-plugin-node-resolve": "^3.4.0",
"rollup-plugin-uglify": "^5.0.2",
"tippex": "^3.0.0",
"typescript": "^3.0.3"
}
}
const notifier = require('node-notifier');
export class ResultNotificationPlugin implements plugins.Command {
operate;
version;
constructor(operate, version = '') {
this.operate = operate;
this.version = version;
}
async onFile(file: plugins.File) {
return file;
}
async onFinish(commandContext: plugins.CommandContext) {
notifier.notify({
title: 'Egret',
message: this.operate + ' complete!'
});
if(this.version){
console.log(this.operate, 'complete:', this.version)
}
}
}
import * as fs from "fs";
import * as path from "path";
const rollup = require('rollup');
const resolve = require('rollup-plugin-node-resolve');
const typescriptPlugin = require('./rollup-plugin-typescript');
const typescript = require('typescript');
const {uglify} = require('rollup-plugin-uglify');
const commonjs = require('rollup-plugin-commonjs');
const glob = require('glob');
export class RollupCompilePlugin implements plugins.Command {
options;
[options: string]: any;
constructor(options) {
this.options = options;
}
async onFile(file: plugins.File) {
return file;
}
async onFinish(commandContext: plugins.CommandContext) {
const {publishPolicy, libraryType, defines} = this.options;
const debugMode = publishPolicy === 'debug';
const tsconfig = require('../tsconfig.json');
/*if (!debugMode) {
tsconfig.compilerOptions.defines = defines;
}
console.log(tsconfig);*/
let plugins = [
typescriptPlugin({
typescript,
tsconfig,
}),
resolve(),
commonjs(),
];
if (!debugMode) {
plugins.push(uglify());
}
let outputConfig: any = {
format: 'cjs',
};
if (debugMode) {
outputConfig.sourcemap = true;
}
const bundle = await rollup.rollup({
input: './src/Main.ts',
plugins,
});
const ps = [];
if (!debugMode) {
const propertiesFile = path.resolve(commandContext.projectRoot, 'egretProperties.json');
const properties = require(propertiesFile);
const minStr = libraryType == 'release' ? '.min' : '';
for (let module of properties.modules) {
glob.sync(`libs/modules/${module.name}/*${minStr}.js`).forEach(libFile => {
ps.push(new Promise((resolve, reject) => {
fs.readFile(libFile, function (e, content) {
if (e) {
reject(e);
} else {
resolve({libFile, content});
}
});
}))
}
);
}
}
const results = await Promise.all([
Promise.all(ps),
bundle.generate(outputConfig),
]);
results[0].forEach(({libFile, content}) => {
commandContext.createFile(libFile, content);
});
const {code, map} = results[1];
let bundleFile = debugMode ?
`bin-debug/bundle.js` :
'bundle.min.js';
let sourceCode = code;
if(!debugMode){
sourceCode = 'RELEASE=true;DEBUG=false;' + sourceCode;
}
if (map) {
commandContext.createFile(bundleFile + '.map', new Buffer(map.toString()));
sourceCode += `//# sourceMappingURL=bundle.js.map\n`;
}
commandContext.createFile(bundleFile, new Buffer(sourceCode));
if (!debugMode) {
const projectRoot = commandContext.projectRoot;
const filepath = path.join(projectRoot, 'template/web/index.html');
const htmlContent = fs.readFileSync(filepath);
commandContext.createFile("index.html", htmlContent);
}
}
}
/**
* Created by rockyl on 2018/7/6.
*/
module.exports = require('./rollup-plugin-typescript.cjs');
\ No newline at end of file
'use strict';
var ts = require('typescript');
var rollupPluginutils = require('rollup-pluginutils');
var path = require('path');
var fs = require('fs');
var assign = Object.assign;
var compareVersions = require('compare-versions');
var tippex = require('tippex');
function endsWith(str, tail) {
return !tail.length || str.slice(-tail.length) === tail;
}
function getDefaultOptions() {
return {
noEmitHelpers: true,
module: 'es2015',
sourceMap: true
};
}
// Gratefully lifted from 'look-up', due to problems using it directly:
// https://github.com/jonschlinkert/look-up/blob/master/index.js
// MIT Licenced
function findFile(cwd, filename) {
var fp = cwd ? (cwd + '/' + filename) : filename;
if (fs.existsSync(fp)) {
return fp;
}
var segs = cwd.split(path.sep);
var len = segs.length;
while (len--) {
cwd = segs.slice(0, len).join('/');
fp = cwd + '/' + filename;
if (fs.existsSync(fp)) {
return fp;
}
}
return null;
}
function compilerOptionsFromTsConfig(typescript, tsconfig) {
var cwd = process.cwd();
var tsconfig = typescript.readConfigFile(
findFile(cwd, 'tsconfig.json'),
function (path) {
return fs.readFileSync(path, 'utf8');
}
);
if (!tsconfig.config || !tsconfig.config.compilerOptions) return {};
return tsconfig.config.compilerOptions;
}
function adjustCompilerOptions(typescript, options) {
// Set `sourceMap` to `inlineSourceMap` if it's a boolean
// under the assumption that both are never specified simultaneously.
if (typeof options.inlineSourceMap === 'boolean') {
options.sourceMap = options.inlineSourceMap;
delete options.inlineSourceMap;
}
// Delete the `declaration` option to prevent compilation error.
// See: https://github.com/rollup/rollup-plugin-typescript/issues/45
delete options.declaration;
var tsVersion = typescript.version.split('-')[0];
if ('strictNullChecks' in options && compareVersions(tsVersion, '1.9.0') < 0) {
delete options.strictNullChecks;
console.warn("rollup-plugin-typescript: 'strictNullChecks' is not supported; disabling it");
}
}
// Hack around TypeScript's broken handling of `export class` with
// ES6 modules and ES5 script target.
//
// It works because TypeScript transforms
//
// export class A {}
//
// into something like CommonJS, when we wanted ES6 modules.
//
// var A = (function () {
// function A() {
// }
// return A;
// }());
// exports.A = A;
//
// But
//
// class A {}
// export { A };
//
// is transformed into this beauty.
//
// var A = (function () {
// function A() {
// }
// return A;
// }());
// export { A };
//
// The solution is to replace the previous export syntax with the latter.
function fix(code, id) {
// Erase comments, strings etc. to avoid erroneous matches for the Regex.
var cleanCode = getErasedCode(code, id);
var re = /export\s+(default\s+)?((?:abstract\s+)?class)(?:\s+(\w+))?/g;
var match;
while (match = re.exec(cleanCode)) {
// To keep source maps intact, replace non-whitespace characters with spaces.
code = erase(code, match.index, match[0].indexOf(match[2]));
var name = match[3];
if (match[1]) { // it is a default export
// TODO: support this too
if (!name) throw new Error(("TypeScript Plugin: cannot export an un-named class (module " + id + ")"));
// Export the name ` as default`.
name += ' as default';
}
// To keep source maps intact, append the injected exports last.
code += "\nexport { " + name + " };";
}
return code;
}
function getErasedCode(code, id) {
try {
return tippex.erase(code);
} catch (e) {
throw new Error(("rollup-plugin-typescript: " + (e.message) + "; when processing: '" + id + "'"));
}
}
function erase(code, start, length) {
var end = start + length;
return code.slice(0, start) +
code.slice(start, end).replace(/[^\s]/g, ' ') +
code.slice(end);
}
var resolveHost = {
directoryExists: function directoryExists(dirPath) {
try {
return fs.statSync(dirPath).isDirectory();
} catch (err) {
return false;
}
},
fileExists: function fileExists(filePath) {
try {
return fs.statSync(filePath).isFile();
} catch (err) {
return false;
}
}
};
/*
interface Options {
tsconfig?: boolean;
include?: string | string[];
exclude?: string | string[];
typescript?: typeof ts;
module?: string;
}
*/
// The injected id for helpers. Intentially invalid to prevent helpers being included in source maps.
var helpersId = '\0typescript-helpers';
var helpersSource = fs.readFileSync(path.resolve(__dirname, './typescript-helpers.js'), 'utf-8');
function typescript(options) {
options = assign({}, options || {});
var filter = rollupPluginutils.createFilter(
options.include || ['*.ts+(|x)', '**/*.ts+(|x)'],
options.exclude || ['*.d.ts', '**/*.d.ts']);
delete options.include;
delete options.exclude;
// Allow users to override the TypeScript version used for transpilation.
var typescript = options.typescript || ts;
delete options.typescript;
// Load options from `tsconfig.json` unless explicitly asked not to.
var tsconfig = options.tsconfig === false ? {} :
compilerOptionsFromTsConfig(typescript, options.tsconfig);
delete options.tsconfig;
// Since the CompilerOptions aren't designed for the Rollup
// use case, we'll adjust them for use with Rollup.
adjustCompilerOptions(typescript, tsconfig);
adjustCompilerOptions(typescript, options);
// Merge all options.
options = assign(tsconfig, getDefaultOptions(), options);
// Verify that we're targeting ES2015 modules.
if (options.module !== 'es2015' && options.module !== 'es6') {
throw new Error(("rollup-plugin-typescript: The module kind should be 'es2015', found: '" + (options.module) + "'"));
}
var parsed = typescript.convertCompilerOptionsFromJson(options, process.cwd());
if (parsed.errors.length) {
parsed.errors.forEach(function (error) {
return console.error(("rollup-plugin-typescript: " + (error.messageText)));
});
throw new Error("rollup-plugin-typescript: Couldn't process compiler options");
}
var compilerOptions = parsed.options;
return {
resolveId: function resolveId(importee, importer) {
// Handle the special `typescript-helpers` import itself.
if (importee === helpersId) {
return helpersId;
}
if (!importer) return null;
var result;
importer = importer.split('\\').join('/');
if (compareVersions(typescript.version, '1.8.0') < 0) {
// Suppress TypeScript warnings for function call.
result = typescript.nodeModuleNameResolver(importee, importer, resolveHost);
} else {
result = typescript.nodeModuleNameResolver(importee, importer, compilerOptions, resolveHost);
}
if (result.resolvedModule && result.resolvedModule.resolvedFileName) {
if (endsWith(result.resolvedModule.resolvedFileName, '.d.ts')) {
return null;
}
return result.resolvedModule.resolvedFileName;
}
return null;
},
load: function load(id) {
if (id === helpersId) {
return helpersSource;
}
},
transform: function transform(code, id) {
if (!filter(id)) return null;
var transformed = typescript.transpileModule(fix(code, id), {
fileName: id,
reportDiagnostics: true,
compilerOptions: compilerOptions
});
// All errors except `Cannot compile modules into 'es6' when targeting 'ES5' or lower.`
var diagnostics = transformed.diagnostics ?
transformed.diagnostics.filter(function (diagnostic) {
return diagnostic.code !== 1204;
}) : [];
var fatalError = false;
diagnostics.forEach(function (diagnostic) {
var message = typescript.flattenDiagnosticMessageText(diagnostic.messageText, '\n');
if (diagnostic.file) {
var ref = diagnostic.file.getLineAndCharacterOfPosition(diagnostic.start);
var line = ref.line;
var character = ref.character;
console.error(((diagnostic.file.fileName) + "(" + (line + 1) + "," + (character + 1) + "): error TS" + (diagnostic.code) + ": " + message));
} else {
console.error(("Error: " + message));
}
if (diagnostic.category === ts.DiagnosticCategory.Error) {
fatalError = true;
}
});
if (fatalError) {
throw new Error("There were TypeScript errors transpiling");
}
return {
// Always append an import for the helpers.
code: transformed.outputText +
"\nimport { __assign, __awaiter, __extends, __decorate, __metadata, __param } from '" + helpersId + "';",
// Rollup expects `map` to be an object so we must parse the string
map: transformed.sourceMapText ? JSON.parse(transformed.sourceMapText) : null
};
}
};
}
module.exports = typescript;
\ No newline at end of file
export const __assign = Object.assign || function (target) {
for (var source, i = 1; i < arguments.length; i++) {
source = arguments[i];
for (var prop in source) {
if (Object.prototype.hasOwnProperty.call(source, prop)) {
target[prop] = source[prop];
}
}
}
return target;
};
export function __extends(d, b) {
for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __() { this.constructor = d; }
d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
}
export function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
export function __metadata(k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
}
export function __param(paramIndex, decorator) {
return function (target, key) { decorator(target, key, paramIndex); }
}
export function __awaiter(thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator.throw(value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments)).next());
});
}
{
"compilerOptions": {
/* Basic Options */
"target": "es5",
/* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', or 'ESNEXT'. */
"module": "commonjs",
/* Specify module code generation: 'commonjs', 'amd', 'system', 'umd' or 'es2015'. */
"lib": [
"es5",
"es2015.promise"
],
/* Specify library files to be included in the compilation: */
"allowJs": true,
/* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true,
/* Enable all strict type-checking options. */
"noImplicitAny": false
/* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
/* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
/* Source Map Options */
// "sourceRoot": "./", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "./", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
\ No newline at end of file
import * as fs from 'fs';
import * as path from 'path';
export class WxgamePlugin implements plugins.Command {
constructor() {
}
async onFile(file: plugins.File) {
if (file.extname == '.js') {
const filename = file.origin;
if (filename == "libs/modules/promise/promise.js" || filename == 'libs/modules/promise/promise.min.js') {
return null;
}
if (filename == 'libs/modules/egret/egret.js' || filename == 'libs/modules/egret/egret.min.js') {
let content = file.contents.toString();
content += `;window.egret = egret;`;
content = content.replace(/definition = __global/, "definition = window");
file.contents = new Buffer(content);
}
else {
let content = file.contents.toString();
if (
filename == "libs/modules/res/res.js" ||
filename == 'libs/modules/res/res.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.min.js' ||
filename == 'libs/modules/assetsmanager/assetsmanager.js'
) {
content += ";window.RES = RES;"
}
if (filename == "libs/modules/eui/eui.js" || filename == 'libs/modules/eui/eui.min.js') {
content += ";window.eui = eui;"
}
if (filename == 'libs/modules/dragonBones/dragonBones.js' || filename == 'libs/modules/dragonBones/dragonBones.min.js') {
content += ';window.dragonBones = dragonBones';
}
content = "var egret = window.egret;" + content;
if (filename == 'main.js') {
content += ";window.Main = Main;"
}
file.contents = new Buffer(content);
}
}
return file;
}
async onFinish(pluginContext: plugins.CommandContext) {
//同步 index.html 配置到 game.js
const gameJSPath = path.join(pluginContext.outputDir, "game.js");
if(!fs.existsSync(gameJSPath)) {
console.log(`${gameJSPath}不存在,请先使用 Launcher 发布微信小游戏`);
return;
}
let gameJSContent = fs.readFileSync(gameJSPath, { encoding: "utf8" });
const projectConfig = pluginContext.buildConfig.projectConfig;
const optionStr =
`entryClassName: ${projectConfig.entryClassName},\n\t\t` +
`orientation: ${projectConfig.orientation},\n\t\t` +
`frameRate: ${projectConfig.frameRate},\n\t\t` +
`scaleMode: ${projectConfig.scaleMode},\n\t\t` +
`contentWidth: ${projectConfig.contentWidth},\n\t\t` +
`contentHeight: ${projectConfig.contentHeight},\n\t\t` +
`showFPS: ${projectConfig.showFPS},\n\t\t` +
`fpsStyles: ${projectConfig.fpsStyles},\n\t\t` +
`showLog: ${projectConfig.showLog},\n\t\t` +
`maxTouches: ${projectConfig.maxTouches},`;
const reg = /\/\/----auto option start----[\s\S]*\/\/----auto option end----/;
const replaceStr = '\/\/----auto option start----\n\t\t' + optionStr + '\n\t\t\/\/----auto option end----';
gameJSContent = gameJSContent.replace(reg, replaceStr);
fs.writeFileSync(gameJSPath, gameJSContent);
//修改横竖屏
let orientation;
if (projectConfig.orientation == '"landscape"') {
orientation = "landscape";
}
else {
orientation = "portrait";
}
const gameJSONPath = path.join(pluginContext.outputDir, "game.json");
let gameJSONContent = JSON.parse(fs.readFileSync(gameJSONPath, { encoding: "utf8" }));
gameJSONContent.deviceOrientation = orientation;
fs.writeFileSync(gameJSONPath, JSON.stringify(gameJSONContent, null, "\t"));
}
}
\ No newline at end of file
import AssetAdapter from "./views/adapters/AssetAdapter";
import ThemeAdapter from "./views/adapters/ThemeAdapter";
import LoadingView from "./views/LoadingView";
import GameConfig from "./model/GameConfig";
import MainStage from "./views/MainStage";
import {Dispatcher, LocalStorage, StageProxy} from "./alienlib-cjs/support";
class Main extends eui.UILayer {
constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
}
private onAddedToStage() {
Dispatcher.init();
StageProxy.init(this.stage, this);
this.stage.scaleMode = egret.Capabilities.isMobile ? egret.StageScaleMode.FIXED_WIDTH : egret.StageScaleMode.SHOW_ALL;
this.stage.orientation = egret.Capabilities.isMobile ? egret.OrientationMode.PORTRAIT : egret.OrientationMode.AUTO;
}
protected createChildren(): void {
super.createChildren();
egret.registerImplementation("eui.IAssetAdapter", new AssetAdapter());
egret.registerImplementation("eui.IThemeAdapter", new ThemeAdapter());
this.runGame().catch(e => {
console.log(e);
})
}
private async runGame() {
await this.loadResource();
this.createGameScene();
}
private async loadResource() {
try {
egret.ImageLoader.crossOrigin = "anonymous";
const resBasePath = window['resPath'] || '';
await RES.loadConfig("default.res.json", resBasePath + "resource/");
await this.loadTheme();
let loadingView = LoadingView.instance;
this.addChild(loadingView);
await RES.loadGroup("loading", 0, loadingView);
}
catch (e) {
console.error(e);
}
}
private loadTheme() {
return new Promise((resolve, reject) => {
let theme = new eui.Theme("resource/default.thm.json", this.stage);
theme.addEventListener(eui.UIEvent.COMPLETE, () => {
resolve();
}, this);
})
}
/**
* 创建场景界面
* Create scene interface
*/
protected createGameScene(): void {
LocalStorage.init(GameConfig.gameName);
let mainStage:MainStage = MainStage.instance;
this.addChildAt(mainStage, 0);
}
}
/**
* Created by rockyl on 2018/8/21.
*/
import Alert from "./views/panels/PanelAlert";
import Toast from "./views/components/Toast";
import lang from "./lang";
import {gameInfo} from "./model/DataCenter";
export default class Utils{
static showErrorAlert(e = null, callback = null){
let text = e || lang.net_error;
Alert.show(text, function(){
if(callback){
callback();
}
})
}
static showNoMoreCredits(){
Toast.show({text: gameInfo.creditUnit + lang.no_more_credits});
}
static delayLoad(){
RES.loadGroup('menu');
RES.loadGroup('common');
RES.loadGroup('play');
RES.loadGroup('panel_rank');
RES.loadGroup('panel_result');
}
}
/**
* Created by rockyl on 16/3/29.
*/
import {IAnimation} from "./IAnimation";
export class Fade implements IAnimation {
private _tween: egret.Tween;
private _target: any;
private _targetAlpha: number;
private _duration: number;
constructor(target: any) {
this._target = target;
}
fadeIn(duration: number = 200): void {
this._duration = duration;
this._targetAlpha = 1;
this._target.alpha = 0;
this._target.visible = true;
this.play();
}
fadeOut(duration: number = 200): void {
this._duration = duration;
this._targetAlpha = 0;
this._target.alpha = 1;
this.play();
}
play(): void {
this._tween = egret.Tween.get(this._target).to({alpha: this._targetAlpha}, this._duration).set({visible: this._targetAlpha > 0});
}
stop(): void {
if (this._tween) {
egret.Tween.removeTweens(this._target);
}
}
}
/**
* Created by rockyl on 16/3/9.
*/
export interface IAnimation {
play(): void;
stop(): void;
}
/**
* Created by rockyl on 16/3/29.
*/
export class Shake {
private _tween: egret.Tween;
private _target: any;
private _callback;
private _size;
private _perDuration;
private _count = 0;
private _oldPos: any = {};
constructor(target: any) {
this._target = target;
}
play(callback, count = 1, size = 10, duration = 300): void {
this._callback = callback;
this._size = size;
this._perDuration = duration / 8;
this._count = count;
this._playOnce()
}
_playOnce() {
let {x, y} = this._target;
this._oldPos = {x, y};
let s = this._size;
let offsets = [
[0, -s],
[s, -s],
[s, 0],
[0, 0],
[-s, 0],
[-s, s],
[0, s],
[0, 0],
];
let tween = this._tween = egret.Tween.get(this._target, null, null, true);
offsets.forEach(offset => {
tween.to({x: x + offset[0], y: y + offset[1]}, this._perDuration)
});
tween.call(() => {
if (this._count > 0) {
this._count--;
this._playOnce();
} else {
this._onFinished();
}
});
}
_onFinished() {
if (this._callback) {
this._callback();
}
}
stop(): void {
if (this._tween) {
egret.Tween.get(this._target, null, null, true)
.to(this._oldPos, 10);
}
}
}
/**
* Created by rockyl on 2018/1/5.
*
* 闪烁图片
*/
import {Wave} from "./Wave";
export class TwinkleImage extends eui.Image {
private _autoPlay = true;
private _duration = 1000;
private _max = 1;
private _min = 0;
private _loop = 0;
private _wave;
protected childrenCreated(): void {
super.childrenCreated();
this.resetWave();
if (this._autoPlay) {
this.play();
}
}
private resetWave() {
if (this._wave) {
this._wave.stop();
}
this._wave = new Wave(this, this._duration, this.wave.bind(null, this._max, this._min), this._loop, false);
}
private wave(max, min, t) {
return {
alpha: (Math.sin(t) / 2 + 0.5) * (max - min) + min
}
}
play() {
this._wave.play();
}
stop() {
this._wave.stop();
}
public get autoPlay() {
return this._autoPlay;
}
public set autoPlay(value) {
if (this._autoPlay != value) {
this._autoPlay = value;
this.resetWave();
}
}
public get duration() {
return this._duration;
}
public set duration(value) {
if (this._duration != value) {
this._duration = value;
this.resetWave();
}
}
public get max() {
return this._max;
}
public set max(value) {
if (this._max != value) {
this._max = value;
this.resetWave();
}
}
public get min() {
return this._min;
}
public set min(value) {
if (this._min != value) {
this._min = value;
this.resetWave();
}
}
public get loop() {
return this._loop;
}
public set loop(value) {
if (this._loop != value) {
this._loop = value;
this.resetWave();
}
}
}
/**
* Created by rockyl on 16/3/9.
*/
import {IAnimation} from "./IAnimation";
export class Wave implements IAnimation {
static round: Function = function (h: number, t: number): any {
return {x: Math.cos(t) * h, y: Math.sin(t) * h};
};
static cos: Function = function (h: number, t: number): any {
return {x: Math.cos(t) * h, y: 0};
};
static sin: Function = function (h: number, t: number): any {
h = h || 1;
return {x: 0, y: Math.sin(t) * h};
};
static rotate: Function = function (t: number): any {
return {r: 360 * t / Math.PI / 2};
};
static shake: Function = function (angle: number, count: number, t: number): any {
return {r: Math.sin(t * count) * angle};
};
static breath: Function = function (scale: number, t: number): any {
return {sx: Math.sin(t) * scale + 1, sy: -Math.sin(t + Math.PI / 4) * scale + 1};
};
static zoom: Function = function (scale: number, t: number): any {
scale = scale || 0.1;
return {sx: Math.sin(t) * scale + 1, sy: Math.sin(t) * scale + 1};
};
static fade: Function = function (base, t: number): any {
return {alpha: (Math.sin(t) + 1) * 0.5 + base};
};
_tween: egret.Tween;
target: any;
duration: number;
delay: number;
offset: number;
loop: number;
reverse: boolean;
private _calProps;
private _oldProperties: any = {};
private _count;
constructor(target: any, duration: number, calProps: Function = null, loop: number = 0, autoPlay: boolean = true, reverse: boolean = false, delay: number = 0, offset: number = 0) {
this.target = target;
this._calProps = calProps ? calProps : Wave.round;
this.duration = duration;
this.loop = loop;
this.reverse = reverse;
this.delay = delay;
this.offset = offset;
this.updateRegisterPos();
if (autoPlay) {
this.play();
}
}
updateRegisterPos(): void {
this._oldProperties.x = this.target.x;
this._oldProperties.y = this.target.y;
this._oldProperties.scaleX = this.target.scaleX;
this._oldProperties.scaleY = this.target.scaleY;
this._oldProperties.skewX = this.target.skewX;
this._oldProperties.skewY = this.target.skewY;
this._oldProperties.rotation = this.target.rotation;
this._oldProperties.alpha = this.target.alpha;
}
play() {
if (this._tween) {
return this._tween;
}
this._count = 0;
return this._playStep();
}
_playStep() {
if (this.loop > 0 && this._count >= this.loop) {
this.stop();
return;
}
this._count++;
this.t = this.reverse ? Math.PI * 2 : 0;
this._tween = egret.Tween.get(this);
this._tween.wait(this.delay).to({t: this.reverse ? 0 : Math.PI * 2}, this.duration).call(this._playStep, this);
return this._tween;
}
private _t: number = 0;
private get t(): number {
return this._t;
}
private set t(value: number) {
if (!this.target.stage) {
return;
}
this._t = value;
let props: any = this._calProps.call(this, this._t + this.offset);
if (props.hasOwnProperty('x')) {
this.target.x = (props.x || 0) + this._oldProperties.x;
}
if (props.hasOwnProperty('y')) {
this.target.y = (props.y || 0) + this._oldProperties.y;
}
if (props.hasOwnProperty('sx')) {
this.target.scaleX = props.sx;
}
if (props.hasOwnProperty('sy')) {
this.target.scaleY = props.sy;
}
if (props.hasOwnProperty('skewX')) {
this.target.skewX = props.skewX;
}
if (props.hasOwnProperty('skewY')) {
this.target.skewY = props.skewY;
}
if (props.hasOwnProperty('r')) {
this.target.rotation = props.r;
}
if (props.hasOwnProperty('alpha')) {
this.target.alpha = props.alpha;
}
}
stop(recovery: boolean = false, animation: boolean = false, duration: number = 1000): void {
if (!this._tween) {
return;
}
egret.Tween.removeTweens(this);
if (recovery) {
egret.Tween.get(this.target).to(this._oldProperties, duration);
}
this._tween = null;
}
get playing(): boolean {
return this._tween != null;
}
}
/**
* Created by rockyl on 2018/9/12.
*/
export {
}
/**
* Created by rockyl on 2017/12/5.
*
* 自填充组件
*/
export class FullChild extends eui.Group {
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.addEventListener(egret.Event.RESIZE, this.onResize, this);
}
protected onRemovedFromStage(event: egret.Event): void {
this.removeEventListener(egret.Event.RESIZE, this.onResize, this);
}
private onResize(event: egret.Event): void {
if (this.numChildren > 0) {
this.updateChild(this.getChildAt(0))
}
}
private updateChild(child) {
let scale;
if (this.width / this.height > child.width / child.height) {
scale = this.width / child.width;
} else {
scale = this.height / child.height;
}
child.scaleX = child.scaleY = scale;
}
}
/**
* Convert the text in html format to the object that can be assigned to the egret.TextField#textFlow property
* @see http://edn.egret.com/cn/docs/page/146 Text mixed in a variety of style
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/text/HtmlTextParser.ts
* @language en_US
*/
/**
* 将html格式文本转换为可赋值给 egret.TextField#textFlow 属性的对象
* @see http://edn.egret.com/cn/docs/page/146 多种样式文本混合
* @version Egret 2.4
* @platform Web,Native
* @includeExample egret/text/HtmlTextParser.ts
* @language zh_CN
*/
export class HtmlTextParser {
/**
* @version Egret 2.4
* @platform Web,Native
*/
constructor() {
this.initReplaceArr();
this.initPreReplaceArr();
}
private replaceArr: any[] = [];
private initReplaceArr(): void {
const arr = this.replaceArr = [];
arr.push([/&lt;/g, "<"]);
arr.push([/&gt;/g, ">"]);
arr.push([/&amp;/g, "&"]);
arr.push([/&quot;/g, "\""]);
arr.push([/&apos;/g, "\'"]);
}
private preReplaceArr: any[] = [];
private initPreReplaceArr() {
const arr = this.preReplaceArr = [];
arr.push([/\\\"/g, "\""]);
arr.push([/<br>/g, "\n"]);
}
/**
* @private
*
* @param value
* @returns
*/
private replaceSpecial(value: string): string {
for (let i = 0; i < this.replaceArr.length; i++) {
let k = this.replaceArr[i][0];
let v = this.replaceArr[i][1];
value = value.replace(k, v);
}
return value;
}
/**
* @private
*/
private resutlArr: Array<egret.ITextElement> = [];
/**
* Convert the text in html format to the object that can be assigned to the egret.TextField#textFlow property
* @param htmltext {string} Text in html
* @returns {Array<egret.ITextElement>} 可赋值给 egret.TextField#textFlow Object that can be assigned to the egret.TextField#textFlow property
* @version Egret 2.4
* @platform Web,Native
* @language en_US
*/
/**
* 将html格式文本转换为可赋值给 egret.TextField#textFlow 属性的对象
* @param htmltext {string} html文本
* @returns {Array<egret.ITextElement>} 可赋值给 egret.TextField#textFlow 属性的对象
* @version Egret 2.4
* @platform Web,Native
* @language zh_CN
*/
public parse(htmltext: string): egret.ITextElement[] {
this.preReplaceArr.forEach(p => {
htmltext = htmltext.replace(p[0], p[1]);
});
this.stackArray = [];
this.resutlArr = [];
let firstIdx = 0;//文本段开始位置
let length: number = htmltext.length;
while (firstIdx < length) {
let starIdx: number = htmltext.indexOf("<", firstIdx);
if (starIdx < 0) {
this.addToResultArr(htmltext.substring(firstIdx));
firstIdx = length;
}
else {
this.addToResultArr(htmltext.substring(firstIdx, starIdx));
let fontEnd = htmltext.indexOf(">", starIdx);
if (fontEnd == -1) {
egret.$error(1038);
fontEnd = starIdx;
}
else if (htmltext.charAt(starIdx + 1) == "\/") {//关闭
this.stackArray.pop();
}
else {
this.addToArray(htmltext.substring(starIdx + 1, fontEnd));
}
firstIdx = fontEnd + 1;
}
}
return this.resutlArr;
}
public parser(htmltext: string): Array<egret.ITextElement> {
return this.parse(htmltext);
}
/**
* @private
*
* @param value
*/
private addToResultArr(value: string): void {
if (value == "") {
return;
}
value = this.replaceSpecial(value);
if (this.stackArray.length > 0) {
this.resutlArr.push({text: value, style: this.stackArray[this.stackArray.length - 1]})
}
else {
this.resutlArr.push(<egret.ITextElement>{text: value});
}
}
//将字符数据转成Json数据
private changeStringToObject(str: string): egret.ITextStyle {
str = this.replaceSpecial(str.trim());
let info: any = {};
let header = [];
if (str.charAt(0) == "i" || str.charAt(0) == "b" || str.charAt(0) == "u") {
this.addProperty(info, str, "true");
}
else if (header = str.match(/^(font|a)\s/)) {
str = str.substring(header[0].length).trim();
let next: number = 0;
let titles;
while (titles = str.match(this.getHeadReg())) {
let title = titles[0];
let value = "";
str = str.substring(title.length).trim();
if (str.charAt(0) == "\"") {
next = str.indexOf("\"", 1);
value = str.substring(1, next);
next += 1;
}
else if (str.charAt(0) == "\'") {
next = str.indexOf("\'", 1);
value = str.substring(1, next);
next += 1;
}
else {
value = str.match(/(\S)+/)[0];
next = value.length;
}
this.addProperty(info, title.substring(0, title.length - 1).trim(), value.trim());
str = str.substring(next).trim();
}
}
return info;
}
/**
* @private
*
* @returns
*/
private getHeadReg(): RegExp {
return /^(color|textcolor|strokecolor|stroke|b|bold|i|italic|u|size|fontfamily|href|target)(\s)*=/;
}
/**
* @private
*
* @param info
* @param head
* @param value
*/
private addProperty(info: egret.ITextStyle, head: string, value: string): void {
switch (head.toLowerCase()) {
case "color":
case "textcolor":
value = value.replace(/#/, "0x");
info.textColor = parseInt(value);
break;
case "strokecolor":
value = value.replace(/#/, "0x");
info.strokeColor = parseInt(value);
break;
case "stroke":
info.stroke = parseInt(value);
break;
case "b":
case "bold":
info.bold = value == "true";
break;
case "u":
info.underline = value == "true";
break;
case "i":
case "italic":
info.italic = value == "true";
break;
case "size":
info.size = parseInt(value);
break;
case "fontfamily":
info.fontFamily = value;
break;
case "href":
info.href = this.replaceSpecial(value);
break;
case "target":
info.target = this.replaceSpecial(value);
break;
}
}
/**
* @private
*/
private stackArray: Array<egret.ITextStyle>;
/**
* @private
*
* @param infoStr
*/
private addToArray(infoStr: string): void {
let info: egret.ITextStyle = this.changeStringToObject(infoStr);
if (this.stackArray.length == 0) {
this.stackArray.push(info);
}
else {
let lastInfo: Object = this.stackArray[this.stackArray.length - 1];
for (let key in lastInfo) {
if (info[key] == null) {
info[key] = lastInfo[key];
}
}
this.stackArray.push(info);
}
}
}
/**
* Created by rockyl on 2018/8/16.
*
* 滚动式背景图
*/
export enum LOOP_DIRECTION {
LEFT,
RIGHT,
UP,
DOWN,
}
export class LoopComponent extends egret.DisplayObjectContainer {
_direction: LOOP_DIRECTION;
_sizeField: string;
_posField: string;
_moveSign;
_lastPos = 0;
_onceDistance;
_loopDistance;
_distance = 0;
_scrollRect: egret.Rectangle;
constructor(direction: LOOP_DIRECTION, width, height) {
super();
this._scrollRect = new egret.Rectangle(0, 0, width, height);
this._direction = direction;
this._sizeField = direction < 2 ? 'width' : 'height';
this._posField = direction < 2 ? 'x' : 'y';
this._moveSign = direction % 2 == 0 ? 1 : -1;
}
private setup(parts) {
let distance = 0;
for (let item of parts) {
let part;
if (typeof item == 'string') {
part = new egret.Bitmap(RES.getRes(item));
} else if (item instanceof egret.Texture) {
part = new egret.Bitmap(item);
} else {
part = item;
}
if(this._moveSign < 0){
this._lastPos = part[this._posField] = this.numChildren == 0 ? 0 : this._lastPos - part[this._sizeField];
}else{
part[this._posField] = this.numChildren == 0 ? 0 : this._lastPos;
this._lastPos += part[this._sizeField];
}
distance += part[this._sizeField];
this.addChild(part);
}
return distance;
}
setupOnce(resArr) {
this._distance = this._onceDistance = this.setup(resArr);
this.update();
}
setupLoop(resArr) {
this._loopDistance = this.setup(resArr);
this._distance = this._onceDistance + this._loopDistance - (this._moveSign < 0);
this.setup(resArr);
this.update();
}
setViewport(pos) {
let nPos;
if (pos < this._distance) {
nPos = this._moveSign * pos
} else {
nPos = this._moveSign * (pos - this._distance) % this._loopDistance + this._onceDistance - (this._moveSign < 0 ? this._onceDistance * 2 : 0)
}
this._scrollRect[this._posField] = nPos;
this.update();
}
update() {
this.scrollRect = this._scrollRect;
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/3/16.
*/
import {checkNeedLoad, loadResGroups} from "../tools/ResGroupsLoader";
let watchPromise;
export function load(resGroupNames, onProgress, onBeginLoadResGroups, onEndLoadResGroups) {
let p: Promise<any>;
let loading = true;
if (resGroupNames && resGroupNames.length > 0 && checkNeedLoad(resGroupNames)) {
onBeginLoadResGroups(true);
p = loadResGroups(resGroupNames, onProgress).then(() => {
loading = false;
onEndLoadResGroups();
});
} else {
onBeginLoadResGroups(false);
loading = false;
onEndLoadResGroups();
p = Promise.resolve();
}
return p.then(() => {
watchPromise && watchPromise();
});
}
export function watchLoaded() {
return new Promise(resolve => {
watchPromise = resolve;
})
}
\ No newline at end of file
/**
* Created by rockyl on 2018/9/12.
*/
import * as ResourceLoader from './ResourceLoader'
export {
ResourceLoader,
}
/**
* Created by rockyl on 2018/9/11.
*/
import * as animation from './animation'
import * as egret from './egret'
import * as navigator from './navigator'
import * as popup from './popup'
import * as support from './support'
import * as tools from './tools'
import * as ui from './ui'
export {
animation,
egret,
navigator,
popup,
support,
tools,
ui,
}
/**
* Created by rocky.l on 2017/1/19.
*
* 场景导航器
*/
import {INavigatorDelegate, NavigatorAction, StackNavigator} from "./StackNavigator";
export interface INavigatorViewBase {
onAddView(): boolean;
onWillMount(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillUnMount(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidEnter(last: string, action: NavigatorAction, parameters: any): void;
onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any>;
onDidLeave(next: string, action: NavigatorAction, parameters: any): void;
}
export class Navigator extends egret.EventDispatcher implements INavigatorDelegate {
static VIEW_WILL_ENTER: string = 'VIEW_WILL_ENTER';
static VIEW_DID_ENTER: string = 'VIEW_DID_ENTER';
static VIEW_WILL_LEAVE: string = 'VIEW_WILL_LEAVE';
static VIEW_DID_LEAVE: string = 'VIEW_DID_LEAVE';
public static log = false;
stack: StackNavigator;
protected _classDic: any;
protected _instanceDic: any;
protected _currentName: string;
protected _currentView: INavigatorViewBase;
constructor() {
super();
this._classDic = {};
this._instanceDic = {};
this.stack = new StackNavigator(this);
}
register(name: string, clazz: any): void {
this._classDic[name] = clazz;
}
push(name: string, parameters: any = null) {
this.stack.push(name, parameters);
}
pop(parameters: any = null) {
this.stack.pop(parameters);
}
popToBottom(parameters: any = null) {
this.stack.popTo(0, null, parameters);
}
popAll(name: string, parameters: any = null) {
this.stack.popAll(name, parameters);
}
replace(name: string, parameters: any = null) {
this.stack.replace(name, parameters);
}
jump(name: string, parameters: any = null) {
this.stack.jump(name, parameters);
}
get currentView(): INavigatorViewBase {
return this._currentView;
}
get currentName(): string {
return this._currentName;
}
protected newView(name: string): INavigatorViewBase {
return new this._classDic[name]();
}
protected getViewInstanceByName(name: string): INavigatorViewBase {
let view: INavigatorViewBase = this._instanceDic[name];
if (!view) {
view = this._instanceDic[name] = this.newView(name);
}
return view;
}
protected addView(view: INavigatorViewBase, addToBottom) {
}
/**
* 栈入实现
* @param name
* @param last
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onEnter(name: string, last: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
this._currentView = view;
this._currentName = name;
await view.onWillMount(last, action, parameters);
let addToBottom = view.onAddView();
this.addView(view, addToBottom);
if (Navigator.log) console.log(name + ' will enter.');
this.dispatchEventWith(Navigator.VIEW_WILL_ENTER, false, {name, last, action, parameters});
await view.onWillEnter(last, action, parameters);
if (Navigator.log) console.log(name + ' did enter.');
this.dispatchEventWith(Navigator.VIEW_DID_ENTER, false, {name, last, action, parameters});
view.onDidEnter(last, action, parameters);
}
/**
* 栈出实现
* @param name
* @param next
* @param action
* @param parameters
* @returns {Promise<void>}
*/
async onLeave(name: string, next: string, action: NavigatorAction, parameters: any) {
let view: INavigatorViewBase = this.getViewInstanceByName(name);
await view.onWillUnMount(name, action, parameters);
if (Navigator.log) console.log(name + ' will leave.');
this.dispatchEventWith(Navigator.VIEW_WILL_LEAVE, false, {name, next, action, parameters});
await view.onWillLeave(next, action, parameters);
if (Navigator.log) console.log(name + ' did leave.');
this.dispatchEventWith(Navigator.VIEW_DID_LEAVE, false, {name, next, action, parameters});
view.onDidLeave(next, action, parameters);
}
/**
* 当收到错误实现
* @param error
*/
onError(error: Error) {
}
}
/**
* Created by rocky.l on 2017/1/17.
*
* 堆栈导航器
*/
export enum NavigatorAction {Push, Pop, Replace, Jump}
export interface INavigatorDelegate {
onEnter(name: string, last: string, action: NavigatorAction, parameters: any);
onLeave(name: string, next: string, action: NavigatorAction, parameters: any);
onError(error: Error);
}
export class StackNavigator {
private _stack: string[];
private _delegate: INavigatorDelegate;
constructor(delegate: INavigatorDelegate) {
this._stack = [];
this._delegate = delegate;
}
private catchPromise(p: Promise<any>) {
if (p) {
p.catch((e => {
this._delegate.onError(e);
}))
}
}
push(name: string, parameters: any = null) {
let last: string = this.getTopSceneName();
if (last) {
if (last == name) {
return;
}
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Push, parameters));
}
this._stack.push(name);
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Push, parameters));
}
popTo(index, name?: string, parameters: any = null) {
if (this._stack.length > 0 && this._stack.length < (index + 1)) {
return;
}
let last: string = this.getTopSceneName();
this._stack.splice(Math.max(index + 1, 0));
let next: string = this._stack[index];
if (!next) {
this._stack.push(next = name);
}
if (last) {
this.catchPromise(this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters));
}
this.catchPromise(this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters));
}
pop(parameters: any = null) {
this.popTo(this._stack.length - 2, null, parameters);
}
popAll(name: string, parameters: any = null) {
this.popTo(-1, name, parameters);
}
replace(name: string, parameters: any = null) {
let last: string = this._stack.pop();
this._stack.push(name);
this.catchPromise(this._delegate.onLeave(last, name, NavigatorAction.Replace, parameters));
this.catchPromise(this._delegate.onEnter(name, last, NavigatorAction.Replace, parameters));
}
jump(name: string, parameters: any = null) {
if (this._stack.length < 2) {
this.push(name, parameters);
return;
}
let last: string = this._stack.pop();
this._stack.splice(1);
let next: string = name;
this._stack.push(next);
this._delegate.onLeave(last, next, NavigatorAction.Pop, parameters);
this._delegate.onEnter(next, last, NavigatorAction.Pop, parameters);
}
private getTopSceneName(): string {
return this._stack.length > 0 ? this._stack[this._stack.length - 1] : null;
}
private getBottomSceneName(): string {
return this._stack.length > 0 ? this._stack[0] : null;
}
}
/**
* Created by rockyl on 2018/9/12.
*/
import {Navigator} from './Navigator'
import {StackNavigator} from './StackNavigator'
export {
Navigator,
StackNavigator,
}
\ No newline at end of file
/**
* Created by rockyl on 16/3/9.
*/
import {StageProxy} from "../support";
import {IDialogEffect, None} from "./PopupEffect";
import {combineProp} from "../tools/Utils";
import {enumChildren} from "../tools/EgretUtils";
const defaultModalConfig: any = {
color: 0,
alpha: 0.7,
duration: 200,
};
const POPUP_SHOW: string = 'POPUP_SHOW';
const POPUP_HIDE: string = 'POPUP_HIDE';
let _modalMask: eui.Rect;
let _pupUpStack: Array<any> = [];
let _popLayer: eui.Group;
let _modalConfig: any;
export function init(popLayer: eui.Group) {
_popLayer = popLayer;
_popLayer.width = StageProxy.getWidth();
_popLayer.height = StageProxy.getHeight();
StageProxy.getStage().addEventListener(egret.Event.RESIZE, onStageResize, this);
}
function onStageResize(event: egret.Event = null): void {
if (_modalMask) {
_modalMask.width = StageProxy.getWidth();
_modalMask.height = StageProxy.getHeight();
}
}
export function addPopUp(target: eui.Component, effectClazz: any = null, effectParams: any = null, modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null): void {
if (target.parent) {
return;
}
let dispatchPopUpShow = _pupUpStack.length == 0;
let top = getTopPupUp();
if (top && top['inactive']) {
top['inactive']();
}
_modalConfig = combineProp(defaultModalConfig, modalConfig);
_pupUpStack.unshift({target: target, modalTouchFun: modalTouchFun, modal: modal});
updateModalMask(_pupUpStack[0]);
let effect: IDialogEffect = createEffectInstance(effectClazz);
effect.show(target, _popLayer, function (): void {
if (target['active']) {
target['active']();
}
}, this, effectParams);
if (dispatchPopUpShow) {
//dispatchEventWith(PopUpManager.POPUP_SHOW);
}
}
export function removePopUp(target: eui.Component, effectClazz: any = null, effectParams: any = null): void {
if (!target.parent) {
return;
}
if (!getInStack(target, true)) {
return;
}
let aimItem: any;
_pupUpStack.some(function (item: any): boolean {
if (item.modal) {
aimItem = item;
return true;
}
});
if (aimItem) {
updateModalMask(aimItem);
} else {
setModalMaskVisible(false);
}
let effect: IDialogEffect = createEffectInstance(effectClazz);
effect.hide(target, _popLayer, function (): void {
if (target['inactive']) {
target['inactive']();
}
let top = getTopPupUp();
if (top && top['active']) {
top['active']();
}
}, this, effectParams);
let dispatchPopUpHide = _pupUpStack.length == 0;
if (dispatchPopUpHide) {
//dispatchEventWith(PopUpManager.POPUP_HIDE);
}
}
function getTopPupUp() {
if (_pupUpStack.length > 0) {
return _pupUpStack[_pupUpStack.length - 1];
} else {
return null;
}
}
export function removeTopPupUp(): boolean {
let top = getTopPupUp();
if (top) {
if (top['close']) {
top['close']();
}
return true;
}
return false;
}
export function removeAllPupUp(): void {
enumChildren(_popLayer, (popup: any) => {
if (popup != _modalMask) {
popup['close']();
}
});
}
function getInStack(target: egret.DisplayObjectContainer, del: boolean = false): any {
let data: any;
_pupUpStack.some(function (item: any, index: number): boolean {
if (item.target == target) {
data = {item: item, index: index};
return true;
}
});
if (data && del) {
_pupUpStack.splice(data.index, 1);
}
return data;
}
function createEffectInstance(effectClazz: any = null): IDialogEffect {
let effect: IDialogEffect;
if (effectClazz) {
effect = new effectClazz();
} else {
effect = new None();
}
return effect;
}
function onModalMaskTap(event: egret.TouchEvent): void {
let item: any = _pupUpStack[0];
if (item && item.modal && item.modalTouchFun) {
item.modalTouchFun();
}
}
function updateModalMask(item: any): void {
let maskIndex: number = _popLayer.getChildIndex(_modalMask);
let index: number = _popLayer.getChildIndex(item.target);
if (maskIndex != index - 1) {
setModalMaskVisible(item.modal, index);
}
}
function setModalMaskVisible(visible: boolean, index: number = -1): void {
const modalMask = getModalMask();
if (visible) {
modalMask.fillColor = _modalConfig.color;
modalMask.fillAlpha = _modalConfig.alpha;
if (index >= 0) {
setModalMaskVisible(true);
_popLayer.addChildAt(modalMask, index);
} else {
_popLayer.addChild(modalMask);
}
egret.Tween.get(modalMask, null, null, true).to({alpha: 1}, _modalConfig.duration);
} else {
if (modalMask.parent) {
egret.Tween.get(modalMask, null, null, true).to({alpha: 0}, _modalConfig.duration).call(function (modalMask: eui.Rect): void {
_popLayer.removeChild(modalMask);
}, this, [modalMask]);
}
}
}
function getModalMask(): eui.Rect {
if (!_modalMask) {
_modalMask = new eui.Rect();
_modalMask.width = StageProxy.getWidth();
_modalMask.height = StageProxy.getHeight();
_modalMask.addEventListener(egret.TouchEvent.TOUCH_TAP, onModalMaskTap, this);
}
return _modalMask;
}
/**
* Created by rockyl on 16/3/9.
*/
import {None} from "./PopupEffect";
import {addPopUp, removePopUp} from "./PopUpManager";
import {checkNeedLoad, loadResGroups} from "../tools/ResGroupsLoader";
import {EventComponent} from "../support/EventComponent";
export class PopupBase extends EventComponent {
protected showEffect: any;
protected showEffectParams: any;
protected closeEffect: any;
protected closeEffectParams: any;
protected popupShowBanner: boolean;
protected _callback: Function;
protected _excludeActionsClose: string[] = [];
constructor(showEffect: any = null, showEffectParams: any = null, closeEffect: any = null, closeEffectParams: any = null, popupShowBanner: boolean = false) {
super();
this.showEffect = showEffect || None;
this.showEffectParams = showEffectParams;
this.closeEffect = closeEffect || None;
this.closeEffectParams = closeEffectParams;
this.popupShowBanner = popupShowBanner;
this._excludeActionsClose = [];
this.init();
}
protected init(): void {
}
protected getResGroupNames(): string[] {
return null;
}
protected onBeginLoadResGroups() {
}
protected onEndLoadResGroups() {
}
protected getSkinName(): any {
return null;
}
/**
* 添加不用关闭的动作
* @param actions
*/
addExcludeForClose(actions: string[]): void {
this._excludeActionsClose = this._excludeActionsClose.concat(actions);
}
dealAction = (action: string = null, data: any = null) => {
if (this._callback) {
this._callback(action || 'close', data);
}
if (this._excludeActionsClose.indexOf(action) < 0) {
this.close();
this._callback = null;
}
};
async popup(modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null) {
let resGroupNames = this.getResGroupNames();
if (resGroupNames && resGroupNames.length > 0 && checkNeedLoad(resGroupNames)) {
this.onBeginLoadResGroups();
await loadResGroups(resGroupNames);
this.onEndLoadResGroups();
} else {
this.onEndLoadResGroups();
}
if (!this.skinName) {
let skinName = this.getSkinName();
if (skinName) {
this.skinName = skinName;
}
}
this._popup(modalTouchFun, modal, modalConfig);
}
private _popup(modalTouchFun: Function = null, modal: boolean = true, modalConfig: any = null) {
addPopUp(this, this.showEffect, this.showEffectParams, modalTouchFun, modal, modalConfig);
}
close(): void {
removePopUp(this, this.closeEffect, this.closeEffectParams);
}
active() {
this.enableEvents();
}
inactive() {
this.disableEvents();
}
}
/**
* Created by rockyl on 16/3/9.
*/
/*
* Blind 刷出来
* Bounce 跳动
* Clip 横向收缩
* Scale 纵向收缩
* Drop 单向收缩+fade
* Slide 单向收缩
* Explode 八方向爆炸
* Fade 渐进
* Fold 抽屉收缩
* Puff 放大+Fade
* Pulsate 闪烁
* Shake 抖动
* */
import {StageProxy} from "../support";
export class Utils {
static centerPopUp(popUp: eui.Component): void {
popUp.horizontalCenter = popUp.verticalCenter = 0;
}
static centerHorizontal(popUp: eui.Component): void {
popUp.horizontalCenter = 0;
}
static centerVertical(popUp: eui.Component): void {
popUp.verticalCenter = 0;
}
static notCenterPopUp(popUp: eui.Component): void {
popUp.horizontalCenter = popUp.verticalCenter = NaN;
}
static getCenterPos(popUp: eui.Component): any {
let x: number = 0;
let y: number = 0;
let parent: egret.DisplayObjectContainer = popUp.parent;
if (parent) {
x = (parent.width - popUp.width) * 0.5;
y = (parent.height - popUp.height) * 0.5;
}
return {x: x, y: y};
}
static transDirection(dStr: string): number {
let d: number;
switch (dStr) {
case "up":
d = 0;
break;
case "right":
d = 1;
break;
case "bottom":
d = 2;
break;
case "left":
d = 3;
break;
}
return d;
}
}
export interface IDialogEffect {
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void;
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void;
}
export class None implements IDialogEffect {
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
target.scaleX = target.scaleY = target.alpha = 1;
parent.addChild(target);
Utils.centerPopUp(target);
callback.call(thisObj);
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
parent.removeChild(target);
callback.call(thisObj);
}
}
/***
* 渐进渐出
*/
export class Fade implements IDialogEffect {
static DEFAULT_DURATION: number = 200;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
target.alpha = 0;
parent.addChild(target);
Utils.centerPopUp(target);
let duration: number = (params && params.duration) || Fade.DEFAULT_DURATION;
egret.Tween.get(target).to({alpha: 1}, duration).call(callback, thisObj);
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Fade.DEFAULT_DURATION;
egret.Tween.get(target).to({alpha: 0}, duration).call(function (): void {
parent.removeChild(target);
callback.call(thisObj);
}, this);
}
}
/**
* 飞入
* duration: 时间
* direction: 方向(up, bottom, left, right)
* withFade: 是否伴随渐进渐出
* startPos:
* endPos:
*/
export class Flew implements IDialogEffect {
static DEFAULT_DURATION: number = 300;
static outPos: Array<any>;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
if (!Flew.outPos) {
Flew.outPos = [
{x: 0, y: -StageProxy.getHeight()},
{x: StageProxy.getWidth(), y: 0},
{x: 0, y: StageProxy.getHeight()},
{x: -StageProxy.getWidth(), y: 0}
];
}
parent.addChild(target);
Utils.notCenterPopUp(target);
let startPos: any = params.startPos || Flew.outPos[Utils.transDirection(params.direction)];
let endPos: any = params.endPos || Utils.getCenterPos(target);
target.x = startPos.x || endPos.x;
target.y = startPos.y || endPos.y;
let duration: number = (params && params.duration) || Flew.DEFAULT_DURATION;
let state: any = {x: endPos.x, y: endPos.y};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(callback, thisObj);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 1}, duration);
}
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let defaultPos: any = Flew.outPos[Utils.transDirection(params.direction)];
let endPos: any = params.endPos || Utils.getCenterPos(target);
let duration: number = (params && params.duration) || Flew.DEFAULT_DURATION;
let state: any = {x: defaultPos.x || endPos.x, y: defaultPos.y || endPos.y};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(function (): void {
parent.removeChild(target);
Utils.centerPopUp(target);
callback.call(thisObj);
}, this);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 0}, duration);
}
}
}
/***
* 缩放
* duration: 时间
* withFade: 是否伴随渐进渐出
*/
export class Scale implements IDialogEffect {
static DEFAULT_DURATION: number = 200;
show(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Scale.DEFAULT_DURATION;
target.scaleX = target.scaleY = 0;
let state: any = {scaleX: 1, scaleY: 1};
parent.addChild(target);
Utils.centerPopUp(target);
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(callback, thisObj);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 1}, duration);
}
}
hide(target: eui.Component, parent: eui.Group, callback: Function, thisObj: any, params: any): void {
let duration: number = (params && params.duration) || Scale.DEFAULT_DURATION;
target.scaleX = target.scaleY = 1;
let state: any = {scaleX: 0, scaleY: 0};
egret.Tween.get(target).to(state, duration, params ? params.ease : null).call(function (): void {
parent.removeChild(target);
target.scaleX = target.scaleY = 1;
callback.call(thisObj);
}, this);
if (params && params.withFade) {
egret.Tween.get(target).to({alpha: 0}, duration);
}
}
}
/**
* Created by rockyl on 2018/9/12.
*/
import * as PopupEffect from './PopupEffect'
import * as PopUpManager from './PopUpManager'
export {
PopupEffect,
PopUpManager,
}
/**
* Created by lenovo on 2014/7/23.
*/
export class Dispatcher {
static eventDispatcher: egret.EventDispatcher;
static init(): void {
Dispatcher.eventDispatcher = new egret.EventDispatcher();
}
static dispatch(eventName: string, params: any = null): void {
if (params) {
Dispatcher.eventDispatcher.dispatchEventWith(eventName, false, params);
} else {
Dispatcher.eventDispatcher.dispatchEvent(new egret.Event(eventName));
}
}
static addEventListener(eventName: string, callback: Function, thisObj: any): void {
Dispatcher.eventDispatcher.addEventListener(eventName, callback, thisObj);
}
static removeEventListener(eventName: string, callback: Function, thisObj: any): void {
Dispatcher.eventDispatcher.removeEventListener(eventName, callback, thisObj);
}
}
/**
* Created by admin on 2017/6/23.
*/
import {eventManager} from "./";
export class EventComponent extends eui.Component {
private get eventGroupName() {
return this['__class__'] + '_' + this.hashCode;
}
registerEvent(target: any, eventName: any, callback: Function, thisObj: any, priority: number = 0): void {
eventManager.register(this.eventGroupName, target, eventName, callback, thisObj, priority);
}
enableEvents() {
eventManager.enable(this.eventGroupName);
}
disableEvents() {
eventManager.disable(this.eventGroupName);
}
}
export class VisualEventComponent extends EventComponent {
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.enableEvents();
}
protected onRemovedFromStage(event: egret.Event): void {
this.disableEvents();
}
}
export class VisualEventItemRenderer extends eui.ItemRenderer {
private get eventGroupName() {
return this['__class__'] + '_' + this.hashCode;
}
registerEvent(target: any, eventName: any, callback: Function, thisObj: any, priority: number = 0): void {
eventManager.register(this.eventGroupName, target, eventName, callback, thisObj, priority);
}
enableEvents() {
eventManager.enable(this.eventGroupName);
}
disableEvents() {
eventManager.disable(this.eventGroupName);
}
constructor() {
super();
this.addEventListener(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
this.addEventListener(egret.Event.REMOVED_FROM_STAGE, this.onRemovedFromStage, this);
}
protected onAddedToStage(event: egret.Event): void {
this.enableEvents();
}
protected onRemovedFromStage(event: egret.Event): void {
this.disableEvents();
}
}
/**
* Created by rockyl on 16/5/19.
*
* 事件管理器
*/
import {injectProp} from "../tools/Utils";
class EventManager {
private _groups: any = {};
register(groupName: string, target: any, eventName, callback: Function, thisObj: any, priority: number = 0): void {
if (!target) {
console.error('target is empty');
}
let item: RegisterItem = new RegisterItem();
injectProp(item, {target, eventName, callback, thisObj, priority}, null, false);
let group: any = this._groups[groupName];
if (!group) {
group = this._groups[groupName] = {enable: false, items: []};
}
group.items.push(item);
if (group.enable) { //如果组已生效,添加进去的就立马生效
this.addEventListener(item);
}
}
registerOn(obj: any, target: any, eventName, callback: Function, thisObj: any, priority: number = 0): void {
this.register(obj['__class__'], target, eventName, callback, thisObj, priority);
}
enable(groupName: string): void {
let group: any = this._groups[groupName];
if (!group) {
group = this._groups[groupName] = {enable: false, items: []};
}
if (!group.enable) {
group.enable = true;
group.items.forEach(this.addEventListener);
}
}
private addEventListener(item: RegisterItem) {
item.target['addEventListener'](item.eventName, item.callback, item.thisObj, false, item.priority);
}
enableOn(obj: any): void {
this.enable(obj['__class__']);
}
disable(groupName: string): void {
let group: any = this._groups[groupName];
if (group && group.enable) {
group.enable = false;
group.items.forEach(this.removeEventListener);
}
}
private removeEventListener(item: RegisterItem) {
item.target['removeEventListener'](item.eventName, item.callback, item.thisObj);
}
disableOn(obj: any): void {
this.disable(obj['__class__']);
}
dump(groupName: string = null): void {
for (let key in this._groups) {
let group: any = this._groups[key];
console.log(key + '[' + group.items.length + ']: ' + (group.enable ? '● enable' : '○ disable'));
console.log(group.items.map((item: RegisterItem) => {
return item.eventName;
}).join(','));
}
}
}
class RegisterItem {
target: any;
eventName: string;
callback: Function;
thisObj: any;
priority: number;
}
const eventManager:EventManager = new EventManager();
export default eventManager;
/**
* Created by Rocky.L on 2015/4/22.
*/
let _ID: string;
export function init(ID: string): void {
_ID = ID;
}
export function getName(key: string, prefix: string = null): string {
return (prefix || !_ID || _ID == '' ? prefix : _ID) + '_' + key;
}
export function getItem(key: string, prefix: string = null): string {
return egret.localStorage.getItem(getName(key, prefix));
}
export function setItem(key: string, value: string, prefix: string = null): boolean {
egret.localStorage.setItem(getName(key, prefix), value);
return true;
}
export function getItemObj(key: string, defaultObj: any = null, prefix: string = null): any {
let result: any;
try {
result = JSON.parse(getItem(key, prefix));
} catch (e) {
}
if (!result) {
result = defaultObj;
}
return result;
}
export function setItemObj(key: string, itemObj: any, prefix: string = null): boolean {
return setItem(key, JSON.stringify(itemObj), prefix);
}
/**
* Created by rockyl on 16/3/9.
*/
import {getTweenPromise} from "../tools/EgretUtils";
import {getItem, setItem} from "./LocalStorage";
let conflictPercent = 0.5;
let musicRes: string;
let musicChannel: egret.SoundChannel;
let musicPlaying: boolean;
let musicVolume: number;
export function setMusic(res: string) {
musicRes = res;
}
export function playMusic(res: string = null, {goon = false, volume = 1} = {}): void {
if (musicRes == res && !getMusicMute()) {
return;
}
let vol = goon ? musicVolume || 1 : volume;
if (!goon) {
musicRes = res;
}
if (getMusicMute()) {
return;
}
musicPlaying = true;
/*if (musicChannel) {
musicChannel.stop();
}*/
if (RES.getRes(musicRes)) {
_playMusic(RES.getRes(musicRes), vol);
} else {
RES.getResAsync(musicRes, (music: egret.Sound) => {
_playMusic(music, vol);
}, this);
}
}
async function _playMusic(music: egret.Sound, volume) {
musicVolume = volume;
if (music) {
if (musicChannel) {
await _channelFade(musicChannel, 0);
}
musicChannel = music.play();
musicChannel.volume = 0;
await _channelFade(musicChannel, volume, 2000);
}
}
async function _channelFade(channel: egret.SoundChannel, volume, duration = 500) {
if (duration == 0) {
if (volume == 0) {
egret.Tween.removeTweens(channel);
channel.stop();
}
} else {
await getTweenPromise(
egret.Tween
.get(channel, null, null, true)
.to({volume}, duration)
);
}
}
export function stopMusic(mute: boolean = false): void {
musicPlaying = false;
if (!mute) {
musicRes = null;
}
if (musicChannel) {
_channelFade(musicChannel, 0, 0);
musicChannel = null;
}
}
export function switchMusic(): void {
if (musicRes) {
if (getMusicMute()) {
stopMusic(true)
} else {
if (!musicPlaying) {
playMusic(null, {goon: true, volume: musicVolume});
}
}
}
}
export function getMusicMute(): boolean {
return false;
//return !dataCenterService.getSettingItem('music');
}
export function setMusicMute(value: boolean) {
//dataCenterService.setSettingItem('music', !value);
}
let effectRes: string;
let effectChannelMap: any = {};
export function playEffect(res: string = null, {loop = 1, conflict = false, force = false} = {}) {
if (res) {
effectRes = res;
}
if (!force && getEffectMute()) {
return Promise.resolve();
//return Promise.reject('effect mute');
}
let callback;
let p = new Promise((resolve => {
callback = resolve;
}));
if (RES.getRes(res)) {
_playEffect(res, RES.getRes(res), loop, conflict, callback);
} else {
RES.getResAsync(res, (music: egret.Sound) => {
_playEffect(res, music, loop, conflict, callback);
}, this);
}
return p;
}
function _playEffect(res, effect, loop, conflict, callback) {
if (effect) {
//console.log('playEffect', res);
effect.type = egret.Sound.EFFECT;
let effectChannel = effect.play(0, loop);
effectChannelMap[res] = effectChannel;
effectChannel.once(egret.Event.SOUND_COMPLETE, (event) => {
onEffectComplete({res, conflict});
callback();
}, this);
} else {
//reject('can\'t loaded ' + res);
callback();
}
}
export function stopEffect(res, {fade = false} = {}) {
let channel = effectChannelMap[res];
if (channel) {
if (fade) {
return new Promise(resolve => {
egret.Tween
.get(channel, null, null, true)
.to({volume: 0.1}, 300)
.call(() => {
_stopEffect(res);
resolve();
});
});
} else {
_stopEffect(res);
return Promise.resolve();
}
} else {
return Promise.resolve();
//return Promise.reject(`${res} is not on channel`)
}
}
function _stopEffect(res) {
let channel = effectChannelMap[res];
if (channel) {
channel.stop();
}
delete effectChannelMap[res];
}
function onEffectComplete({res, conflict}): void {
if (conflict && musicChannel && !getMusicMute()) {
egret.Tween
.get(musicChannel, null, null, true)
.to({volume: musicVolume}, 200);
//musicChannel.volume = 1;
}
delete effectChannelMap[res];
}
export function switchEffect(): void {
if (getEffectMute()) {
for (let res in effectChannelMap) {
let channel = effectChannelMap[res];
channel.stop();
}
}
}
export function getEffectMute(): boolean {
return false
//return !dataCenterService.getSettingItem('effect');
}
export function setEffectMute(value: boolean) {
//dataCenterService.setSettingItem('effect', !value);
}
export function getAllMute(): boolean {
return getMusicMute();
}
export function switchAll(): void {
switchEffect();
switchMusic();
}
/**
* 震动
*/
export function vibrate(): void {
if (getVibrateMute()) {
return;
}
//Native.instance.vibrate();
}
export function getVibrateMute(): boolean {
let mm: string = getItem('vibrateMute');
return mm ? mm == '1' : false;
}
export function setVibrateMute(value: boolean) {
setItem('vibrateMute', value ? '1' : '0');
}
export function switchVibrate(): void {
setVibrateMute(!getVibrateMute());
}
/**
* Created by rockyl on 16/3/9.
*/
let _stage: egret.Stage;
let _root: egret.DisplayObjectContainer;
let lastTouchPos: any = {};
let autoAdjustTargets: egret.DisplayObject[];
export function init(stage: egret.Stage, root: egret.DisplayObjectContainer): void {
_stage = stage;
_root = root;
stage.addEventListener(egret.TouchEvent.TOUCH_END, function (event: egret.TouchEvent): void {
lastTouchPos.x = event.stageX;
lastTouchPos.y = event.stageY;
}, this);
autoAdjustTargets = [];
stage.addEventListener(egret.Event.RESIZE, onStageResize, this);
}
function onStageResize(event: egret.Event = null): void {
const {width, height} = getSize();
//console.log(`resize stage: (${width}, ${height})`);
autoAdjustTargets.forEach((child: egret.DisplayObject) => {
child.width = width;
child.height = height;
});
}
export function getStage() {
return _stage;
}
export function getWidth(): number {
return _stage.stageWidth;
}
export function getHeight(): number {
return _stage.stageHeight;
}
export function getSize(): any {
return {
width: getWidth(),
height: getHeight(),
};
}
export function getCenter(): any {
const {width, height} = getSize();
return {
x: width / 2,
y: height / 2
}
}
export function registerAutoAdjust(target: egret.DisplayObject): void {
let index = autoAdjustTargets.indexOf(target);
if (index < 0) {
autoAdjustTargets.push(target);
}
onStageResize();
}
export function unregisterAutoAdjust(target: egret.DisplayObject): void {
let index = autoAdjustTargets.indexOf(target);
if (index >= 0) {
autoAdjustTargets.splice(index, 1);
}
}
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment