Commit f0572854 authored by rockyl's avatar rockyl

upload cures

parents
Pipeline #72761 failed with stages
in 0 seconds
# Created by .ignore support plugin (hsz.mobi)
design/origin/
node_modules
libs/
bin-debug/
bin-release/
design/sheetModifyTime.json
.wing/
!/src/game/
!/design/images/fonts/
!/resource/assets/effects/
!/resource/assets/fonts/
!/resource/assets/sheets/
!/resource/assets/singles/
\ No newline at end of file
# Game Template for Egret
\ No newline at end of file
{
"engineVersion": "5.2.10",
"compilerVersion": "5.2.10",
"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"
}
],
"version": {
"main": "1.0.0",
"build": 588
}
}
\ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<module type="WEB_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>{projectName}</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"
],
"game": [
"bin-debug/bundle.js"
]
}
\ No newline at end of file
{
"name": "game-template-egret",
"version": "1.0.0",
"description": "",
"main": "template-config.js",
"dependencies": {
},
"devDependencies": {},
"scripts": {
"postinstall": "cd scripts && npm i"
},
"repository": {
"type": "git",
"url": "git@gitlab2.dui88.com:laoqifeng/game-template-egret.git"
},
"author": "",
"license": "ISC"
}
{
"build-process": "egret",
"remote-path": "activity/{projectName}"
}
\ 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}",
"no_more_items":"没有炮弹了",
"need_install_app":"请先安装游戏",
"share_result": {
"success": "分享成功",
"fail": "分享失败",
"cancel": "分享被取消"
}
}
{
"settings": {
"services": [
"storage",
"main",
"defense",
"buriedPoint",
"badge"
],
"componentSuperClasses": [
"CuresComponent",
"MyComponent"
],
"serviceSuperClasses": [
"Service"
]
},
"bindings": [
{
"name": "scene_menu",
"skin": "scene.SceneMenuSkin",
"resGroups": [],
"bindings": [
{
"target": "this",
"components": [
{
"script": "components/SceneMenu",
"enabled": true,
"injection": {
"type": "1"
}
}
]
},
{
"target": "badgeChance",
"components": [
{
"script": "components/Badge",
"enabled": true,
"injection": {
"name": "chance"
}
}
]
},
{
"target": "btnStart",
"components": [
{
"script": "components/ButtonStart",
"enabled": true,
"injection": {
"type": {
"ddd": {
"aaa": "bbb"
},
"sdf": "sdf"
}
}
},
{
"script": "components/BuriedPointButton",
"enabled": true,
"injection": {
"dpm": "app_id.202.7.1",
"dcm": "213.oaid.0.0"
}
},
{
"script": "components/Breath",
"injection": {
"duration": 3000,
"scaleOffset": 0.1
},
"enabled": true
}
]
},
{
"target": "btnRule",
"components": [
{
"script": "components/ButtonRule",
"injection": {
"type": 2
},
"enabled": true
},
{
"script": "components/BuriedPointButton",
"injection": {
"dpm": "app_id.202.7.2",
"dcm": "213.oaid.0.0"
},
"enabled": true
}
]
}
],
"deleteConfirmPop": false
},
{
"name": "scene_play",
"skin": "scene.ScenePlaySkin",
"resGroups": [],
"bindings": [
{
"target": "this",
"components": [
{
"script": "components/ScenePlay",
"injection": {}
}
]
},
{
"target": "btnBack",
"components": [
{
"script": "components/ButtonBack",
"enabled": true
}
]
},
{
"target": "gameView.labelInGameView",
"components": [
{
"script": "components/GameViewLabel",
"enabled": true,
"injection": {}
}
]
}
],
"deleteConfirmPop": false
},
{
"name": "panel_rule",
"skin": "panel.PanelRuleSkin",
"resGroups": [],
"bindings": [
{
"target": "this",
"components": [
{
"script": "components/PanelRule",
"injection": {
"content": "一个弹窗哟!\\n换行",
"button": "确定"
},
"enabled": true
}
]
}
],
"deleteConfirmPop": false
}
]
}
\ No newline at end of file
{
"groups": [
{
"keys": "",
"name": "panels"
},
{
"keys": "lang,project-config",
"name": "common"
},
{
"keys": "",
"name": "play"
},
{
"keys": "",
"name": "mission"
},
{
"keys": "",
"name": "draw_reward"
}
],
"resources": [
{
"url": "configs/lang.json",
"type": "json",
"name": "lang"
},
{
"url": "configs/project.json",
"type": "json",
"name": "project-config"
}
]
}
\ No newline at end of file
{
"skins": {},
"autoGenerateExmlsList": true,
"exmls": [
"resource/skins/components/BadgeSkin.exml",
"resource/skins/components/GameViewSkin.exml",
"resource/skins/components/ToastSkin.exml",
"resource/skins/ui/ProgressSkin.exml",
"resource/skins/LoadingViewSkin.exml",
"resource/skins/MainStageSkin.exml",
"resource/skins/ui/ButtonSkin.exml",
"resource/skins/panels/PanelAlertSkin.exml",
"resource/skins/panels/PanelRuleSkin.exml",
"resource/skins/scenes/SceneFinalRewardSkin.exml",
"resource/skins/scenes/SceneMenuSkin.exml",
"resource/skins/scenes/ScenePlaySkin.exml",
"resource/skins/ui/IconButtonSkin.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 x="245" includeIn="loading" bottom="607">
<e:ProgressBar id="progressBar" skinName="ui.ProgressSkin" width="270"/>
<e:Label text="loading..." y="-40" horizontalCenter="0"/>
</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.BadgeSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Rect ellipseWidth="30" ellipseHeight="30" fillColor="0xff0000" height="30" width="100%" strokeColor="0xffffff" strokeWeight="2"/>
<e:Label id="lab" text="0" left="8" right="8" size="24" verticalCenter="0"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="component.GameViewSkin" width="400" height="300" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Label id="labelInGameView" text="GameView" x="126.5" y="135"/>
</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" width="500" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Rect width="100%" height="100%" fillColor="0xeaeaea" ellipseWidth="20" ellipseHeight="20"/>
<e:Label id="labContent" text="Label" textColor="0x333333" left="50" right="50" top="100" bottom="170" textAlign="center"/>
<e:Button id="btnConfirm" label="Button" y="217" skinName="ui.ButtonSkin" horizontalCenter="0"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="panel.PanelRuleSkin" width="500" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing">
<e:Rect width="100%" height="100%" fillColor="0xeaeaea" ellipseWidth="20" ellipseHeight="20"/>
<e:Label id="labContent" text="Label" textColor="0x333333" left="50" right="50" top="100" bottom="170" textAlign="center" lineSpacing="5"/>
<e:Button id="btnConfirm" label="Button" y="217" skinName="ui.ButtonSkin" horizontalCenter="0"/>
</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="1334" 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="{grpStart}">
<tween:To duration="250">
<tween:props>
<e:Object bottom="{140}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{btnRule}">
<tween:To duration="250">
<tween:props>
<e:Object y="{30}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
<tween:TweenGroup id="leave">
<tween:TweenItem target="{grpStart}">
<tween:To duration="200">
<tween:props>
<e:Object bottom="{-124}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
<tween:TweenItem target="{btnRule}">
<tween:To duration="200">
<tween:props>
<e:Object y="{-60}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
</w:Declarations>
<e:Group id="grpStart" bottom="-124" horizontalCenter="0" width="270" height="124">
<e:Button id="btnStart" label="Start" skinName="ui.ButtonSkin" width="270" height="124"/>
</e:Group>
<e:Button id="btnRule" label="Rule" skinName="ui.ButtonSkin" x="618" y="-60"/>
<e:Label id="lab" text="Label" y="362.42" x="338"/>
<e:Label text="SceneMenu" verticalCenter="0" horizontalCenter="0"/>
<e:Component id="badgeChance" x="119" y="593" skinName="component.BadgeSkin"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="scene.ScenePlaySkin" width="750" height="1334" 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="{btnBack}">
<tween:To duration="250" ease="cubicOut">
<tween:props>
<e:Object x="{30}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
<tween:TweenGroup id="leave">
<tween:TweenItem target="{btnBack}">
<tween:To duration="250" ease="cubicIn">
<tween:props>
<e:Object x="{-107}"/>
</tween:props>
</tween:To>
</tween:TweenItem>
</tween:TweenGroup>
</w:Declarations>
<!--ns1:GameView id="gameView" skinName="component.GameViewSkin" horizontalCenter="0" bottom="208" locked="true"/-->
<e:Button id="btnBack" label="Back" y="30" skinName="ui.ButtonSkin" x="-107"/>
<e:Label text="ScenePlay" horizontalCenter="0" verticalCenter="0"/>
<e:Component id="gameView" x="175" y="60" skinName="component.GameViewSkin"/>
</e:Skin>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="ui.ButtonSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" states="up,down,disabled" >
<e:Rect width="100%" height="100%" fillColor="0x007cb2" ellipseWidth="20" ellipseHeight="20" fillColor.down="0x21afed" fillColor.disabled="0xa7adaf"/>
<e:Label id="labelDisplay" text="Label" left="20" right="20" top="15" bottom="15" textAlign="center" verticalAlign="middle"/>
</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
<?xml version="1.0" encoding="utf-8"?>
<e:Skin class="ui.ProgressSkin" xmlns:e="http://ns.egret.com/eui" xmlns:w="http://ns.egret.com/wing" width="100" height="25">
<e:Rect id="track" width="100%" height="100%" ellipseWidth="20" ellipseHeight="20" fillAlpha="0" strokeWeight="2" strokeColor="0x007cb2"/>
<e:Rect id="thumb" width="100%" height="100%" fillColor="0x007cb2" ellipseWidth="20" ellipseHeight="20"/>
<e:Label id="labelDisplay" text="0/0" size="18" horizontalCenter="0" textColor="0xffffff" verticalCenter="0"/>
</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
/**
* 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 {
UglifyPlugin,
ExmlPlugin,
} from 'built-in';
import {ResultNotificationPlugin} from "./result-notification-plugin";
import {ConcatPlugin} from "./concat-plugin";
import {RollupCompilePlugin} from "./rollup-compile-plugin";
import {GenerateDependencePlugin} from "./generate-dependence-plugin";
const config: ResourceManagerConfig = {
buildConfig: (params) => {
const {target, command, projectName, version} = params;
if (command == 'build') {
const outputDir = '.';
return {
outputDir,
commands: [
new GenerateDependencePlugin(),
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 GenerateDependencePlugin(),
new RollupCompilePlugin({
publishPolicy: 'release',
libraryType: 'release',
defines: {DEBUG: false, RELEASE: true},
//generateSourceMap: 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",
],
target: "vendor.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;
import * as path from 'path'
import * as fs from 'fs'
const templateHeader = `/**
* THIS FILE WAS GENERATE BY COMPILER
* DO NOT MODIFY THIS FILE
*/
`;
export class GenerateDependencePlugin implements plugins.Command {
async onFile(file: plugins.File) {
return file;
}
async onFinish(commandContext: plugins.CommandContext) {
const projectConfig = require(path.resolve('resource/configs/project.json'));
let content = templateHeader;
for(let name of projectConfig.settings.services){
const serviceName = (name.charAt(0).toUpperCase() + name.substr(1)) + 'Service';
content += `import './services/${serviceName}'\n`;
}
content += '\n';
for (let scene:any of projectConfig.bindings) {
for (let binding of scene.bindings) {
for (let component of binding.components) {
const name = component.script;
content += `import './${name}'\n`;
}
}
}
fs.writeFileSync('src/MustCompile.ts', content);
}
[options: string]: any;
}
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-node-resolve": "^3.4.0",
"rollup-plugin-uglify": "^5.0.2",
"rollup-pluginutils": "^2.3.3",
"tippex": "^3.0.0",
"tslib": "^1.9.3",
"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('version:', 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 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, generateSourceMap} = this.options;
const debugMode = publishPolicy === 'debug';
let plugins = [
typescriptPlugin({
typescript,
}),
resolve(),
];
if (!debugMode) {
plugins.push(uglify());
}
let outputConfig: any = {
format: 'cjs',
};
if (debugMode || generateSourceMap) {
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);
}
}
}
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var path = require('path');
var fs = require('fs');
var ts = require('typescript');
var rollupPluginUtils = require('rollup-pluginutils');
var resolveId = _interopDefault(require('resolve'));
function endsWith ( str, tail ) {
return !tail.length || str.slice( -tail.length ) === tail;
}
function getDefaultOptions () {
return {
noEmitHelpers: true,
module: 'ESNext',
sourceMap: true,
importHelpers: 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 getConfigContent(path){
var content = fs.readFileSync( path, 'utf8' );
/*if(process.env.hasOwnProperty('GAME_LIB_PATH')){
content = content.replace('$GAME_LIB_PATH$', process.env.GAME_LIB_PATH)
}*/
return content;
}
function getCompilerOptionsFromTsConfig (typescript, tsconfigPath) {
if (tsconfigPath && !fs.existsSync(tsconfigPath)) {
throw new Error(("Could not find specified tsconfig.json at " + tsconfigPath));
}
var existingTsConfig = tsconfigPath || findFile( process.cwd(), 'tsconfig.json' );
if (!existingTsConfig) {
return {};
}
var tsconfig = typescript.readConfigFile( existingTsConfig, getConfigContent);
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 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;
}
}
};
var TSLIB_ID = '\0tslib';
function typescript ( options ) {
if ( options === void 0 ) options = {};
options = Object.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 and tslib version used for helpers.
var typescript = options.typescript || ts;
var tslib = options.tslib ||
fs.readFileSync(resolveId.sync('tslib/tslib.es6.js', { basedir: __dirname }), 'utf-8' );
delete options.typescript;
delete options.tslib;
// Load options from `tsconfig.json` unless explicitly asked not to.
var tsconfig = options.tsconfig === false ?
{} :
getCompilerOptionsFromTsConfig( 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 );
options = Object.assign( tsconfig, getDefaultOptions(), options );
// Verify that we're targeting ES2015 modules.
var moduleType = options.module.toUpperCase();
if ( moduleType !== 'ES2015' && moduleType !== 'ES6' && moduleType !== 'ESNEXT' && moduleType !== 'COMMONJS' ) {
throw new Error( ("rollup-plugin-typescript: The module kind should be 'ES2015' or 'ESNext, 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 {
name: 'typescript',
resolveId: function resolveId$$1 ( importee, importer ) {
if ( importee === 'tslib' ) {
return TSLIB_ID;
}
if ( !importer ) { return null; }
importer = importer.split('\\').join('/');
var 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 === TSLIB_ID ) {
return tslib;
}
},
transform: function transform ( code, id ) {
//if ( !filter( id ) ) { return null; }
var transformed = typescript.transpileModule( code, {
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 {
code: transformed.outputText,
// Rollup expects `map` to be an object so we must parse the string
map: transformed.sourceMapText ? JSON.parse(transformed.sourceMapText) : null
};
}
};
}
module.exports = typescript;
{
"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 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} from "@alienlib/support";
import {init as initStageProxy} from "@alienlib/support/StageProxy";
import {init as initLocalStorage} from "@alienlib/support/LocalStorage";
import './MustCompile'
class Main extends eui.UILayer {
constructor() {
super();
this.once(egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
}
private onAddedToStage() {
Dispatcher.init();
initStageProxy(this.stage, this);
initLocalStorage(GameConfig.gameName);
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("common", 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 {
let mainStage:MainStage = MainStage.instance;
this.addChildAt(mainStage, 0);
}
}
/**
* THIS FILE WAS GENERATE BY COMPILER
* DO NOT MODIFY THIS FILE
*/
import './services/StorageService'
import './services/MainService'
import './services/DefenseService'
import './services/BuriedPointService'
import './services/BadgeService'
import './components/SceneMenu'
import './components/Badge'
import './components/ButtonStart'
import './components/BuriedPointButton'
import './components/Breath'
import './components/ButtonRule'
import './components/BuriedPointButton'
import './components/ScenePlay'
import './components/ButtonBack'
import './components/GameViewLabel'
import './components/PanelRule'
/**
* Created by rockyl on 2018/8/21.
*/
import lang from "./lang";
import {gameInfo} from "./model/data-center";
import Toast from "./views/Toast";
export function showErrorAlert(e = null, callback?){
let text = !e || e instanceof Error ? lang.net_error : e;
/*Alert.show(text, function(){
if(callback){
callback();
}else{
location.reload();
}
})*/
}
export function catchError(p, callback?){
p.catch(e=>{
if(e instanceof Error){
console.log(e.message);
console.log(e.stack);
}
showErrorAlert(e, callback);
})
}
export function showNoMoreCredits(){
Toast.show({text: gameInfo.creditUnit + lang.no_more_credits});
}
export function delayLoad(){
}
/**
* Created by rockyl on 2018/9/26.
*
* 角标
*/
import CurseComponent from "../curse/CurseComponent";
import badgeService from "../services/BadgeService";
import {BADGE_CHANGED} from "../model/events";
export default class Badge extends CurseComponent {
public name:string = '';
private lab: eui.Label;
protected reset() {
super.reset();
this.lab = this.host.lab;
this.registerEvent(badgeService, BADGE_CHANGED, this.onBadgeChange, this);
this.registerEvent(this.host, egret.Event.ADDED_TO_STAGE, this.onAddedToStage, this);
}
protected awake() {
super.awake();
this.update();
}
protected sleep() {
super.sleep();
}
private onBadgeChange(event){
const {name, number} = event.data;
if(name == this.name){
this.setNum(number);
}
}
update(){
this.setNum(badgeService.getNumber(this.name));
}
setNum(value){
this.lab.text = value + '';
}
private onAddedToStage(event){
this.update();
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import {breath, Wave} from "@alienlib/animation/wave";
import {anchorCenter} from "@alienlib/tools/Utils";
export default class Breath extends CurseComponent{
duration: number = 2000;
scaleOffset: number = 0.1;
wave: Wave;
protected reset() {
super.reset();
anchorCenter(this.host);
this.wave = new Wave(this.host, this.duration, breath.bind(null, this.scaleOffset), 0, false);
}
protected awake() {
super.awake();
this.wave.play();
}
protected sleep() {
super.sleep();
this.wave.stop(true);
}
say(){
console.log('hello')
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import buriedPointService from "../services/BuriedPointService";
export default class BuriedPointButton extends CurseComponent {
dpm: string;
dcm: string;
private buriedPointName: string;
protected reset() {
super.reset();
this.buriedPointName = 'buried-point-' + Date.now();
buriedPointService.addBuriedPointConfig(
this.buriedPointName,
{dpm: this.dpm, dcm: this.dcm}
);
this.registerEvent(this.host, egret.TouchEvent.TOUCH_TAP, this.onHostTap, this);
}
protected awake() {
super.awake();
buriedPointService.logExposure(this.buriedPointName);
}
protected sleep() {
super.sleep();
}
protected destroy() {
super.destroy();
}
private onHostTap(event) {
buriedPointService.logClick(this.buriedPointName);
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import SceneController from "../views/SceneController";
export default class ButtonBack extends CurseComponent{
type: number;
protected reset() {
super.reset();
this.registerEvent(this.host, egret.TouchEvent.TOUCH_TAP, this.onHostTap, this);
}
protected destroy() {
super.destroy();
}
private onHostTap(event){
SceneController.back();
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import PanelController from "../views/PanelController";
import {PANEL_RULE} from "../model/constants";
export default class ButtonRule extends CurseComponent{
type: number;
protected reset() {
super.reset();
this.registerEvent(this.host, egret.TouchEvent.TOUCH_TAP, this.onHostTap, this);
}
private onHostTap(event){
PanelController.instance.show(PANEL_RULE)
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import SceneController from "../views/SceneController";
import {SCENE_PLAY} from "../model/constants";
export default class ButtonStart extends CurseComponent{
type: number;
protected reset() {
super.reset();
this.registerEvent(this.host, egret.TouchEvent.TOUCH_TAP, this.onHostTap, this);
}
private onHostTap(event){
SceneController.goto(SCENE_PLAY);
}
}
/**
* Created by rockyl on 2018/10/19.
*
*
*/
import CurseComponent from "../curse/CurseComponent";
export default class GameViewLabel extends CurseComponent {
protected reset() {
super.reset();
}
protected awake() {
super.awake();
this.host.text = 'hello';
}
protected sleep() {
super.sleep();
}
protected destroy() {
super.destroy();
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/10/11.
*
* 规则弹窗
*/
import CurseComponent from "../curse/CurseComponent";
import PanelController from "../views/PanelController";
import {PANEL_RULE} from "../model/constants";
export default class PanelRule extends CurseComponent {
content: string;
button: string;
protected reset() {
super.reset();
console.log(this.content);
const {labContent, btnConfirm} = this.host;
labContent.text= this.content;
btnConfirm.label = this.button;
this.registerEvent(btnConfirm, egret.TouchEvent.TOUCH_TAP, this.onBtnConfirmTap, this);
}
private onBtnConfirmTap(event) {
PanelController.instance.close(PANEL_RULE);
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import {sin, Wave} from "@alienlib/animation/wave";
import {delayLoad} from "../Utils";
export default class SceneMenu extends CurseComponent{
wave: Wave;
protected reset() {
super.reset();
const {lab} = this.host;
this.wave = new Wave(lab, 2000, sin.bind(null, 20), 0, false);
delayLoad();
}
protected awake() {
super.awake();
this.wave.play();
}
protected sleep() {
super.sleep();
this.wave.stop(true);
}
protected destroy() {
super.destroy();
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import CurseComponent from "../curse/CurseComponent";
import {delayLoad} from "../Utils";
import defenseService from "../services/DefenseService";
export default class ScenePlay extends CurseComponent{
protected reset() {
super.reset();
defenseService.setView(this.host);
delayLoad();
}
protected awake() {
super.awake();
}
protected sleep() {
super.sleep();
}
protected destroy() {
super.destroy();
}
}
/**
* Created by rockyl on 2018/10/10.
*
* 脚本组件基类
*/
import eventManager from "@alienlib/support/EventManager";
export default class CurseComponent extends egret.HashObject{
protected host;
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);
}
/**
* 初始化
*/
protected reset() {
}
/**
* 唤醒
*/
protected awake() {
this.enableEvents();
}
/**
* 沉睡
*/
protected sleep() {
this.disableEvents();
}
/**
* 销毁
*/
protected destroy() {
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/8/20.
*
* 弹窗
*/
import {Flew} from "@alienlib/popup/PopupEffect";
import {PopupBase} from "@alienlib/popup/PopupBase";
import {awakeView, mountScene, sleepView} from "./Manager";
export default class CursePanel extends PopupBase {
options: any;
constructor(name, options) {
super(
Flew, {direction: 'up', withFade: true, ease: egret.Ease.backOut},
Flew, {direction: 'up', withFade: true, ease: egret.Ease.backIn},
);
this.name = name;
this.options = options;
}
protected getSkinName(): any {
return this.options.skin;
}
protected childrenCreated(): void {
super.childrenCreated();
mountScene(this, this.name);
//unmountScene(this, this.name);
}
async show(data, callback) {
this._callback = callback;
await this.popup();
awakeView(this, this.name);
}
active(): void {
super.active();
}
inactive(): void {
super.inactive();
sleepView(this, this.name);
}
}
/**
* Created by rockyl on 2018/8/15.
*
* Curse场景
*/
import {NavigatorAction} from "@alienlib/navigator/StackNavigator";
import Scene from "./Scene";
import {awakeView, mountScene, sleepView, unMountView} from "./Manager";
export default class CurseScene extends Scene {
options: any;
constructor(name, options){
super();
this.name = name;
this.options = options;
}
protected getSkinName(): any {
return this.options.skin;
}
protected getResGroupNames(): string[] {
return this.options.resGroupNames;
}
async onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any> {
awakeView(this, this.name);
return super.onWillEnter(last, action, parameters);
}
async onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any> {
sleepView(this, this.name);
return super.onWillLeave(next, action, parameters);
}
active(): void {
super.active();
}
inactive(): void {
super.inactive();
}
childrenCreated(): void {
super.childrenCreated();
mountScene(this, this.name);
//unmountScene(this, this.name);
}
}
/**
* Created by rockyl on 2018/10/10.
*/
import {injectProp} from "@alienlib/tools/Utils";
const componentDefinitions = {};
const components = [];
const bindingsMap = {};
let bindingConfig: {
name: string,
skin: string,
resGroups?: string[],
bindings: {
target: string,
components: {
script: string,
enabled?: boolean,
injection?: any,
}
}
}[];
function getDefName(str){
return str.substr(str.lastIndexOf('/') + 1);
}
export function ready(config) {
bindingConfig = config;
for (let scene of config) {
for (let binding of scene.bindings) {
for (let component of binding.components) {
const name = getDefName(component.script);
componentDefinitions[name] = window[name];
}
}
}
}
function newComponent(name) {
const def = componentDefinitions[name];
if (!def) {
return null;
}
const ins = new def();
components.push(ins);
return ins;
}
function getHostKey(host) {
return host['__class__'] + '_' + host.hashCode;
}
function getBindingByName(name){
return bindingConfig.find(item=>item.name == name);
}
export function getComponents(host, createWhenNotExist = false) {
const key = getHostKey(host);
let bindings = bindingsMap[key];
if (!bindings && createWhenNotExist) {
bindings = bindingsMap[key] = [];
}
return bindings;
}
export function getComponent(host, nameOrDef){
let target;
const components = getComponents(host);
for(let component of components){
if(components['__class__'] == nameOrDef || component instanceof nameOrDef){
target = component;
break;
}
}
return target;
}
function transData(data){
for(let key in data){
const child = data[key];
const type = typeof child;
if(type == 'object'){
transData(child);
}else if(type == 'string'){
data[key] = child.replace(/\\n/g, '\n');
}
}
}
function bindComponent(host, component, injection) {
let components = getComponents(host, true);
components.push(component);
transData(injection);
injectProp(component, injection);
component['host'] = host;
}
function unbindComponents(host, ...componentArr) {
let components = getComponents(host);
if (!components) {
return;
}
if (componentArr.length > 0) {
for (let component of componentArr) {
component.destroy();
const index = components.indexOf(component);
if (index >= 0) {
components.splice(index, 1);
}
}
} else {
for (let component of components) {
component.destroy();
}
components.splice(0);
}
}
function findTargetInObject(object, targetName){
let target = null;
if(!targetName || targetName == 'this'){
target = object;
}else{
try {
const arr = targetName.split('.');
target = arr.reduce((a, b)=>{
if(a[b]){
return a[b];
}
}, object);
}catch (e) {}
}
return target;
}
function forEachBindings(sceneView, name, func) {
const item = getBindingByName(name);
for (let binding of item.bindings) {
const {target} = binding;
const targetView = findTargetInObject(sceneView, target);
if (targetView) {
func(targetView, binding);
} else {
console.warn(`target ${target} is not exist`)
}
}
}
export function mountScene(sceneView, name) {
forEachBindings(sceneView, name, function (targetView, binding) {
for (let component of binding.components) {
const {script, injection, enabled} = component;
if(!enabled){
continue;
}
const name = getDefName(script);
const instance = newComponent(name);
if (instance) {
bindComponent(targetView, instance, injection);
instance.reset();
} else {
console.warn('script is not exist:', name);
}
}
});
}
export function unMountView(view, name) {
forEachBindings(view, name, function (targetView) {
unbindComponents(targetView);
});
}
export function awakeView(view, name) {
forEachBindings(view, name, function (targetView) {
const components = getComponents(targetView);
if (components) {
for (let component of components) {
component.awake();
}
}
});
}
export function sleepView(view, name) {
forEachBindings(view, name, function (targetView) {
const components = getComponents(targetView);
if (components) {
for (let component of components) {
component.sleep();
}
}
});
}
/**
* Created by admin on 2017/9/25.
*
* 自定义导航
*/
import {NavigatorAction} from "@alienlib/navigator/StackNavigator";
import {injectProp} from "@alienlib/tools/Utils";
import {INavigatorViewBase, Navigator} from "@alienlib/navigator/Navigator";
import Scene from "./Scene";
import CurseScene from "./CurseScene";
export default class CurseNavigator extends Navigator{
private _rootView:eui.Group;
private readonly _injectProps;
private readonly _optionsMap;
constructor(rootView:eui.Group, injectProps = {}){
super();
this._rootView = rootView;
this._injectProps = injectProps;
this._injectProps.navigator = this;
this._optionsMap = {};
}
registerScene(name: string, options: any): void {
this._optionsMap[name] = options;
}
protected newView(name: string): INavigatorViewBase {
const view = new CurseScene(name, this._optionsMap[name]);
injectProp(view, this._injectProps);
return view;
}
protected addView(view:Scene, addToBottom){
if(addToBottom){
this._rootView.addChildAt(view, 0);
}else{
this._rootView.addChild(view);
}
}
async onEnter(name: string, last: string, action: NavigatorAction, parameters: any): Promise<void> {
this._rootView.touchThrough = true;
await super.onEnter(name, last, action, parameters);
this._rootView.touchThrough = false;
}
async onLeave(name: string, next: string, action: NavigatorAction, parameters: any): Promise<void> {
await super.onLeave(name, next, action, parameters);
}
onError(error:Error): void {
if(DEBUG){
console.log(error);
}
}
}
/**
* Created by rockyl on 2017/1/19.
*
* 场景
*/
import {INavigatorViewBase} from "@alienlib/navigator/Navigator";
import {Dispatcher} from "@alienlib/support";
import {NavigatorAction} from "@alienlib/navigator/StackNavigator";
import {ResourceLoader} from "@alienlib/egret";
import {waitPromise} from "@alienlib/tools/EgretUtils";
import CurseNavigator from "./Navigator";
export default class Scene extends eui.Component implements INavigatorViewBase {
public navigator: CurseNavigator;
private needLoad: boolean;
private resolveEnter;
private resolveLeave;
constructor() {
super();
this.onBeginLoadResGroups = this.onBeginLoadResGroups.bind(this);
this.onEndLoadResGroups = this.onEndLoadResGroups.bind(this);
this.onProgress = this.onProgress.bind(this);
}
protected get tweenEnter(): egret.tween.TweenGroup {
return this['enter' + (this.currentState ? '_' + this.currentState : '')];
}
protected get tweenLeave(): egret.tween.TweenGroup {
return this['leave' + (this.currentState ? '_' + this.currentState : '')];
}
protected childrenCreated(): void {
super.childrenCreated();
this.percentWidth = this.percentHeight = 100;
let tween;
if (this.tweenEnter) {
this.tweenEnter.addEventListener(egret.Event.COMPLETE, this.onTweenEnterComplete, this);
} else if (this.skin) {
this.skin.states.forEach(state => {
if (tween = this['enter_' + state.name]) {
tween.addEventListener(egret.Event.COMPLETE, this.onTweenEnterComplete, this);
}
})
}
if (this.tweenLeave) {
this.tweenLeave.addEventListener(egret.Event.COMPLETE, this.onTweenLeaveComplete, this);
} else if (this.skin) {
this.skin.states.forEach(state => {
if (tween = this['leave_' + state.name]) {
tween.addEventListener(egret.Event.COMPLETE, this.onTweenLeaveComplete, this);
}
})
}
}
protected getResGroupNames(): string[] {
return null;
}
protected getSkinName(): any {
return null;
}
protected onBeginLoadResGroups(needLoad) {
}
protected onEndLoadResGroups() {
}
protected onProgress(current, total) {
Dispatcher.dispatch('RES_LOAD_PROGRESS', {current, total})
}
active() {
}
inactive() {
}
onWillUnMount(next: string, action: NavigatorAction, parameters: any): Promise<any> {
return Promise.resolve()
}
protected onSkinOn() {
}
onAddView(): boolean {
return true;
}
onDidEnter(last: string, action: NavigatorAction, parameters: any): void {
}
onDidLeave(next: string, action: NavigatorAction, parameters: any): void {
if (this.parent) {
this.parent.removeChild(this);
}
/*if(action != NavigatorAction.Push){
let resGroupNames = this.getResGroupNames();
if(resGroupNames){
resGroupNames.forEach((resGroupName)=>{
RES.destroyRes(resGroupName, false);
});
}
}*/
}
protected shouldShowLeaveLayer(next, action, parameters) {
return true;
}
protected onBeginLoadResGroups(needLoad) {
this.needLoad = needLoad;
Dispatcher.dispatch('show_loading', {needLoad})
}
protected onEndLoadResGroups() {
}
async onWillMount(next: string, action: NavigatorAction, parameters: any): Promise<any> {
let resGroupNames = this.getResGroupNames();
let p: Promise<any> = ResourceLoader.load(resGroupNames, this.onProgress, this.onBeginLoadResGroups, this.onEndLoadResGroups);
await waitPromise(500);
await p.then(() => {
if (!this.skinName) {
let skinName = this.getSkinName();
if (skinName) {
this.skinName = skinName;
}
} else {
this.onSkinOn();
}
});
}
async onWillEnter(last: string, action: NavigatorAction, parameters: any): Promise<any> {
this.resetScene(parameters);
this.active();
await waitPromise(100);
if (this.tweenEnter) {
this.tweenEnter.play(0);
}
this.onPlayEnter();
const p = Promise.resolve();
Dispatcher.dispatch('hide_black_layer', p);
await p;
await this.waitingForEnter();
}
private waitingForEnter() {
return new Promise(resolve => {
if (this.tweenEnter && this.resolveEnter === false) {
this.resolveEnter = resolve;
} else {
resolve();
}
});
}
async onWillLeave(next: string, action: NavigatorAction, parameters: any): Promise<any> {
if (this.tweenLeave) {
this.tweenLeave.play(0);
}
this.onPlayLeave();
await this.waitingForLeave();
if (this.shouldShowLeaveLayer(next, action, parameters)) {
Dispatcher.dispatch('show_black_layer');
await waitPromise(300);
}
this.inactive();
}
private waitingForLeave() {
return new Promise(resolve => {
if (this.tweenLeave) {
this.resolveLeave = resolve;
} else {
resolve();
}
});
}
private onTweenEnterComplete(event: egret.Event): void {
this.resolveEnter && this.resolveEnter();
this.resolveEnter = null;
}
private onTweenLeaveComplete(event: egret.Event): void {
this.resolveLeave && this.resolveLeave();
this.resolveLeave = null;
}
protected onPlayEnter() {
}
protected onPlayLeave() {
}
protected resetScene(parameters) {
}
protected goto(name, parameters = null) {
this.navigator.push(name, parameters);
}
protected back(parameters = null) {
this.navigator.pop(parameters);
}
}
\ No newline at end of file
/**
* Created by rockyl on 2017/12/21.
*/
declare const recordUrl: string;
declare const resPath: string;
declare const revivePluginId: number;
declare const drawPluginId: number;
declare function getDuibaToken(success: Function, failed: Function);
declare function devil(t);
declare const shareCfg: any;
declare module AS{
export function ready();
/**
* 用户相关接口,如登录,退出等
*
* @namespace AS.account
*/
namespace account{
function getInfo();
function logout();
function receiveAward();
function softFavorites();
function toLogin(success?, fail?);
function preferenceChannelSign();
}
/**
* APP能力相关接口,如app下载,安装等
*
* @namespace AS.app
*/
namespace app{
function appCallbackRegister();
function cancelDownload();
function downloadApp(option, callback?: Function);
function downloadFile();
function getAppInfo();
function getAppState(packageName, versionCode):string;
function installApp();
function launchApp(packageName);
function linkTo();
function pauseAppDownload();
function updateApp();
function uninstallApp();
function showGuidePopup();
function upgradeToMainAppSearch();
function getInstalledAppList();
}
/**
* 分享到其他社交平台接口,如微博,微信等
*
* @namespace AS.share
*/
namespace share{
function setData(data, callback, type?);
function showTitleBarShare();
function showTitleBarDownload();
}
/**
* 手机系统能力调用接口,如相册、摄像头、电话短信等
*
* @namespace AS.sys
*/
namespace sys{
function openAlbum();
function openCamera();
function openMap();
function openSendMail();
function openSendSMS();
function sendSMS();
function openCallTel();
function callTel();
function checkCreateShortcut();
function addShortcut();
function deleteShortcut();
function isSupportGyroscopeSensor();
function detectGyroscopeSensor();
function cancelDetectGyroscopeSensor();
function getMaxVolume();
function getVolume();
function setVolume();
function detectVoiceLevel();
function cancelVoiceLevel();
function addCalendarRemind();
function copy();
function isAndroidEmulator();
function finishActivity();
function quitDialogRegister();
}
/**
* 高级功能接口,intent相关
*
* @namespace AS.bridge
*/
namespace bridge{
function startActivityIntent();
function startBroadcastIntent();
function startServiceIntent();
}
/**
* 支付功能接口,如发起支付、获取支付用户信息
*
* @namespace AS.pay
*/
namespace pay{
function getPaymentUser();
function sendPayment();
}
}
\ No newline at end of file
/**
* Created by rockyl on 2018/9/12.
*/
import Language from "./model/Language";
const lang: Language = new Language();
export default lang;
/**
* Created by rockyl on 2017/1/20.
*
* 游戏配置
*/
export default class GameConfig extends egret.HashObject {
static WEB_SERVICE_URL: string = DEBUG ? 'http://localhost:3000' : '';
static gameName: string = 'curse';
static gameConfig: any = {};
static appConfig: any = {};
static defenseConfig: any = {};
static factor = 10;
static parseConfig() {
const {gameInfo, appInfo, defenseStrategy} = window['CFG'];
const {gameConfig, appConfig, defenseConfig} = this;
const {id, oaId, gameId} = gameInfo;
gameConfig.id = id;
gameConfig.oaId = oaId;
gameConfig.gameId = gameId || window['gameId'];
const {appId, earnCreditsUrl, open, openLogin} = appInfo;
appConfig.appId = appId;
appConfig.earnCreditsUrl = earnCreditsUrl;
appConfig.open = open;
appConfig.openLogin = openLogin;
const {interfaceLimit = 50, scoreUnit = 0} = defenseStrategy;
defenseConfig.interfaceLimit = interfaceLimit;
defenseConfig.scoreUnit = scoreUnit;
}
static initData() {
}
}
/**
* Created by rockyl on 2018/8/21.
*/
export default class GameInfo{
data:any;
creditUnit;
update(data){
this.data = data;
this.data.oldMaxScore = this.data ? this.maxScore : 0;
}
get statusCode(){
return this.data.status.code;
}
get maxScore(){
return this.data.maxScore || 0;
}
get percentage(){
return this.data.percentage;
}
get credits(){
return this.data.credits;
}
get status(){
return this.data.status;
}
get gameId(){
return this.data.gameId;
}
get consumerId(){
return this.data.consumerId;
}
}
/**
* Created by admin on 2017/6/30.
*/
import {StringUtils, Utils} from "@alienlib/tools";
import {LanguageIds, LanguagePack} from "./LanguagePack";
export default class Language extends LanguagePack{
public ids:LanguageIds;
public htmlParser:egret.HtmlTextParser;
constructor(){
super();
this.ids = new LanguageIds();
this.htmlParser = new egret.HtmlTextParser();
}
initData(){
Utils.injectProp(this, RES.getRes('lang'));
}
format(template, ...params){
return StringUtils.formatApply(template, params);
}
formatHtml(template, ...params){
return this.htmlParser.parse(StringUtils.formatApply(template, params));
}
}
\ No newline at end of file
export class LanguagePack{
need_login:string;
net_error:string;
current_score:string;
max_score:string;
score_unit:string;
free:string;
my_credit:string;
no_more_credits:string;
revive_cost:string;
revive_failed:string;
rank_first:string;
rank_second:string;
rank_third:string;
rank_num:string;
rank_out:string;
me:string;
rank_max_score:string;
rank_reward_content:string;
no_more_items:string;
need_install_app:string;
share_result:any;
}
export class LanguageIds{
need_login:string = 'need_login';
net_error:string = 'net_error';
current_score:string = 'current_score';
max_score:string = 'max_score';
score_unit:string = 'score_unit';
free:string = 'free';
my_credit:string = 'my_credit';
no_more_credits:string = 'no_more_credits';
revive_cost:string = 'revive_cost';
revive_failed:string = 'revive_failed';
rank_first:string = 'rank_first';
rank_second:string = 'rank_second';
rank_third:string = 'rank_third';
rank_num:string = 'rank_num';
rank_out:string = 'rank_out';
me:string = 'me';
rank_max_score:string = 'rank_max_score';
rank_reward_content:string = 'rank_reward_content';
no_more_items:string = 'no_more_items';
need_install_app:string = 'need_install_app';
share_result:string = 'share_result';
}
\ No newline at end of file
/**
* Created by admin on 2017/5/23.
*
* 常量名词
*/
export const SCENE_STORY:string = 'scene_story';
export const SCENE_MENU:string = 'scene_menu';
export const SCENE_PLAY:string = 'scene_play';
export const SCENE_MISSION:string = 'scene_mission';
export const SCENE_DRAW_REWARD:string = 'scene_draw-reward';
export const SCENE_FINAL_REWARD:string = 'scene_final_reward';
export const PANEL_RULE:string = 'panel_rule';
export const BADGE_ITEM_COUNT:string = 'BADGE_ITEM_COUNT';
export const BADGE_DRAW_REWARD_COUNT:string = 'BADGE_DRAW_REWARD_COUNT';
\ No newline at end of file
/**
* Created by rockyl on 2018/9/12.
*
* 数据中心
*/
import GameInfo from "./GameInfo";
export const gameInfo: GameInfo = new GameInfo();
export const authData: any = {};
export const pluginInfos = {};
/**
* Created by rocky.l on 2017/2/8.
*
* 事件名
*/
export const SETTING_CHANGED: string = 'SETTING_CHANGED';
export const SHOW_WAITING: string = 'SHOW_WAITING';
export const HIDE_WAITING: string = 'HIDE_WAITING';
export const SHOW_TOAST: string = 'SHOW_TOAST';
export const HIDE_TOAST: string = 'HIDE_TOAST';
export const SCORE_CHANGE: string = 'SCORE_CHANGE';
export const BADGE_CHANGED: string = 'BADGE_CHANGED';
\ No newline at end of file
/**
* Created by rockyl on 2018/7/24.
*
* 埋点
*/
export default class BuriedPoint {
dpm: string;
dcm: string;
constructor(dpm, dcm, env){
this.dpm = this.fill(dpm, env);
this.dcm = this.fill(dcm, env);
}
fill(src, env){
let result = src;
for(let key in env){
result = result.replace(key, env[key]);
}
return result;
}
}
/**
* Created by rockyl on 15/12/16.
*
* 网络服务
*/
import GameConfig from "../model/GameConfig";
import {Ajax, EgretUtils} from "@alienlib/tools";
class WebService {
/**
* 调用API
* @param uri
* @param params
* @param method
* @param responseType
*/
callApi(uri: string, params: any = null, method: string = 'post', responseType = 'json'): Promise<any> {
if (!params) {
params = {};
}
let url: string = GameConfig.WEB_SERVICE_URL + uri;
let m: Function = method == 'post' ? Ajax.POST : Ajax.GET;
return m.call(Ajax, url, params).then(
(response) => {
let data;
switch (responseType) {
case 'json':
try {
data = JSON.parse(response);
} catch (e) {
if(DEBUG) console.log('decode json failed: ' + url);
return Promise.reject(e);
}
if (data.success) {
return data.data || data;
} else {
return Promise.reject(data.message || data.desc);
}
default:
return response;
}
},
(error) => {
if (DEBUG) {
console.log(error);
}
return Promise.reject(error);
}
);
}
polling(successFunc, uri, params, maxTimes = 5, delay = 400, method = 'POST', responseType = 'json'): Promise<any> {
let p = Promise.resolve();
for (let i = 0; i < maxTimes; i++) {
p = p.then(func);
p = p.then(() => {
return EgretUtils.waitPromise(delay)
})
}
const callApi = this.callApi;
let lastData;
return p.then(
() => {
return Promise.reject(null);
},
(e) => {
if (e === 'success') {
return Promise.resolve(lastData);
}
return Promise.reject(e);
}
);
function func() {
return callApi(uri, params, method, responseType).then(
(data) => {
if (successFunc(data)) {
lastData = data;
return Promise.reject('success');
}
},
(e) => {
return Promise.reject(e);
}
)
}
}
}
const webService = new WebService();
export default webService;
/**
* Created by rockyl on 2018/8/21.
*
* api
*/
import webService from "./WebService";
import GameConfig from "../model/GameConfig";
import {authData, gameInfo, pluginInfos} from "../model/data-center";
import {injectProp} from "@alienlib/tools/Utils";
import {md5} from "@alienlib/tools/md5";
export async function getToken() {
return new Promise((resolve, reject) => {
if (window['getDuibaToken']) {
getDuibaToken(
({token}) => {
resolve(token);
},
(key, msg) => {
reject(msg);
}
)
} else {
resolve();
}
});
}
export async function getCredits() {
const {unitName, credits} = await webService.callApi(
'/ctool/getCredits',
{},
'get'
);
gameInfo.creditUnit = unitName;
}
export async function getInfo() {
gameInfo.update(
await webService.callApi(
'/ngame/new/getInfo',
{id: GameConfig.gameConfig.gameId},
'get'
)
);
}
export async function getRule() {
return await webService.callApi(
'/ngapi/getRule',
{id: GameConfig.gameConfig.gameId},
'post',
'html'
)
}
export async function getRealtimeRank(type, count = 50) {
return await webService.callApi(
'/ngapi/realtimerank/' + type,
{
id: GameConfig.gameConfig.gameId,
count,
},
'get'
)
}
export async function tryStart() {
await doStart();
const {ticketId} = authData;
await getStartStatus(ticketId);
}
export async function doStart(credits = null, customizedType = null) {
let {gameId, oaId} = GameConfig.gameConfig;
const params: any = {
id: gameId,
oaId: oaId
};
if (credits) {
params.credits = credits;
}
if (customizedType) {
params.customizedType = customizedType;
}
params.token = await getToken();
const {token, submitToken, ticketId} = await webService.callApi(
'/ngapi/dostart',
params
);
injectProp(authData, {
token: devil(token),
submitToken: devil(submitToken),
ticketId
})
}
export async function getStartStatus(ticketId, customizedType = null) {
const params: any = {
ticketId: ticketId
};
if (customizedType) {
params.customizedType = customizedType
}
return await webService.polling(
data => {
return data.code === 1
},
'/ngapi/getStartStatus',
params
);
}
export async function getPrizeInfo(activityId) {
pluginInfos[activityId] = await webService.callApi(
'/activityPlugDrawInfo/getPrizeInfo',
{activityId},
'get'
);
}
export async function plugDrawInfo(activityId) {
const {plugin} = await webService.callApi(
'/plugin/plugDrawInfo',
{id: activityId},
'get'
);
}
export async function datapash(collection) {
await webService.callApi(
'/ngame/new/datapash',
{
gameId: GameConfig.gameConfig.id,
ticketId: authData.ticketId,
dynamicData: JSON.stringify(collection),
}
);
}
export async function getRankRewardList(showName = false) {
return webService.callApi(
'/ngapi/winranks',
{
id: GameConfig.gameConfig.gameId,
showName,
}
);
}
export async function draw(activityId, deductCredits = false) {
const {orderId} = await doJoinPlugDraw(activityId, deductCredits);
return getPlugOrderStatus(orderId);
}
export async function doJoinPlugDraw(activityId, deductCredits = false) {
return webService.callApi(
'/activityPlugDrawInfo/doJoinPlugdraw',
{activityId, deductCredits}
);
}
export async function getPlugOrderStatus(orderId) {
return webService.polling(
function (data) {
return data.result != 0;
},
'/plugin/getOrderStatus',
{orderId},
10,
);
}
export async function submit(score, collection, strategyCollection) {
const {orderId} = await gameSubmit(score, strategyCollection, collection);
return getSubmitResult(orderId);
}
export async function gameSubmit(score, gameData = [], dynamicData = [[]]) {
const {submitToken, ticketId} = authData;
const gameDataStr = JSON.stringify(gameData);
const dynamicDataStr = JSON.stringify(dynamicData);
let sign = md5(ticketId + '' + score + '' + gameDataStr + '' + submitToken);
const data = await webService.callApi(
'/ngame/new/submit',
{
ticketId,
score,
gameData: gameDataStr,
sgin: sign,
dynamicData: dynamicDataStr
}
);
gameInfo.update(data.rsp);
return data;
}
export async function getSubmitResult(orderId) {
const params: any = {
orderId
};
return await webService.polling(
data => {
return !data.flag;
},
'/ngame/new/getSubmitResult',
params
);
}
export async function getBaiduGameInfo() {
updateBaiduGameInfo(await webService.callApi(
'/aaw/baidu/api/getInfo',
{
activityId: GameConfig.gameConfig.gameId,
},
'get'
));
}
export async function addTimes(type) {
return webService.callApi(
'/aaw/baidu/api/addTimes',
{
activityId: GameConfig.gameConfig.gameId,
type,
},
'get'
);
}
export async function doPlay() {
return webService.callApi(
'/aaw/baidu/api/doPlay',
{
activityId: GameConfig.gameConfig.gameId,
}
);
}
/**
* Created by rockyl on 2018/8/23.
*
* 任务服务
*/
import Service from "./Service";
import {BADGE_CHANGED} from "../model/events";
class BadgeService extends Service {
items: any;
async start(): Promise<void> {
await super.start();
this.items = {};
}
private getItem(name){
let item = this.items[name];
if(!item){
item = this.items[name] = {
number: 0,
};
}
return item;
}
private updateItem(name, item, number){
item.number = number;
this.dispatchEventWith(BADGE_CHANGED, false, {name, number})
}
update(name, number){
const item = this.getItem(name);
this.updateItem(name, item, number);
}
change(name, number){
const item = this.getItem(name);
this.updateItem(name, item, item.number + number);
}
getNumber(name){
const item = this.getItem(name);
return item.number;
}
}
const badgeService: BadgeService = new BadgeService();
export default badgeService;
/**
* Created by rockyl on 2018/9/29.
*
* 埋点服务
*/
import Service from "./Service";
import GameConfig from "../model/GameConfig";
import {JSONP} from "@alienlib/tools/Ajax";
import webService from "../net/WebService";
import BuriedPoint from "../net/BuriedPoint";
import {gameInfo} from "../model/data-center";
class BuriedPointService extends Service {
private _buriedPoints: any = {};
env: any;
async start(): Promise<void> {
await super.start();
this.initEnv();
}
initEnv(){
this.env = {
app_id: GameConfig.appConfig.appId,
oaid: GameConfig.gameConfig.oaId,
}
}
addBuriedPoints(buriedPoints) {
for (let name in buriedPoints) {
this._buriedPoints[name] = buriedPoints[name];
}
}
addBuriedPointConfig(name, config) {
const {dpm, dcm} = config;
this._buriedPoints[name] = new BuriedPoint(dpm, dcm, this.env);
}
addBuriedPointConfigs(configs) {
for (let name in configs) {
this.addBuriedPointConfig(name, configs[name]);
}
}
logExposure(name) {
return this.log(name, 'exposure');
}
logClick(name) {
return this.log(name, 'click');
}
log(name, type) {
let logPoint = this._buriedPoints[name];
let {consumerId} = gameInfo;
let {appId} = GameConfig.appConfig;
let {dpm, dcm} = logPoint;
if (type == 'exposure') {
return JSONP('//embedlog.duiba.com.cn/exposure/standard', {
dpm, dcm, consumerId, appId,
}, 'get').catch(e => {
//console.log(e);
});
} else {
return webService.callApi(
'/log/click',
{
dpm, dcm, consumerId, appId
},
'get'
).catch(e => {
//console.log(e);
});
}
}
}
const buriedPointService: BuriedPointService = new BuriedPointService();
export default buriedPointService;
/**
* Created by rockyl on 2018/8/23.
*/
import Service from "./Service";
import GameConfig from "../model/GameConfig";
import * as api from "../net/proxy";
class DefenseService extends Service {
collection: any[] = [];
strategyCollection: any[] = [];
pashCount;
setView(view){
this.registerEvent(view, egret.TouchEvent.TOUCH_BEGIN, this.onTouch.bind(this, 'md'), this);
}
reset() {
this.collection.splice(0);
this.strategyCollection.splice(0);
this.pashCount = 0;
}
private onTouch(type, e:egret.TouchEvent){
const data = { a: type, t: Date.now(), x: e.stageX, y: e.stageY };
/*let str = JSON.stringify(data);
str = md5(str);
let result = '';
for(let i = 0, li = str.length; i < li; i++){
result += Math.random() < 0.3 ? str.charAt(i) : '';
}*/
this.strategyCollection.push(data)
}
scoreChanged(score){
const {interfaceLimit, scoreUnit} = GameConfig.defenseConfig;
const nextDatapashScore = score - this.pashCount * scoreUnit;
if (scoreUnit == 0 || nextDatapashScore < scoreUnit || this.pashCount > interfaceLimit) {
return;
}
this.collection.push(this.strategyCollection.concat());
api.datapash(this.strategyCollection);
this.strategyCollection.splice(0);
this.pashCount++;
}
close(){
this.collection.push(this.strategyCollection.concat());
return {
strategyCollection: this.strategyCollection,
collection: this.collection,
}
}
}
const defenseService: DefenseService = new DefenseService();
export default defenseService;
\ No newline at end of file
/**
* Created by admin on 2017/6/26.
*
* 主服务
*/
import GameConfig from "../model/GameConfig";
import Service from "./Service";
import * as api from '../net/proxy'
class MainService extends Service {
async start() {
GameConfig.parseConfig();
await super.start();
await Promise.all([
api.getInfo(),
//api.getCredits(),
//api.getPrizeInfo(drawPluginId),
//api.plugDrawInfo(drawPluginId),
])
}
}
const mainService: MainService = new MainService();
export default mainService
/**
* Created by admin on 2017/6/26.
*
* 事件管理器
*/
import eventManager from "@alienlib/support/EventManager";
export default class Service extends egret.EventDispatcher{
constructor(){
super();
this.init();
}
protected init(){
}
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);
}
async start(){
eventManager.enable(this.eventGroupName);
}
async stop(){
eventManager.disable(this.eventGroupName);
}
}
\ No newline at end of file
/**
* Created by admin on 2017/6/16.
*
* 存储数据服务
*/
import Service from "./Service";
import {LocalStorage} from "@alienlib/support";
import {SETTING_CHANGED} from "../model/events";
class StorageService extends Service{
protected store:any;
protected _initialized;
start(): Promise<any> {
this.load();
this.store.launch_count = this.store.launch_count ? this.store.launch_count + 1 : 1;
this.save();
return super.start();
}
private load(){
this.store = LocalStorage.getItemObj('store', {});
}
save(){
LocalStorage.setItemObj('store', this.store);
}
clean(keeps = null){
if(keeps){
for(let k in this.store){
if(keeps.indexOf(k) < 0 && this.store.hasOwnProperty(k)){
delete this.store[k];
}
}
}else{
this.store = {};
}
this.save();
this._initialized = false;
}
get launchCount(){
return this.store.launch_count;
}
getSettingItem(field){
return this.store.setting ? (this.store.setting[field] === undefined ? true : this.store.setting[field]) : true;
}
setSettingItem(field, value, dispatch = true){
let setting = this.store.setting;
if(!setting){
setting = this.store.setting = {};
}
setting[field] = value;
this.save();
if(dispatch){
this.dispatchEventWith(SETTING_CHANGED, false, {field, value});
}
}
switchSettingItem(field, dispatch = true){
this.setSettingItem(field, !this.getSettingItem(field), dispatch);
}
}
const storageService:StorageService = new StorageService();
export default storageService;
\ No newline at end of file
/**
* Created by rockyl on 2018/8/27.
*
* 加载视图
*/
import {Dispatcher} from "@alienlib/support";
export default class LoadingView extends eui.Component implements RES.PromiseTaskReporter {
private static _instance:LoadingView;
public static get instance():LoadingView {
if (this._instance == undefined) {
this._instance = new LoadingView();
}
return this._instance;
}
public progressBar: eui.ProgressBar;
constructor() {
super();
this.percentWidth = this.percentHeight = 100;
this.skinName = LoadingViewSkin;
this.onProgress(0, 100);
Dispatcher.addEventListener('RES_LOAD_PROGRESS', function(e){
const {current, total} = e.data;
this.setProgress(current/total);
}, this)
}
public setProgress(process, immediately: boolean = false){
let d = this.progressBar.slideDuration;
if(immediately){
this.progressBar.slideDuration = 0;
}
this.progressBar.value = Math.floor(process * 100);
if(immediately){
this.progressBar.slideDuration = d;
}
}
public onProgress(current: number, total: number): void {
this.setProgress(current/total);
}
setState(state){
this.currentState = state;
}
}
/**
* Created by rockyl on 2018/8/15.
*
* 主舞台
*/
import Service from "../services/Service";
import LoadingView from "./LoadingView";
import GameConfig from "../model/GameConfig";
import {PopUpManager} from "@alienlib/popup";
import lang from "../lang";
import {gameInfo} from "../model/data-center";
import {Dispatcher} from "@alienlib/support";
import {SCENE_FINAL_REWARD, SCENE_MENU, SCENE_PLAY} from "../model/constants";
import {catchError} from "../Utils";
import {ready as readyCurseManager} from "../curse/Manager";
import SceneController from "./SceneController";
import PanelController from "./PanelController";
import {getTweenPromise} from "@alienlib/tools/EgretUtils";
import Toast from "./Toast";
Toast;
export default class MainStage extends eui.Component {
private static _instance: MainStage;
public static get instance(): MainStage {
if (this._instance == undefined) {
this._instance = new MainStage();
}
return this._instance;
}
projectConfig: any;
services: Service[];
sceneContainer: eui.Group;
popLayer: eui.Group;
loadingView: LoadingView;
constructor() {
super();
this.init();
this.percentWidth = 100;
this.percentHeight = 100;
this.skinName = MainStageSkin;
}
protected init() {
lang.initData();
GameConfig.initData();
this.projectConfig = RES.getRes('project-config');
this.services = this.projectConfig.settings.services.map(item => {
return window[item + 'Service'];
});
}
childrenCreated(): void {
super.createChildren();
this.addChildAt(this.loadingView = LoadingView.instance, 1);
readyCurseManager(this.projectConfig.bindings);
const sceneConfig = {};
const panelConfig = {};
for (let binding of this.projectConfig.bindings) {
const {name, skin, resGroups} = binding;
const config = {
skin: skin,
resGroupNames: resGroups,
};
if (binding.name.indexOf('scene') >= 0) {
sceneConfig[name] = config;
} else {
panelConfig[name] = config;
}
}
SceneController.instance.configure(this.sceneContainer, sceneConfig);
PanelController.instance.configure(this.popLayer, panelConfig);
Dispatcher.addEventListener('show_loading', this.showLoading, this);
Dispatcher.addEventListener('show_black_layer', this.showBlackLayer, this);
Dispatcher.addEventListener('hide_black_layer', this.hideBlackLayer, this);
catchError(this.start());
}
showLoading(event) {
const {needLoad} = event.data;
this.loadingView.setState(needLoad ? 'loading' : 'blank');
if (needLoad) {
this.loadingView.setProgress(0, true);
}
}
clearAndGotoScene(sceneName, params = null) {
PopUpManager.removeAllPupUp();
SceneController.popAll(sceneName, params);
}
showBlackLayer(event) {
const p = event.data;
const layer = this.loadingView;
Toast.clean();
this.addChildAt(layer, 3);
egret.Tween.get(layer, null, null, true)
.to({alpha: 1}, 200)
}
hideBlackLayer(event) {
const p = event.data;
const layer = this.loadingView;
if (!this.contains(layer)) {
return Promise.resolve();
}
p.then(
(data) => {
return getTweenPromise(
egret.Tween.get(layer, null, null, true)
.to({alpha: 0}, 200).call(() => {
if (this.contains(layer)) {
this.removeChild(layer);
}
})
)
}
)
}
async start(params = null) {
await Promise.all(this.services.map(service => service.start()));
const code = gameInfo.statusCode;
const sceneName = code == 4 || code == 5 ? SCENE_FINAL_REWARD :
SCENE_MENU;
this.clearAndGotoScene(sceneName, params)
}
async stop() {
return Promise.all(this.services.map(service => service.stop()))
.then(
(data) => {
},
(error) => {
}
);
}
}
/**
* Created by admin on 2017/5/16.
*
* 弹窗控制器
*/
import CursePanel from "../curse/CursePanel";
import {init as initPopUpManager} from "@alienlib/popup/PopUpManager";
export default class PanelController {
private static _instance: PanelController;
public static get instance(): PanelController {
if (this._instance == undefined) {
this._instance = new PanelController();
}
return this._instance;
}
private _configured;
private _registerMap:any = {};
private _instanceMap:any = {};
configure(rootView, panelConfigs) {
if (this._configured) {
return;
}
this._configured = true;
initPopUpManager(rootView);
for (let key in panelConfigs) {
this.register(key, panelConfigs[key]);
}
}
register(name, options) {
this._registerMap[name] = options;
}
show(name, params?, callback?){
let instance: CursePanel = this._instanceMap[name];
let options = this._registerMap[name];
if(!instance){
instance = this._instanceMap[name] = new CursePanel(name, options);
}
instance.show(params, callback);
return instance;
}
close(name){
let instance: CursePanel = this._instanceMap[name];
if(!instance){
return ;
}
instance.close();
}
}
/**
* Created by admin on 2017/5/16.
*
* 场景控制器
*/
import CurseNavigator from "../curse/Navigator";
import CurseScene from "../curse/CurseScene";
export default class SceneController {
private static _instance: SceneController;
public static get instance(): SceneController {
if (this._instance == undefined) {
this._instance = new SceneController();
}
return this._instance;
}
private _navigator: CurseNavigator;
private _configured;
configure(rootView, sceneConfigs, injectProps?) {
if (this._configured) {
return;
}
this._configured = true;
this._navigator = new CurseNavigator(rootView, injectProps);
for (let key in sceneConfigs) {
this.register(key, sceneConfigs[key]);
}
}
register(name, options) {
this._navigator.registerScene(name, options);
}
get navigator() {
return this._navigator;
}
active() {
let scene: CurseScene = <CurseScene>this._navigator.currentView;
scene.active();
}
inactive() {
let scene: CurseScene = <CurseScene>this._navigator.currentView;
scene.inactive();
}
static replace(name: string, parameters: any = null) {
SceneController.instance.navigator.replace(name, parameters);
}
static goto(name: string, parameters: any = null) {
SceneController.instance.navigator.push(name, parameters);
return true;
}
static back(parameters: any = null) {
SceneController.instance.navigator.pop(parameters);
}
static popAll(name: string, parameters: any = null) {
SceneController.instance.navigator.popAll(name, parameters);
}
static jump(name: string, parameters: any = null) {
SceneController.instance.navigator.jump(name, parameters);
}
}
/**
* Created by admin on 2017/9/14.
*
* Toast组件
*/
import {VisualEventComponent} from "@alienlib/support/EventComponent";
import {Dispatcher} from "@alienlib/support";
import {HIDE_TOAST, SHOW_TOAST} from "../model/events";
export default class Toast extends VisualEventComponent {
private static _instance:Toast;
public static get instance():Toast {
return this._instance;
}
protected grp: eui.Group;
protected labContent: eui.Label;
private _queue;
private _tween;
constructor(){
super();
Toast._instance = this;
}
createChildren(): void {
super.createChildren();
this.grp.alpha = 0;
this._queue = [];
this.registerEvent(Dispatcher, SHOW_TOAST, this.onShow, this);
this.registerEvent(Dispatcher, HIDE_TOAST, this.onClean, this);
}
addAndPlayOne(data = null){
if(data && this._queue.length == 0 && !this._tween){
this._queue.push(data);
}
else if(data && this._queue.length > 0 && data.text != this._queue[this._queue.length-1].text){
this._queue.push(data);
}
if(this._queue.length == 0 || this._tween){
return;
}
let item = this._queue.shift();
let {text, color = 0xfff1d3, duration = 1000} = item;
this.labContent.text = text;
this.labContent.textColor = color;
this._tween = egret.Tween.get(this.grp, null, null, true)
.to({alpha: 1}, 300)
.wait(duration)
.to({alpha: 0}, 200)
.call(()=>{
this._tween = null;
this.addAndPlayOne();
});
}
clean(){
this._queue.splice(0);
}
private onShow(event: egret.Event): void {
this.addAndPlayOne(event.data);
}
private onClean(event: egret.Event): void {
this.clean();
egret.Tween.get(this.grp, null, null, true)
.to({alpha: 0}, 200);
}
static show(data){
Toast._instance.addAndPlayOne(data);
}
static clean(){
Toast._instance.clean();
}
}
\ No newline at end of file
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
export default class AssetAdapter implements eui.IAssetAdapter {
/**
* @language zh_CN
* 解析素材
* @param source 待解析的新素材标识符
* @param compFunc 解析完成回调函数,示例:callBack(content:any,source:string):void;
* @param thisObject callBack的 this 引用
*/
public getAsset(source: string, compFunc: Function, thisObject: any): void {
function onGetRes(data: any): void {
compFunc.call(thisObject, data, source);
}
if (RES.hasRes(source)) {
let data = RES.getRes(source);
if (data) {
onGetRes(data);
}
else {
RES.getResAsync(source, onGetRes, this);
}
}
else {
RES.getResByUrl(source, onGetRes, this, RES.ResourceItem.TYPE_IMAGE);
}
}
}
//////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-present, Egret Technology.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
export default class ThemeAdapter implements eui.IThemeAdapter {
/**
* 解析主题
* @param url 待解析的主题url
* @param onSuccess 解析完成回调函数,示例:compFunc(e:egret.Event):void;
* @param onError 解析失败回调函数,示例:errorFunc():void;
* @param thisObject 回调的this引用
*/
public getTheme(url: string, onSuccess: Function, onError: Function, thisObject: any): void {
function onResGet(e: string): void {
onSuccess.call(thisObject, e);
}
function onResError(e: RES.ResourceEvent): void {
if (e.resItem.url == url) {
RES.removeEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
onError.call(thisObject);
}
}
if (typeof generateEUI !== 'undefined') {
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI);
}, this);
}
else if (typeof generateEUI2 !== 'undefined') {
RES.getResByUrl("resource/gameEui.json", (data, url) => {
window["JSONParseClass"]["setData"](data);
egret.callLater(() => {
onSuccess.call(thisObject, generateEUI2);
}, this);
}, this, RES.ResourceItem.TYPE_JSON);
}
else {
RES.addEventListener(RES.ResourceEvent.ITEM_LOAD_ERROR, onResError, null);
RES.getResByUrl(url, onResGet, this, RES.ResourceItem.TYPE_TEXT);
}
}
}
declare var generateEUI: { paths: string[], skins: any }
declare var generateEUI2: { paths: string[], skins: any }
\ No newline at end of file
//一些名称相关的字符串替换
exports.replaces = {
constants: {
projectName: null, //会用项目名替换
},
contentInFiles: [
'index.html',
'project.json'
],
nameOfFiles: []
};
//收尾时删除的文件
exports.deletes = [
'package.json',
'package-lock.json',
'game-template-curse.iml',
'.git'
];
require("launcher/native_require.js");
egret_native.egtMain = function () {
egret_native.nativeType = "native";
egret_native.egretInit();
egret_native.egretStart();
};
var manifest = JSON.parse(egret_native.readFileSync("manifest.json"));
var game_file_list = manifest.initial.concat(manifest.game);
var window = this;
egret_native.setSearchPaths([""]);
egret_native.requireFiles = function () {
for (var key in game_file_list) {
var src = game_file_list[key];
require(src);
}
};
egret_native.egretInit = function () {
if(egret_native.featureEnable) {
//控制一些优化方案是否开启
//Control whether some optimization options are open
var result = egret_native.featureEnable({
});
}
egret_native.requireFiles();
egret.dom = {};
egret.dom.drawAsCanvas = function () {
};
};
egret_native.egretStart = function () {
var option = {
//以下为自动修改,请勿修改
//The following is automatically modified, please do not modify
//----auto option start----
entryClassName: "Main",
frameRate: 60,
scaleMode: "fixedWidth",
contentWidth: 750,
contentHeight: 1206,
showPaintRect: false,
showFPS: false,
fpsStyles: "x:0,y:0,size:12,textColor:0xffffff,bgAlpha:0.9",
showLog: false,
logFilter: "",
maxTouches: 2,
textureScaleFactor: 1
//----auto option end----
};
egret.native.NativePlayer.option = option;
egret.runEgret();
egret_native.Label.createLabel("/system/fonts/DroidSansFallback.ttf", 20, "", 0);
egret_native.EGTView.preSetOffScreenBufferEnable(true);
};
\ No newline at end of file
require("launcher/native_require.js");
egret_native.egtMain = function () {
egret_native.nativeType = "runtime";
egret_native.egretInit();
egret_native.egretStart();
};
\ 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: #888888;
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="30"
data-content-width="750"
data-content-height="1334"
data-show-paint-rect="false"
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 src="vendor.js"></script>
<script src="bundle.min.js"></script>
<script>
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;
}
});
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": 10
}
}
var recordUrl = 'record/';
function resolve(a) {
var b = eval(a);
return b;
}
</script>
</body>
</html>
\ No newline at end of file
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"removeComments": true,
"importHelpers": true,
"experimentalDecorators": true,
"allowJs": true,
"lib": [
"es5",
"dom",
"es2015.promise"
],
"baseUrl": "./",
"paths": {
"@alienlib/*": ["/Users/rockyl/WorkSpaces/alienlib/src/*"]
}
},
"exclude": [
"node_modules",
"scripts",
"bin-debug",
"bin-release",
"design"
]
}
\ No newline at end of file
{
"resourcePlugin":{
"configs":[{
"configPath":"resource/default.res.json",
"relativePath":"resource/"
}]
},
"theme":"resource/default.thm.json"
}
\ No newline at end of file
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