优化若干代码

This commit is contained in:
2024-04-17 20:15:52 +08:00
parent 54580cc1b2
commit 58cc2e3b82
66 changed files with 5821 additions and 4019 deletions

View File

@@ -1,5 +1,5 @@
{ {
"image": { "image": {
"type": "sprite-frame" "type": "texture"
} }
} }

5
.editorconfig Normal file
View File

@@ -0,0 +1,5 @@
root = true
[*]
charset = utf-8
end_of_line = lf

11
.eslintignore Normal file
View File

@@ -0,0 +1,11 @@
.creator
.idea
.vscode
.git
.DS_Store
/node_modules
/build
/temp
/library
/profiles
/settings

11
.prettierignore Normal file
View File

@@ -0,0 +1,11 @@
.creator
.idea
.vscode
.git
.DS_Store
/node_modules
/build
/temp
/library
/profiles
/settings

6
.prettierrc.json Normal file
View File

@@ -0,0 +1,6 @@
{
"printWidth": 100,
"singleQuote": true,
"semi": false,
"endOfLine": "lf"
}

View File

@@ -1,162 +1,164 @@
import { import {
_decorator, _decorator,
Component, Component,
CCInteger, CCInteger,
CCFloat, CCFloat,
Vec2, Vec2,
Animation, Animation,
Vec3, Vec3,
} from 'cc' } from 'cc'
const { ccclass, property } = _decorator
const {ccclass, property} = _decorator
import FishBase from './FishBase' import FishBase from './FishBase'
import MathUtils from '../../script/engine/utils/MathUtils' import MathUtils from '../../script/engine/utils/MathUtils'
import { Logger } from '../../script/engine/utils/Logger' import {Logger} from '../../script/engine/utils/Logger'
import TimeHelper from '../../script/game/utils/TimeHelper' import TimeHelper from '../../script/game/utils/TimeHelper'
@ccclass('FishMover') @ccclass('FishMover')
export default class FishMover extends Component { export default class FishMover extends Component {
// //鱼类型 //鱼类型
@property({ type: CCInteger }) @property({type: CCInteger})
public fishType: number = 1 public fishType: number = 1
// //鱼移动速度 //鱼移动速度
@property({ type: CCFloat }) @property({type: CCFloat})
public speed: number = 3 public speed: number = 3
// //下个位置移动点 //下个位置移动点
private targetMoveIndex: number = 0 private targetMoveIndex: number = 0
// //鱼移动位置 //鱼移动位置
public movePList: Array<Vec2> = [] public movePList: Array<Vec2> = []
// //贝萨尔曲线 //贝萨尔曲线
public bezierPList: Array<Vec2> = [] public bezierPList: Array<Vec2> = []
public isMoving: boolean = false public isMoving: boolean = false
private minSpeed: number = 0.1 private minSpeed: number = 0.1
private moveCount: number = 1 private moveCount: number = 1
private totalTimes: number = 60 * 2 private totalTimes: number = 60 * 2
private _vec3Cahce: Vec3 = new Vec3() private _vec3Cahce: Vec3 = new Vec3()
public startMove() {
this.targetMoveIndex = 0
this.isMoving = true
//this.node.getComponent(Animation).play()//v3 当前帧 不能播放
TimeHelper.exeNextFrame(this.node, () =>
this.node.getComponent(Animation).play()
)
}
update(dt) { public startMove() {
// this.moveFish(); this.targetMoveIndex = 0
this.checkMoveBezier() this.isMoving = true
} //this.node.getComponent(Animation).play()//v3 当前帧 不能播放
TimeHelper.exeNextFrame(this.node, () =>
this.node.getComponent(Animation).play()
)
}
private checkMoveBezier() { update(dt) {
if (this.isMoving && !this.getComponent(FishBase).isDead) { // this.moveFish();
this.moveCount++ this.checkMoveBezier()
if (this.moveCount >= this.totalTimes) { }
this.moveCount = this.totalTimes
}
this.moveBezier()
}
}
public moveBezier() { private checkMoveBezier() {
// [warn] [[-632,-230],[-444,-117],[-264,-242]] if (this.isMoving && !this.getComponent(FishBase).isDead) {
// let p0: cc.Vec2 = cc.v2(-632, -230) this.moveCount++
// let p1: cc.Vec2 = cc.v2(-444, -117) if (this.moveCount >= this.totalTimes) {
// let p2: cc.Vec2 = cc.v2(-264, -242) this.moveCount = this.totalTimes
if (this.bezierPList.length > this.targetMoveIndex + 2) { }
let p0: Vec2 = this.bezierPList[this.targetMoveIndex] this.moveBezier()
let p1: Vec2 = this.bezierPList[this.targetMoveIndex + 1] }
let p2: Vec2 = this.bezierPList[this.targetMoveIndex + 2] }
let t: number = this.moveCount / this.totalTimes
let mx: number =
Math.pow(1 - t, 2) * p0.x +
2 * t * (1 - t) * p1.x +
Math.pow(t, 2) * p2.x
let my: number =
Math.pow(1 - t, 2) * p0.y +
2 * t * (1 - t) * p1.y +
Math.pow(t, 2) * p2.y
this.node.getPosition(this._vec3Cahce)
let rad: number = MathUtils.p2pRad(
new Vec2(this._vec3Cahce.x, this._vec3Cahce.y),
new Vec2(mx, my)
)
let rot111: number = MathUtils.radiansToDegrees(rad)
let rot: number = MathUtils.rotation2Fish(rot111)
if (this.fishType == 7 || this.fishType == 27 || this.fishType == 29) {
if (rot > 90 || rot < -90) {
this.node.getScale(this._vec3Cahce)
if (this._vec3Cahce.x > 0) {
this._vec3Cahce.x = -1 * this._vec3Cahce.x
this.node.setScale(this._vec3Cahce)
}
} else {
this.node.getScale(this._vec3Cahce)
if (this._vec3Cahce.x < 0) {
this._vec3Cahce.x = -1 * this._vec3Cahce.x
this.node.setScale(this._vec3Cahce)
}
}
} else if (
this.fishType == 9 ||
this.fishType == 10 ||
this.fishType == 21 ||
this.fishType == 28
) {
} else {
// this.node.rotation = rot; //过时
this.node.angle = -rot
}
// Logger.log("moveBezier====", rad, rot111, this.fishType, rot)
let moveTimes: number = Math.round(this.speed / this.minSpeed)
for (let i = 0; i < moveTimes; i++) {
let speedX: number = this.minSpeed * Math.cos(rad)
let speedY: number = this.minSpeed * Math.sin(rad)
this.node.getPosition(this._vec3Cahce)
this._vec3Cahce.x += speedX
this._vec3Cahce.y += speedY
this.node.setPosition(this._vec3Cahce)
if (
MathUtils.distance(this._vec3Cahce.x, this._vec3Cahce.y, mx, my) <=
this.minSpeed
) {
this.node.setPosition(mx, my)
break
}
if (
MathUtils.distance(
this._vec3Cahce.x,
this._vec3Cahce.y,
p2.x,
p2.y
) <=
this.minSpeed * 2
) {
this.node.setPosition(p2.x, p2.y)
this.targetMoveIndex += 2
this.moveCount = 0
break
}
}
} else {
this.isMoving = false
}
}
onDisable() { public moveBezier() {
this.isMoving = false // [warn] [[-632,-230],[-444,-117],[-264,-242]]
} // let p0: cc.Vec2 = cc.v2(-632, -230)
// let p1: cc.Vec2 = cc.v2(-444, -117)
// let p2: cc.Vec2 = cc.v2(-264, -242)
if (this.bezierPList.length > this.targetMoveIndex + 2) {
let p0: Vec2 = this.bezierPList[this.targetMoveIndex]
let p1: Vec2 = this.bezierPList[this.targetMoveIndex + 1]
let p2: Vec2 = this.bezierPList[this.targetMoveIndex + 2]
let t: number = this.moveCount / this.totalTimes
let mx: number =
Math.pow(1 - t, 2) * p0.x +
2 * t * (1 - t) * p1.x +
Math.pow(t, 2) * p2.x
let my: number =
Math.pow(1 - t, 2) * p0.y +
2 * t * (1 - t) * p1.y +
Math.pow(t, 2) * p2.y
this.node.getPosition(this._vec3Cahce)
let rad: number = MathUtils.p2pRad(
new Vec2(this._vec3Cahce.x, this._vec3Cahce.y),
new Vec2(mx, my)
)
let rot111: number = MathUtils.radiansToDegrees(rad)
let rot: number = MathUtils.rotation2Fish(rot111)
if (this.fishType == 7 || this.fishType == 27 || this.fishType == 29) {
if (rot > 90 || rot < -90) {
this.node.getScale(this._vec3Cahce)
if (this._vec3Cahce.x > 0) {
this._vec3Cahce.x = -1 * this._vec3Cahce.x
this.node.setScale(this._vec3Cahce)
}
} else {
this.node.getScale(this._vec3Cahce)
if (this._vec3Cahce.x < 0) {
this._vec3Cahce.x = -1 * this._vec3Cahce.x
this.node.setScale(this._vec3Cahce)
}
}
} else if (
this.fishType == 9 ||
this.fishType == 10 ||
this.fishType == 21 ||
this.fishType == 28
) {
} else {
// this.node.rotation = rot; //过时
this.node.angle = -rot
}
// Logger.log("moveBezier====", rad, rot111, this.fishType, rot)
let moveTimes: number = Math.round(this.speed / this.minSpeed)
for (let i = 0; i < moveTimes; i++) {
let speedX: number = this.minSpeed * Math.cos(rad)
let speedY: number = this.minSpeed * Math.sin(rad)
this.node.getPosition(this._vec3Cahce)
this._vec3Cahce.x += speedX
this._vec3Cahce.y += speedY
this.node.setPosition(this._vec3Cahce)
if (
MathUtils.distance(this._vec3Cahce.x, this._vec3Cahce.y, mx, my) <=
this.minSpeed
) {
this.node.setPosition(mx, my)
break
}
if (
MathUtils.distance(
this._vec3Cahce.x,
this._vec3Cahce.y,
p2.x,
p2.y
) <=
this.minSpeed * 2
) {
this.node.setPosition(p2.x, p2.y)
this.targetMoveIndex += 2
this.moveCount = 0
break
}
}
} else {
this.isMoving = false
}
}
public exportBezierConfig() { onDisable() {
Logger.warn('exportBezierConfig=') this.isMoving = false
let tempConfig: Array<Array<number>> = [] }
for (let i = 0; i < this.bezierPList.length; i++) {
tempConfig[i] = [] public exportBezierConfig() {
tempConfig[i].push(Math.floor(this.bezierPList[i].x)) Logger.warn('exportBezierConfig=')
tempConfig[i].push(Math.floor(this.bezierPList[i].y)) let tempConfig: Array<Array<number>> = []
} for (let i = 0; i < this.bezierPList.length; i++) {
Logger.warn('fishtype', this.fishType) tempConfig[i] = []
Logger.warn('speed', this.speed) tempConfig[i].push(Math.floor(this.bezierPList[i].x))
Logger.warn('scale', this.node.scale) tempConfig[i].push(Math.floor(this.bezierPList[i].y))
Logger.warn(JSON.stringify(tempConfig)) }
} Logger.warn('fishtype', this.fishType)
Logger.warn('speed', this.speed)
Logger.warn('scale', this.node.scale)
Logger.warn(JSON.stringify(tempConfig))
}
} }

View File

@@ -1,4 +1,5 @@
import { _decorator } from 'cc' import { _decorator } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
@ccclass('CommonEvent') @ccclass('CommonEvent')

View File

@@ -1,4 +1,3 @@
import { _decorator } from 'cc'
import DateUtil from '../utils/DateUtil' import DateUtil from '../utils/DateUtil'
import NetConfig from './NetConfig' import NetConfig from './NetConfig'

View File

@@ -1,4 +1,4 @@
import { _decorator, AudioClip } from 'cc' import { AudioClip } from 'cc'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
export default class MusicConfig { export default class MusicConfig {

View File

@@ -1,4 +1,3 @@
import { _decorator } from 'cc'
export default class NetConfig { export default class NetConfig {
public static hotupdateUrl: string = 'http://localhost:33/hotupdate' public static hotupdateUrl: string = 'http://localhost:33/hotupdate'
} }

View File

@@ -1,18 +1,10 @@
import { import { _decorator, Component, instantiate, Label, Node, tween, Vec3 } from 'cc'
_decorator,
Component,
Label,
Node,
tween,
Vec3,
instantiate,
} from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
import DialogBase from './DialogBase' import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('CommonTips') @ccclass('CommonTips')
export default class CommonTips extends Component { export default class CommonTips extends Component {
public static TipsZorderIndex: number = 999 public static TipsZorderIndex: number = 999

View File

@@ -1,10 +1,10 @@
import { _decorator, Component, Prefab, Widget, instantiate, Node } from 'cc' import { _decorator, Component, instantiate, Node, Prefab, Widget } from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
import DialogBase from './DialogBase' import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('DarkLayer') @ccclass('DarkLayer')
export default class DarkLayer extends Component { export default class DarkLayer extends Component {
private static prefab: Prefab private static prefab: Prefab

View File

@@ -1,9 +1,9 @@
import { _decorator, Component, Node, Widget, director } from 'cc' import { _decorator, Component, Node, Widget } from 'cc'
const { ccclass } = _decorator
import DarkLayer from './DarkLayer' import DarkLayer from './DarkLayer'
import { UIRoot } from '../../game/utils/UIRoot' import { UIRoot } from '../../game/utils/UIRoot'
const { ccclass } = _decorator
@ccclass('DialogBase') @ccclass('DialogBase')
export default class DialogBase extends Component { export default class DialogBase extends Component {
private static LocalZOrder: number = 5 private static LocalZOrder: number = 5

View File

@@ -1,19 +1,10 @@
import { import { _decorator, Component, instantiate, Node, Prefab, Quat, Vec3 } from 'cc'
_decorator,
Component,
Node,
Prefab,
instantiate,
math,
Quat,
Vec3,
} from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
import DialogBase from './DialogBase' import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('LoadingPrefab') @ccclass('LoadingPrefab')
export default class LoadingPrefab extends Component { export default class LoadingPrefab extends Component {
public static instance: Node public static instance: Node

View File

@@ -1,11 +1,11 @@
import { _decorator, Component, Node, Prefab, instantiate } from 'cc' import { _decorator, Component, instantiate, Node, Prefab } from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import Progress from './Progress' import Progress from './Progress'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
import DialogBase from './DialogBase' import DialogBase from './DialogBase'
const { ccclass, property } = _decorator
@ccclass('LoadingScenePrefab') @ccclass('LoadingScenePrefab')
export default class LoadingScenePrefab extends Component { export default class LoadingScenePrefab extends Component {
public static instance: Node public static instance: Node

View File

@@ -1,19 +1,12 @@
import { import { _decorator, AssetManager, AudioClip, AudioSource, Component, instantiate, Prefab } from 'cc'
_decorator,
Component,
AssetManager,
AudioClip,
AudioSource,
instantiate,
Prefab,
} from 'cc'
const { ccclass, property } = _decorator
import { Logger } from '../utils/Logger' import { Logger } from '../utils/Logger'
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import LocalStorage from '../utils/LocalStorage' import LocalStorage from '../utils/LocalStorage'
import MusicConfig from '../config/MusicConfig' import MusicConfig from '../config/MusicConfig'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
const { ccclass, property } = _decorator
/** /**
* 背景音乐 * 背景音乐
*/ */

View File

@@ -1,7 +1,6 @@
import { _decorator, Component, Label, ProgressBar } from 'cc' import { _decorator, Component, Label, ProgressBar } from 'cc'
const { ccclass, property } = _decorator
import { Logger } from '../utils/Logger' const { ccclass, property } = _decorator
@ccclass('Progress') @ccclass('Progress')
export default class Progress extends Component { export default class Progress extends Component {

View File

@@ -1,16 +1,4 @@
import { import { _decorator, AssetManager, AudioClip, AudioSource, Component, instantiate, Node, NodePool, Prefab } from 'cc'
_decorator,
Component,
Prefab,
NodePool,
Node,
instantiate,
AssetManager,
AudioClip,
AudioSource,
} from 'cc'
const { ccclass, property } = _decorator
import { Logger } from '../utils/Logger' import { Logger } from '../utils/Logger'
import PrefabLoader from '../utils/PrefabLoader' import PrefabLoader from '../utils/PrefabLoader'
import LocalStorage from '../utils/LocalStorage' import LocalStorage from '../utils/LocalStorage'
@@ -18,6 +6,9 @@ import EventManager from '../utils/EventManager'
import CommonEvent from '../config/CommonEvent' import CommonEvent from '../config/CommonEvent'
import MusicConfig from '../config/MusicConfig' import MusicConfig from '../config/MusicConfig'
import { GameConfig } from '../../game/config/GameConfig' import { GameConfig } from '../../game/config/GameConfig'
const { ccclass, property } = _decorator
// /** // /**
// * 音效 // * 音效
// * Ios暂时有bug弃用 // * Ios暂时有bug弃用

View File

@@ -1,4 +1,5 @@
import { _decorator, Component, SpriteFrame } from 'cc' import { _decorator, Component, SpriteFrame } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
@ccclass('TextureMgr') @ccclass('TextureMgr')

View File

@@ -1,38 +1,38 @@
import { Canvas, error, log, ResolutionPolicy, sys, view, _decorator } from 'cc' import { _decorator, Canvas, error, log, view } from 'cc'
import DialogBase from '../uicomponent/DialogBase' import DialogBase from '../uicomponent/DialogBase'
const { ccclass, property } = _decorator
import { Logger } from './Logger' const { ccclass, property } = _decorator
@ccclass('AdapterHelper') @ccclass('AdapterHelper')
export default class AdapterHelper { export default class AdapterHelper {
public static winSizeWidth: number public static winSizeWidth: number
public static winSizeHeiht: number public static winSizeHeiht: number
public static fixApdater() {
log('v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true')
return
let framesize = view.getFrameSize()
if (!this.winSizeWidth) {
this.winSizeWidth = screen.width
this.winSizeHeiht = screen.height
}
let designsize = view.getDesignResolutionSize()
let canvas: Canvas = DialogBase.GetRootCanvas().getComponent(Canvas)
let ratio: number = framesize.height / framesize.width public static fixApdater() {
let designRatio: number = designsize.height / designsize.width log('v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true')
if (ratio > designRatio) { return
//canvas.fitHeight = false; let framesize = view.getFrameSize()
//canvas.fitWidth = true; if (!this.winSizeWidth) {
error( this.winSizeWidth = screen.width
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true' this.winSizeHeiht = screen.height
) }
} else { let designsize = view.getDesignResolutionSize()
//canvas.fitHeight = true; let canvas: Canvas = DialogBase.GetRootCanvas().getComponent(Canvas)
//canvas.fitWidth = false;
error( let ratio: number = framesize.height / framesize.width
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true' let designRatio: number = designsize.height / designsize.width
) if (ratio > designRatio) {
} //canvas.fitHeight = false;
} //canvas.fitWidth = true;
error(
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true'
)
} else {
//canvas.fitHeight = true;
//canvas.fitWidth = false;
error(
'v3.6没找到接口修改 fitHeight、fitWidth, 先在项目里写死fitHeight=true'
)
}
}
} }

View File

@@ -1,52 +1,48 @@
import { _decorator } from 'cc' import { _decorator } from 'cc'
const { ccclass, property } = _decorator
import { Logger } from './Logger' const { ccclass, property } = _decorator
@ccclass('BitUtil') @ccclass('BitUtil')
export default class BitUtil { export default class BitUtil {
//index是二进制从右到左 //index是二进制从右到左
public static isBitSet(value: number, index: number): boolean { public static isBitSet(value: number, index: number): boolean {
let str: string = value.toString(2) let str: string = value.toString(2)
if (parseInt(str[str.length - 1 - index]) == 1) { return parseInt(str[str.length - 1 - index]) == 1
return true }
}
return false
}
//从右到左计算 //从右到左计算
public static setBitValue(value: number, index: number): number { public static setBitValue(value: number, index: number): number {
let newValue: number = value let newValue: number = value
let str: string = value.toString(2) let str: string = value.toString(2)
let newStr: string = '' let newStr: string = ''
let maxIndex = Math.max(str.length - 1, index) let maxIndex = Math.max(str.length - 1, index)
for (let i = 0; i <= maxIndex; i++) { for (let i = 0; i <= maxIndex; i++) {
if (index == i) { if (index == i) {
newStr = '1' + newStr newStr = '1' + newStr
} else { } else {
if (str[i] == undefined) { if (str[i] == undefined) {
newStr = '0' + newStr newStr = '0' + newStr
} else { } else {
newStr = str[i] + newStr newStr = str[i] + newStr
} }
} }
} }
newValue = parseInt(newStr, 2) newValue = parseInt(newStr, 2)
return newValue return newValue
} }
public static clearBitValue(value: number, index: number) { public static clearBitValue(value: number, index: number) {
let newValue: number = value let newValue: number = value
let str: string = value.toString(2) let str: string = value.toString(2)
let newStr: string = '' let newStr: string = ''
for (let i = str.length - 1; i >= 0; i--) { for (let i = str.length - 1; i >= 0; i--) {
if (index == str.length - 1 - i) { if (index == str.length - 1 - i) {
newStr = '0' + newStr newStr = '0' + newStr
} else { } else {
newStr = str[i] + newStr newStr = str[i] + newStr
} }
} }
newValue = parseInt(newStr, 2) newValue = parseInt(newStr, 2)
return newValue return newValue
} }
} }

View File

@@ -1,10 +1,11 @@
import { _decorator, Color } from 'cc' import { _decorator, Color } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
@ccclass('ColorHelper') @ccclass('ColorHelper')
export default class ColorHelper { export default class ColorHelper {
public static getColor(hexStr: string): Color { public static getColor(hexStr: string): Color {
let color: Color = Color.BLACK let color: Color = Color.BLACK
return color.fromHEX(hexStr) return color.fromHEX(hexStr)
} }
} }

View File

@@ -1,139 +1,136 @@
import { _decorator } from 'cc'
import { Logger } from './Logger'
export default class DateUtil { export default class DateUtil {
public static formatNumStr(num: number) { public static formatNumStr(num: number) {
let str = '' + num let str = '' + num
if (num < 10) { if (num < 10) {
str = '0' + num str = '0' + num
} }
return str return str
} }
public static formateYearMonthDayStr(timestamp: number) { public static formateYearMonthDayStr(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
) )
} }
public static formateMonthDayStr(timestamp: number) { public static formateMonthDayStr(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return date.getMonth() + 1 + '月' + date.getDate() + '日' return date.getMonth() + 1 + '月' + date.getDate() + '日'
} }
// timestamp:1453094034000 2018-1-31 19:53:44 // timestamp:1453094034000 2018-1-31 19:53:44
//根据时间戳返回 2018-1-31 19:53:44 //根据时间戳返回 2018-1-31 19:53:44
public static formatDateStr(timestamp: number) { public static formatDateStr(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
date.getFullYear() + date.getFullYear() +
'-' + '-' +
(date.getMonth() + 1) + (date.getMonth() + 1) +
'-' + '-' +
date.getDate() + date.getDate() +
' ' + ' ' +
this.formatNumStr(date.getHours()) + this.formatNumStr(date.getHours()) +
':' + ':' +
this.formatNumStr(date.getMinutes()) + this.formatNumStr(date.getMinutes()) +
':' + ':' +
this.formatNumStr(date.getSeconds()) this.formatNumStr(date.getSeconds())
) )
} }
// timestamp:1453094034000 2018-1-31-19-53-44 // timestamp:1453094034000 2018-1-31-19-53-44
//根据时间戳返回 2018-1-31-19-53-44 //根据时间戳返回 2018-1-31-19-53-44
public static formatDateStr2(timestamp: number) { public static formatDateStr2(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
date.getFullYear() + date.getFullYear() +
'-' + '-' +
(date.getMonth() + 1) + (date.getMonth() + 1) +
'-' + '-' +
date.getDate() + date.getDate() +
'-' + '-' +
this.formatNumStr(date.getHours()) + this.formatNumStr(date.getHours()) +
'-' + '-' +
this.formatNumStr(date.getMinutes()) + this.formatNumStr(date.getMinutes()) +
'-' + '-' +
this.formatNumStr(date.getSeconds()) this.formatNumStr(date.getSeconds())
) )
} }
// timestamp:1453094034000 2018-1-31 // timestamp:1453094034000 2018-1-31
//根据时间戳返回 2018-1-31 //根据时间戳返回 2018-1-31
public static formatDateStr3(timestamp: number) { public static formatDateStr3(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate() date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate()
) )
} }
// timestamp:1453094034000 // timestamp:1453094034000
//根据时间戳返回 19:53 //根据时间戳返回 19:53
public static formatHourMinStr(timestamp: number) { public static formatHourMinStr(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
this.formatNumStr(date.getHours()) + this.formatNumStr(date.getHours()) +
':' + ':' +
this.formatNumStr(date.getMinutes()) this.formatNumStr(date.getMinutes())
) )
} }
// timestamp:1453094034000 // timestamp:1453094034000
//根据时间戳返回 19:53:11 //根据时间戳返回 19:53:11
public static formatHourMinSecondStr(timestamp: number) { public static formatHourMinSecondStr(timestamp: number) {
let date: Date = new Date(timestamp) let date: Date = new Date(timestamp)
return ( return (
this.formatNumStr(date.getHours()) + this.formatNumStr(date.getHours()) +
':' + ':' +
this.formatNumStr(date.getMinutes()) + this.formatNumStr(date.getMinutes()) +
':' + ':' +
this.formatNumStr(date.getSeconds()) this.formatNumStr(date.getSeconds())
) )
} }
public static now(): number { public static now(): number {
let date: Date = new Date() let date: Date = new Date()
return date.getTime() return date.getTime()
} }
public static betweenTime(startTime: number, endTime: number) { public static betweenTime(startTime: number, endTime: number) {
let date: Date = new Date() let date: Date = new Date()
if (date.getTime() >= startTime && date.getTime() <= endTime) { if (date.getTime() >= startTime && date.getTime() <= endTime) {
return true return true
} }
return false return false
} }
//根据时间戳返回 1天19:53:11 //根据时间戳返回 1天19:53:11
public static formatLeftTime(timestamp: number) { public static formatLeftTime(timestamp: number) {
let result: string = '' let result: string = ''
let day: number = Math.floor(timestamp / (1000 * 60 * 60 * 24)) let day: number = Math.floor(timestamp / (1000 * 60 * 60 * 24))
let hour: number = Math.floor(timestamp / (1000 * 60 * 60)) % 24 let hour: number = Math.floor(timestamp / (1000 * 60 * 60)) % 24
let min: number = Math.floor(timestamp / (1000 * 60)) % 60 let min: number = Math.floor(timestamp / (1000 * 60)) % 60
let second: number = Math.floor(timestamp / 1000) % 60 let second: number = Math.floor(timestamp / 1000) % 60
result = result =
day + day +
'天' + '天' +
this.formatNumStr(hour) + this.formatNumStr(hour) +
':' + ':' +
this.formatNumStr(min) + this.formatNumStr(min) +
':' + ':' +
this.formatNumStr(second) this.formatNumStr(second)
return result return result
} }
public static isToday(dateTime: number): boolean { public static isToday(dateTime: number): boolean {
let nowDate: Date = new Date() let nowDate: Date = new Date()
let checkDate: Date = new Date(dateTime) let checkDate: Date = new Date(dateTime)
if ( if (
checkDate.getFullYear() == nowDate.getFullYear() && checkDate.getFullYear() == nowDate.getFullYear() &&
checkDate.getMonth() == nowDate.getMonth() && checkDate.getMonth() == nowDate.getMonth() &&
checkDate.getDate() == nowDate.getDate() checkDate.getDate() == nowDate.getDate()
) { ) {
return true return true
} }
return false return false
} }
} }

View File

@@ -1,131 +1,132 @@
import { _decorator, Node, Color, Button, Component, Slider } from 'cc' import { Button, Color, Component, Node, Slider } from 'cc'
import { Logger } from './Logger'
import ColorHelper from './ColorHelper' import ColorHelper from './ColorHelper'
export class HaoEvent { export class HaoEvent {
public callback: Function public callback: Function
public caller: any public caller: any
public isStop: boolean public isStop: boolean
constructor(callback: Function, caller: any) {
this.callback = callback constructor(callback: Function, caller: any) {
this.caller = caller this.callback = callback
this.isStop = false this.caller = caller
} this.isStop = false
}
} }
export default class EventManager { export default class EventManager {
public static instance: EventManager = new EventManager() public static instance: EventManager = new EventManager()
private callbackList = {} private callbackList = {}
public constructor() {} public constructor() {
}
//注册事件 //注册事件
public addListener(eventName: string, callback: Function, caller: any) { public addListener(eventName: string, callback: Function, caller: any) {
if (this.callbackList[eventName]) { if (this.callbackList[eventName]) {
let eventList: Array<HaoEvent> = this.callbackList[eventName] let eventList: Array<HaoEvent> = this.callbackList[eventName]
//不同元件才放入,相同元件覆蓋 //不同元件才放入,相同元件覆蓋
let add: boolean = true let add: boolean = true
for (let i = 0; i < eventList.length; i++) { for (let i = 0; i < eventList.length; i++) {
let event: HaoEvent = eventList[i] let event: HaoEvent = eventList[i]
if (caller === event.caller) { if (caller === event.caller) {
add = false add = false
} }
} }
if (add) { if (add) {
eventList.push(new HaoEvent(callback, caller)) eventList.push(new HaoEvent(callback, caller))
this.callbackList[eventName] = eventList this.callbackList[eventName] = eventList
} }
} else { } else {
// this.callbackList[eventName] = [[callback, caller]]; // this.callbackList[eventName] = [[callback, caller]];
this.callbackList[eventName] = [new HaoEvent(callback, caller)] this.callbackList[eventName] = [new HaoEvent(callback, caller)]
} }
} }
public removeListener(eventName: string, callback: Function) { public removeListener(eventName: string, callback: Function) {
if (this.callbackList[eventName]) { if (this.callbackList[eventName]) {
for (let i = this.callbackList[eventName].length - 1; i >= 0; i--) { for (let i = this.callbackList[eventName].length - 1; i >= 0; i--) {
let event: HaoEvent = this.callbackList[eventName][i] let event: HaoEvent = this.callbackList[eventName][i]
if (event.callback == callback) { if (event.callback == callback) {
this.callbackList[eventName].splice(i, 1) this.callbackList[eventName].splice(i, 1)
break break
} }
} }
} }
} }
public dispatchEvent(eventName, parameter?: any, ...restOfName: any[]) { public dispatchEvent(eventName, parameter?: any, ...restOfName: any[]) {
let eventList: Array<HaoEvent> = this.callbackList[eventName] let eventList: Array<HaoEvent> = this.callbackList[eventName]
if (eventList) { if (eventList) {
for (let i = eventList.length - 1; i >= 0; i--) { for (let i = eventList.length - 1; i >= 0; i--) {
let event: HaoEvent = eventList[i] let event: HaoEvent = eventList[i]
event.callback.call(event.caller, event, parameter, ...restOfName) event.callback.call(event.caller, event, parameter, ...restOfName)
if (event.isStop) { if (event.isStop) {
break break
} }
} }
for (let i = eventList.length - 1; i >= 0; i--) { for (let i = eventList.length - 1; i >= 0; i--) {
let event: HaoEvent = eventList[i] let event: HaoEvent = eventList[i]
event.isStop = false event.isStop = false
} }
} }
} }
public addBtnEvent( public addBtnEvent(
parentNode: Node, parentNode: Node,
objectNode: Node, objectNode: Node,
scriptName: string, scriptName: string,
eventName: string, eventName: string,
data: any = null data: any = null
) { ) {
var btn: Button = objectNode.addComponent(Button) var btn: Button = objectNode.addComponent(Button)
var clickEventHandler = new Component.EventHandler() var clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点 clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = scriptName //这个是代码文件名 clickEventHandler.component = scriptName //这个是代码文件名
clickEventHandler.handler = eventName clickEventHandler.handler = eventName
clickEventHandler.customEventData = data clickEventHandler.customEventData = data
btn.clickEvents.push(clickEventHandler) btn.clickEvents.push(clickEventHandler)
this.addBtnEffect(objectNode) this.addBtnEffect(objectNode)
} }
public removeBtnEvent(objectNode: Node) { public removeBtnEvent(objectNode: Node) {
objectNode.removeComponent(Button) objectNode.removeComponent(Button)
} }
public removeBtnEffect(objectNode: Node) { public removeBtnEffect(objectNode: Node) {
var b = objectNode.getComponent(Button) var b = objectNode.getComponent(Button)
b.transition = Button.Transition.NONE b.transition = Button.Transition.NONE
} }
public addBtnEffect(objectNode: Node, scale: number = 1.1) { public addBtnEffect(objectNode: Node, scale: number = 1.1) {
var b = objectNode.getComponent(Button) var b = objectNode.getComponent(Button)
b.transition = Button.Transition.SCALE b.transition = Button.Transition.SCALE
b.zoomScale = scale b.zoomScale = scale
} }
public addBtnEffect_color( public addBtnEffect_color(
objectNode: Node, objectNode: Node,
normalC: Color = ColorHelper.getColor('#FFFFFF'), normalC: Color = ColorHelper.getColor('#FFFFFF'),
pressC: Color = ColorHelper.getColor('#C0C0C0') pressC: Color = ColorHelper.getColor('#C0C0C0')
) { ) {
var b = objectNode.getComponent(Button) var b = objectNode.getComponent(Button)
b.transition = Button.Transition.COLOR b.transition = Button.Transition.COLOR
b.normalColor = normalC b.normalColor = normalC
b.pressedColor = pressC b.pressedColor = pressC
} }
public addSliderEvent( public addSliderEvent(
parentNode: Node, parentNode: Node,
objectNode: Node, objectNode: Node,
EventName: string, EventName: string,
data: any data: any
) { ) {
var b = objectNode.getComponent(Slider) var b = objectNode.getComponent(Slider)
var clickEventHandler = new Component.EventHandler() var clickEventHandler = new Component.EventHandler()
clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点 clickEventHandler.target = parentNode //这个 node 节点是你的事件处理代码组件所属的节点
clickEventHandler.component = parentNode.name //这个是代码文件名 clickEventHandler.component = parentNode.name //这个是代码文件名
clickEventHandler.handler = EventName clickEventHandler.handler = EventName
clickEventHandler.customEventData = data clickEventHandler.customEventData = data
b.slideEvents.push(clickEventHandler) b.slideEvents.push(clickEventHandler)
} }
} }

View File

@@ -1,13 +1,13 @@
import { _decorator } from 'cc'
export default class Grid { export default class Grid {
public row: number public row: number
public col: number public col: number
constructor(row: number, col) {
this.row = row
this.col = col
}
public static init(row: number, col: number) { constructor(row: number, col: number) {
return new Grid(row, col) this.row = row
} this.col = col
}
public static init(row: number, col: number) {
return new Grid(row, col)
}
} }

View File

@@ -1,34 +1,31 @@
import { _decorator } from 'cc'
import { Logger } from './Logger'
export default class HaoEncrypt { export default class HaoEncrypt {
public static encode(str: string) { public static encode(str: string) {
let result: string = '' let result: string = ''
for (let i = 0; i < str.length; i++) { for (let i = 0; i < str.length; i++) {
//遍历字符串 //遍历字符串
let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值 let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值
if (i % 2 == 0) { if (i % 2 == 0) {
code += 2 code += 2
} else { } else {
code += 1 code += 1
} }
result += String.fromCharCode(code) result += String.fromCharCode(code)
} }
return result return result
} }
public static decode(str: string) { public static decode(str: string) {
let result: string = '' let result: string = ''
for (let i = 0; i < str.length; i++) { for (let i = 0; i < str.length; i++) {
//遍历字符串 //遍历字符串
let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值 let code: number = str.charCodeAt(i) // //逐个提取每个字符并获取Unicode编码值
if (i % 2 == 0) { if (i % 2 == 0) {
code -= 2 code -= 2
} else { } else {
code -= 1 code -= 1
} }
result += String.fromCharCode(code) result += String.fromCharCode(code)
} }
return result return result
} }
} }

View File

@@ -1,4 +1,4 @@
import { sys, _decorator, native, System } from 'cc' import { native, sys } from 'cc'
import { Logger } from './Logger' import { Logger } from './Logger'
import EventManager from './EventManager' import EventManager from './EventManager'
import VersionManager from './VersionManager' import VersionManager from './VersionManager'
@@ -7,326 +7,315 @@ import ResourcePreload from '../../game/utils/ResourcePreload'
import CommonTips from '../uicomponent/CommonTips' import CommonTips from '../uicomponent/CommonTips'
export default class HotUpdate { export default class HotUpdate {
public static Event_CheckUpdate: string = 'Event_CheckUpdate' public static Event_CheckUpdate: string = 'Event_CheckUpdate'
public static Event_On_Progress: string = 'HotUpdate_Event_On_Progress' public static Event_On_Progress: string = 'HotUpdate_Event_On_Progress'
public static Event_On_NeedUpdate: string = 'HotUpdate_Event_On_NeedUpdate' public static Event_On_NeedUpdate: string = 'HotUpdate_Event_On_NeedUpdate'
public static Event_Finish_Update: string = 'HotUpdate_Event_Finish' public static Event_Finish_Update: string = 'HotUpdate_Event_Finish'
public static Event_On_ALREADY_UP_TO_DATE: string = public static Event_On_ALREADY_UP_TO_DATE: string =
'HotUpdate_Event_On_ALREADY_UP_TO_DATE' 'HotUpdate_Event_On_ALREADY_UP_TO_DATE'
public static Event_On_Fail_Update: string = 'HotUpdate_Event_On_Fail_Update' public static Event_On_Fail_Update: string = 'HotUpdate_Event_On_Fail_Update'
private _am: any private _am: any
private _checkListener private _checkListener: null
private storagePath: string private storagePath: string
private manifestUrl: string private manifestUrl: string
private localBigVersion: number private localBigVersion: number
private remoteBigVersion: number private remoteBigVersion: number
public needUpdate: boolean = false public needUpdate: boolean = false
public isUpdating: boolean public isUpdating: boolean
public isFinishUpdate: boolean public isFinishUpdate: boolean
public isCheck: boolean public isCheck: boolean
private key: string private key: string
private hotupdateIndex: number private hotupdateIndex: number
constructor() {}
public init(
index: number,
key: string = 'Code-remote-asset',
manifestUrl: string
) {
if (sys.isNative) {
this.hotupdateIndex = index
this.key = key
this.manifestUrl = manifestUrl
if (false) {
//暂时不想修 fileUtils 这个报错
//暂时注释
// this.storagePath = jsb.fileUtils.getWritablePath() + key;
// if (!jsb.fileUtils.isDirectoryExist(this.storagePath)) {
// jsb.fileUtils.createDirectory(this.storagePath)
// }
} else {
this.storagePath = '获取this.storagePath报错了'
}
Logger.log(this, 'init removeDirectory=', this.storagePath + '_temp') constructor() {
} }
this.needUpdate = false
this.isUpdating = false
this.isFinishUpdate = false
this.isCheck = false
}
private jumpToPack() { public init(
let url: string index: number,
if (sys.isNative) { key: string = 'Code-remote-asset',
if (sys.os == sys.OS.ANDROID) { manifestUrl: string
url = VersionManager.instance.apkStoreUrl ) {
} else if (sys.os == sys.OS.IOS) { if (sys.isNative) {
url = VersionManager.instance.iosStoreUrl this.hotupdateIndex = index
} this.key = key
} this.manifestUrl = manifestUrl
Logger.info( this.storagePath = '获取this.storagePath报错了'
this,
'jumpToPack==androidurl===',
VersionManager.instance.apkStoreUrl
)
Logger.info(
this,
'jumpToPack==iosStoreUrl===',
VersionManager.instance.iosStoreUrl
)
Logger.info(this, 'jumpToPack=====', url)
sys.openURL(url)
// cc.game.end();
}
//显示强制更新,即更细包面板 Logger.log(this, 'init removeDirectory=', this.storagePath + '_temp')
private showPackUpdateDialog() { }
CommonTips.showMsg( this.needUpdate = false
'有新的版本需要更新,下载后请先卸载,以前的版本,再安装!' this.isUpdating = false
) this.isFinishUpdate = false
this.jumpToPack() this.isCheck = false
this.showPackUpdateDialog() }
}
private checkCb(event) { private jumpToPack() {
Logger.log(this, 'checkCb Code: =================' + event.getEventCode()) let url: string
switch (event.getEventCode()) { if (sys.isNative) {
case native.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST: if (sys.os == sys.OS.ANDROID) {
Logger.info(this, 'No local manifest file found, hot update skipped.') url = VersionManager.instance.apkStoreUrl
this.failUpdate() } else if (sys.os == sys.OS.IOS) {
break url = VersionManager.instance.iosStoreUrl
case native.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST: }
case native.EventAssetsManager.ERROR_PARSE_MANIFEST: }
Logger.info(this, 'Fail to download manifest file, hot update skipped.') Logger.info(
this.failUpdate() this,
break 'jumpToPack==androidurl===',
case native.EventAssetsManager.ALREADY_UP_TO_DATE: VersionManager.instance.apkStoreUrl
Logger.info(this, 'Already up to date with the latest remote version.') )
this.alreadyUpToDate() Logger.info(
break this,
case native.EventAssetsManager.NEW_VERSION_FOUND: 'jumpToPack==iosStoreUrl===',
Logger.info( VersionManager.instance.iosStoreUrl
this, )
'new version found, please try to update.', Logger.info(this, 'jumpToPack=====', url)
this.localBigVersion, sys.openURL(url)
this.remoteBigVersion // cc.game.end();
) }
if (
this.key == VersionManager.Config_Key[0] &&
this.localBigVersion < this.remoteBigVersion
) {
//更新大版本
Logger.info(
this,
'new version found, please try to update======packupdate=',
this.localBigVersion,
this.remoteBigVersion
)
this.showPackUpdateDialog()
} else {
Logger.info(
this,
'new version found, please try to update======hotupdate=',
this.localBigVersion,
this.remoteBigVersion
)
// this._am.update();
this.needUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_NeedUpdate,
this.key
)
}
break
case native.EventAssetsManager.UPDATE_PROGRESSION:
// var currentPercent = event.getPercent();
// var totalPercent = event.getPercentByFile();
// var fileprocess = event.getDownloadedFiles() + ' / ' + event.getTotalFiles();
// var byteprocess = event.getDownloadedBytes() + ' / ' + event.getTotalBytes();
Logger.info(
this,
'UPDATE_PROGRESSION2222==========',
this.key,
event.getDownloadedBytes(),
event.getTotalBytes()
)
if (event.getTotalBytes() > 0) {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Progress,
event.getDownloadedBytes(),
event.getTotalBytes(),
this.key
)
}
break
case native.EventAssetsManager.UPDATE_FINISHED:
Logger.info(this, 'UPDATE_FINISHED==============')
this.finishUpdate(true)
break
case native.EventAssetsManager.UPDATE_FAILED:
Logger.warn(this, 'Update failed==========', event.getMessage())
this.failUpdate()
break
case native.EventAssetsManager.ERROR_UPDATING:
let fullFilePath: string = this.storagePath + '/' + event.getAssetId()
let tempFilePath: string =
this.storagePath + '_temp/' + event.getAssetId()
Logger.warn(this, 'fullFilePath====', fullFilePath)
Logger.warn(this, 'tempFilePath====', tempFilePath)
// jsb.fileUtils.removeFile(tempFilePath);
Logger.warn(
this,
'ERROR_UPDATING=============',
event.getAssetId(),
event.getMessage()
)
this.failUpdate()
break
default:
// this.failUpdate();
return
}
}
public checkUpdate() { //显示强制更新,即更细包面板
if (this.isUpdating || this.isCheck) { private showPackUpdateDialog() {
Logger.log(this, 'Checking or updating ...') CommonTips.showMsg(
return '有新的版本需要更新,下载后请先卸载,以前的版本,再安装!'
} )
let hotupdateUrlKey: string = this.jumpToPack()
VersionManager.Config_Url_Key[this.hotupdateIndex] this.showPackUpdateDialog()
Logger.log(this, 'checkoutUpdate=====', this.manifestUrl, hotupdateUrlKey) }
if (!this._am) {
this._am = new native.AssetsManager(
'',
this.storagePath,
this.versionCompareHandle.bind(this)
)
}
// this._am.setMaxConcurrentTask(1);
let manifestStr: string = ManifestConfig.getManifestStr(hotupdateUrlKey)
Logger.log(this, 'checkUpdate=======manifestStr=======', manifestStr)
let manifest = new native.Manifest(manifestStr, this.storagePath)
this._am.setVerifyCallback(function (filePath, asset) {
return true
// var md5 = calculateMD5(filePath);
// if (md5 === asset.md5)
// return true;
// else
// return false;
})
this._am.setEventCallback(this.checkCb.bind(this))
// 设置事件回调
this.isCheck = true
this._am.loadLocalManifest(manifest, this.storagePath)
this._am.checkUpdate()
}
/** private checkCb(event: any) {
* @param versionA 本地版本 1.0.0 Logger.log(this, 'checkCb Code: =================' + event.getEventCode())
* @param versionB 服务器版本 1.0.1 switch (event.getEventCode()) {
* @param return -1需要更新 不用更新 case native.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST:
*/ Logger.info(this, 'No local manifest file found, hot update skipped.')
private versionCompareHandle(versionA, versionB) { this.failUpdate()
var vA = versionA.split('.') break
var vB = versionB.split('.') case native.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:
Logger.log( case native.EventAssetsManager.ERROR_PARSE_MANIFEST:
this, Logger.info(this, 'Fail to download manifest file, hot update skipped.')
'versionCompareHandle======', this.failUpdate()
this.key, break
VersionManager.Config_Key[0] case native.EventAssetsManager.ALREADY_UP_TO_DATE:
) Logger.info(this, 'Already up to date with the latest remote version.')
if (this.key == VersionManager.Config_Key[0]) { this.alreadyUpToDate()
Logger.log(this, 'versionCompareHandle22===', versionA, versionB) break
VersionManager.instance.nowVersion = versionA case native.EventAssetsManager.NEW_VERSION_FOUND:
VersionManager.instance.targetVersion = versionB Logger.info(
} this,
this.localBigVersion = parseInt(vA[0]) 'new version found, please try to update.',
this.remoteBigVersion = parseInt(vB[0]) this.localBigVersion,
for (var i = 0; i < vA.length; ++i) { this.remoteBigVersion
var a = parseInt(vA[i]) )
var b = parseInt(vB[i] || 0) if (
if (a === b) { this.key == VersionManager.Config_Key[0] &&
continue this.localBigVersion < this.remoteBigVersion
} else { ) {
return a - b //更新大版本
} Logger.info(
} this,
if (vB.length > vA.length) { 'new version found, please try to update======packupdate=',
return -1 this.localBigVersion,
} else { this.remoteBigVersion
return 0 )
} this.showPackUpdateDialog()
} } else {
Logger.info(
this,
'new version found, please try to update======hotupdate=',
this.localBigVersion,
this.remoteBigVersion
)
// this._am.update();
this.needUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_NeedUpdate,
this.key
)
}
break
case native.EventAssetsManager.UPDATE_PROGRESSION:
// var currentPercent = event.getPercent();
// var totalPercent = event.getPercentByFile();
// var fileprocess = event.getDownloadedFiles() + ' / ' + event.getTotalFiles();
// var byteprocess = event.getDownloadedBytes() + ' / ' + event.getTotalBytes();
Logger.info(
this,
'UPDATE_PROGRESSION2222==========',
this.key,
event.getDownloadedBytes(),
event.getTotalBytes()
)
if (event.getTotalBytes() > 0) {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Progress,
event.getDownloadedBytes(),
event.getTotalBytes(),
this.key
)
}
break
case native.EventAssetsManager.UPDATE_FINISHED:
Logger.info(this, 'UPDATE_FINISHED==============')
this.finishUpdate(true)
break
case native.EventAssetsManager.UPDATE_FAILED:
Logger.warn(this, 'Update failed==========', event.getMessage())
this.failUpdate()
break
case native.EventAssetsManager.ERROR_UPDATING:
let fullFilePath: string = this.storagePath + '/' + event.getAssetId()
let tempFilePath: string =
this.storagePath + '_temp/' + event.getAssetId()
Logger.warn(this, 'fullFilePath====', fullFilePath)
Logger.warn(this, 'tempFilePath====', tempFilePath)
// jsb.fileUtils.removeFile(tempFilePath);
Logger.warn(
this,
'ERROR_UPDATING=============',
event.getAssetId(),
event.getMessage()
)
this.failUpdate()
break
default:
// this.failUpdate();
return
}
}
public startUpdate() { public checkUpdate() {
if (this.isUpdating) return if (this.isUpdating || this.isCheck) {
let localManifest = this._am.getLocalManifest() Logger.log(this, 'Checking or updating ...')
let remoteManifest = this._am.getRemoteManifest() return
Logger.log(this, 'startUpdate111===', localManifest.getVersionFileUrl()) }
Logger.log(this, 'startUpdate2222===', localManifest.getManifestFileUrl()) let hotupdateUrlKey: string =
Logger.log(this, 'startUpdate3333===', remoteManifest.getVersionFileUrl()) VersionManager.Config_Url_Key[this.hotupdateIndex]
Logger.log(this, 'startUpdate4444===', remoteManifest.getManifestFileUrl()) Logger.log(this, 'checkoutUpdate=====', this.manifestUrl, hotupdateUrlKey)
this.isUpdating = true if (!this._am) {
EventManager.instance.dispatchEvent( this._am = new native.AssetsManager(
HotUpdate.Event_On_Progress, '',
0, this.storagePath,
100, this.versionCompareHandle.bind(this)
this.key )
) }
this._am.update() // this._am.setMaxConcurrentTask(1);
} let manifestStr: string = ManifestConfig.getManifestStr(hotupdateUrlKey)
Logger.log(this, 'checkUpdate=======manifestStr=======', manifestStr)
let manifest = new native.Manifest(manifestStr, this.storagePath)
this._am.setVerifyCallback(function(filePath, asset) {
return true
// var md5 = calculateMD5(filePath);
// if (md5 === asset.md5)
// return true;
// else
// return false;
})
this._am.setEventCallback(this.checkCb.bind(this))
// 设置事件回调
this.isCheck = true
this._am.loadLocalManifest(manifest, this.storagePath)
this._am.checkUpdate()
}
public disposeUpdate() { /**
if (this._am) { * @param versionA 本地版本 1.0.0
this._am.setVerifyCallback(null) * @param versionB 服务器版本 1.0.1
this._am.setEventCallback(null) */
} private versionCompareHandle(versionA: string, versionB: string) {
this._am = null const vA = versionA.split('.')
this._checkListener = null const vB = versionB.split('.')
this.isUpdating = false Logger.log(
this.needUpdate = false this,
} 'versionCompareHandle======',
this.key,
VersionManager.Config_Key[0]
)
if (this.key == VersionManager.Config_Key[0]) {
Logger.log(this, 'versionCompareHandle22===', versionA, versionB)
VersionManager.instance.nowVersion = versionA
VersionManager.instance.targetVersion = versionB
}
this.localBigVersion = parseInt(vA[0])
this.remoteBigVersion = parseInt(vB[0])
for (let i = 0; i < vA.length; ++i) {
const a = parseInt(vA[i])
const b = parseInt(vB[i] || '0')
if (a !== b) return a - b
}
if (vB.length > vA.length) {
return -1
} else {
return 0
}
}
private failUpdate() { public startUpdate() {
this.disposeUpdate() if (this.isUpdating) return
this.isCheck = false let localManifest = this._am.getLocalManifest()
EventManager.instance.dispatchEvent( let remoteManifest = this._am.getRemoteManifest()
HotUpdate.Event_On_Fail_Update, Logger.log(this, 'startUpdate111===', localManifest.getVersionFileUrl())
this.key Logger.log(this, 'startUpdate2222===', localManifest.getManifestFileUrl())
) Logger.log(this, 'startUpdate3333===', remoteManifest.getVersionFileUrl())
} Logger.log(this, 'startUpdate4444===', remoteManifest.getManifestFileUrl())
this.isUpdating = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_Progress,
0,
100,
this.key
)
this._am.update()
}
private alreadyUpToDate() { public disposeUpdate() {
this.disposeUpdate() if (this._am) {
this.isFinishUpdate = true this._am.setVerifyCallback(null)
EventManager.instance.dispatchEvent( this._am.setEventCallback(null)
HotUpdate.Event_On_ALREADY_UP_TO_DATE, }
this.key this._am = null
) this._checkListener = null
} this.isUpdating = false
this.needUpdate = false
}
private finishUpdate(needRestart: boolean) { private failUpdate() {
Logger.info(this, '更新完成=====', needRestart) this.disposeUpdate()
this.disposeUpdate() this.isCheck = false
this.isFinishUpdate = true EventManager.instance.dispatchEvent(
EventManager.instance.dispatchEvent( HotUpdate.Event_On_Fail_Update,
HotUpdate.Event_Finish_Update, this.key
this.key, )
needRestart }
)
if (false && needRestart) { private alreadyUpToDate() {
//暂时不想修 fileUtils 这个报错 this.disposeUpdate()
var searchPaths = '' //jsb.fileUtils.getSearchPaths();暂时注释 this.isFinishUpdate = true
Logger.info(this, '更新完成====searchPaths======', searchPaths) EventManager.instance.dispatchEvent(
sys.localStorage.setItem( HotUpdate.Event_On_ALREADY_UP_TO_DATE,
'HotUpdateSearchPaths', this.key
JSON.stringify(searchPaths) )
) }
//jsb.fileUtils.setSearchPaths(searchPaths);暂时注释
if (this.key == VersionManager.Config_Key[0]) { private finishUpdate(needRestart: boolean) {
ResourcePreload.instance.restartGame() Logger.info(this, '更新完成=====', needRestart)
} this.disposeUpdate()
} this.isFinishUpdate = true
} EventManager.instance.dispatchEvent(
HotUpdate.Event_Finish_Update,
this.key,
needRestart
)
if (false && needRestart) {
//暂时不想修 fileUtils 这个报错
var searchPaths = '' //jsb.fileUtils.getSearchPaths();暂时注释
Logger.info(this, '更新完成====searchPaths======', searchPaths)
sys.localStorage.setItem(
'HotUpdateSearchPaths',
JSON.stringify(searchPaths)
)
//jsb.fileUtils.setSearchPaths(searchPaths);暂时注释
if (this.key == VersionManager.Config_Key[0]) {
ResourcePreload.instance.restartGame()
}
}
}
} }

View File

@@ -1,160 +1,160 @@
import { _decorator } from 'cc' import { _decorator } from 'cc'
const { ccclass } = _decorator
import LoadingPrefab from '../uicomponent/LoadingPrefab'
import VersionManager from './VersionManager'
import { Logger } from './Logger' import { Logger } from './Logger'
const { ccclass } = _decorator
@ccclass('HttpClient') @ccclass('HttpClient')
export default class HttpClient { export default class HttpClient {
public static instance: HttpClient //= new HttpClient(); public static instance: HttpClient //= new HttpClient();
//example //example
// HttpClient.instance.request("http://localhost:8080/haohttp/test", ()=>{ // HttpClient.instance.request("http://localhost:8080/haohttp/test", ()=>{
// console.log("http 请求 end============="); // console.log("http 请求 end=============");
// }, {"nickName":"jhao", "hh":1, "id":9527}); // }, {"nickName":"jhao", "hh":1, "id":9527});
private methodType: string = 'GET' private methodType: string = 'GET'
private responseType: XMLHttpRequestResponseType = 'json' private responseType: XMLHttpRequestResponseType = 'json'
private xhr: XMLHttpRequest private xhr: XMLHttpRequest
// --GET or POST // --GET or POST
public setMethod(method: string = 'GET') { public setMethod(method: string = 'GET') {
this.methodType = method this.methodType = method
} }
public setParams(paramsObj: object): string { public setParams(paramsObj: object): string {
let resParams = '' let resParams = ''
let nowIndex = 1 let nowIndex = 1
for (const key in paramsObj) { for (const key in paramsObj) {
if (paramsObj.hasOwnProperty(key)) { if (paramsObj.hasOwnProperty(key)) {
if (nowIndex == 1) { if (nowIndex == 1) {
resParams += key + '=' + paramsObj[key] resParams += key + '=' + paramsObj[key]
} else { } else {
resParams += '&' + key + '=' + paramsObj[key] resParams += '&' + key + '=' + paramsObj[key]
} }
nowIndex += 1 nowIndex += 1
} }
} }
Logger.log(this, 'resParam===============', resParams) Logger.log(this, 'resParam===============', resParams)
return resParams return resParams
} }
public setResponseType(responseType: XMLHttpRequestResponseType) { public setResponseType(responseType: XMLHttpRequestResponseType) {
this.responseType = responseType this.responseType = responseType
} }
public setContentType() {} public setContentType() {
}
public request( public request(
url: string, url: string,
callback: Function, callback: Function,
params: any = null, params: any = null,
timeOut: number = 5 * 1000 timeOut: number = 5 * 1000
) { ) {
if (params && this.methodType == 'GET') { if (params && this.methodType == 'GET') {
let getParams: string = this.setParams(params) let getParams: string = this.setParams(params)
// getParams = StringUtil:encodeURI(params) // getParams = StringUtil:encodeURI(params)
getParams = encodeURI(getParams) getParams = encodeURI(getParams)
url += '?' + getParams url += '?' + getParams
} }
this.xhr = new XMLHttpRequest() // http请求 fget this.xhr = new XMLHttpRequest() // http请求 fget
//this.xhr = cc.loader.getXMLHttpRequest(); //this.xhr = cc.loader.getXMLHttpRequest();
let xhr: XMLHttpRequest = this.xhr let xhr: XMLHttpRequest = this.xhr
xhr.responseType = this.responseType xhr.responseType = this.responseType
xhr.timeout = timeOut xhr.timeout = timeOut
// xhr.setRequestHeader("Content-Type", "text/plain"); // xhr.setRequestHeader("Content-Type", "text/plain");
xhr.onreadystatechange = () => { xhr.onreadystatechange = () => {
Logger.log( Logger.log(
this, this,
'status======', 'status======',
xhr.status, xhr.status,
xhr.readyState, xhr.readyState,
xhr.statusText xhr.statusText
) )
// if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) { // if (xhr.readyState == 4 && (xhr.status >= 200 && xhr.status < 400)) {
if (xhr.readyState == 4 && xhr.status == 200) { if (xhr.readyState == 4 && xhr.status == 200) {
let response = xhr.response let response = xhr.response
Logger.log(this, 'http response1============', xhr) Logger.log(this, 'http response1============', xhr)
try { try {
let testJson = JSON.stringify(response) let testJson = JSON.stringify(response)
Logger.log(this, 'http response json============', testJson) Logger.log(this, 'http response json============', testJson)
if (callback) { if (callback) {
callback(true, response) callback(true, response)
callback = null callback = null
} }
} catch (error) { } catch (error) {
Logger.error(this, 'http response json=====error=======', error) Logger.error(this, 'http response json=====error=======', error)
if (callback) { if (callback) {
callback(false) callback(false)
callback = null callback = null
} }
} }
} else if (xhr.readyState == 4 && xhr.status == 301) { } else if (xhr.readyState == 4 && xhr.status == 301) {
//域名转移 //域名转移
Logger.log( Logger.log(
this, this,
'http response222============', 'http response222============',
xhr.getResponseHeader('Location') xhr.getResponseHeader('Location')
) )
// console.log("http response333============", xhr.getAllResponseHeaders()); // console.log("http response333============", xhr.getAllResponseHeaders());
if (HttpClient.instance == null) HttpClient.instance = new HttpClient() if (HttpClient.instance == null) HttpClient.instance = new HttpClient()
HttpClient.instance.request(xhr.getResponseHeader('Location'), callback) HttpClient.instance.request(xhr.getResponseHeader('Location'), callback)
} else if (xhr.readyState == 4 && xhr.status == 404) { } else if (xhr.readyState == 4 && xhr.status == 404) {
Logger.log(this, 'http onError============') Logger.log(this, 'http onError============')
if (callback) { if (callback) {
callback(false) callback(false)
callback = null callback = null
} }
} else { } else {
Logger.log( Logger.log(
this, this,
'onreadystatechange else====', 'onreadystatechange else====',
xhr.status, xhr.status,
xhr.readyState, xhr.readyState,
xhr.response xhr.response
) )
if (xhr.readyState == 4) { if (xhr.readyState == 4) {
Logger.log(this, 'http onError else============') Logger.log(this, 'http onError else============')
if (callback) { if (callback) {
callback(false) callback(false)
callback = null callback = null
} }
} }
} }
} }
xhr.onprogress = () => { xhr.onprogress = () => {
Logger.log( Logger.log(
this, this,
'http onprogress===', 'http onprogress===',
xhr.status, xhr.status,
xhr.readyState, xhr.readyState,
xhr.response xhr.response
) )
} }
xhr.onerror = () => { xhr.onerror = () => {
Logger.log(this, 'http onError============') Logger.log(this, 'http onError============')
if (callback) { if (callback) {
callback(false) callback(false)
callback = null callback = null
} }
} }
xhr.ontimeout = () => { xhr.ontimeout = () => {
Logger.log(this, 'http ontimeout============') Logger.log(this, 'http ontimeout============')
if (callback) { if (callback) {
callback(false) callback(false)
callback = null callback = null
} }
} }
Logger.log(this, 'http request==============', url) Logger.log(this, 'http request==============', url)
Logger.log(this, 'http request======method========', this.methodType) Logger.log(this, 'http request======method========', this.methodType)
Logger.log(this, 'http request======params========', params) Logger.log(this, 'http request======params========', params)
xhr.open(this.methodType, url, true) xhr.open(this.methodType, url, true)
xhr.setRequestHeader('content-type', 'text/plain;charset=UTF-8') xhr.setRequestHeader('content-type', 'text/plain;charset=UTF-8')
xhr.send(params) xhr.send(params)
} }
public getInfo(callback: Function = null) {} public getInfo(callback: Function = null) {
}
} }

View File

@@ -1,64 +1,63 @@
import { sys, _decorator } from 'cc' import { sys } from 'cc'
import { Logger } from './Logger'
export default class LocalStorage { export default class LocalStorage {
public static GamePreFlag: string = 'fengshen-game-HaoLocalStorage' public static GamePreFlag: string = 'fengshen-game-HaoLocalStorage'
public static setItem(key: string, value: string): void { public static setItem(key: string, value: string): void {
sys.localStorage.setItem(LocalStorage.GamePreFlag + key, value) sys.localStorage.setItem(LocalStorage.GamePreFlag + key, value)
} }
public static getItem(key: string): string { public static getItem(key: string): string {
return sys.localStorage.getItem(LocalStorage.GamePreFlag + key) return sys.localStorage.getItem(LocalStorage.GamePreFlag + key)
} }
public static removeItem(key: string): void { public static removeItem(key: string): void {
sys.localStorage.removeItem(LocalStorage.GamePreFlag + key) sys.localStorage.removeItem(LocalStorage.GamePreFlag + key)
} }
public static getInt(key: string): number { public static getInt(key: string): number {
let tempValue: string = LocalStorage.getItem(key) let tempValue: string = LocalStorage.getItem(key)
let result: number = 0 let result: number = 0
if (tempValue) { if (tempValue) {
result = parseInt(tempValue) result = parseInt(tempValue)
} }
return result return result
} }
public static setInt(key: string, value: number): void { public static setInt(key: string, value: number): void {
LocalStorage.setItem(key, value.toString()) LocalStorage.setItem(key, value.toString())
} }
public static getFloat(key: string): number { public static getFloat(key: string): number {
let tempValue: string = LocalStorage.getItem(key) let tempValue: string = LocalStorage.getItem(key)
let result: number = 0 let result: number = 0
if (tempValue) { if (tempValue) {
result = parseFloat(tempValue) result = parseFloat(tempValue)
} }
return result return result
} }
public static setFloat(key: string, value: number): void { public static setFloat(key: string, value: number): void {
LocalStorage.setItem(key, value.toString()) LocalStorage.setItem(key, value.toString())
} }
public static getBoolean(key: string): boolean { public static getBoolean(key: string): boolean {
let temp: number = LocalStorage.getInt(key) let temp: number = LocalStorage.getInt(key)
if (temp == 1) { if (temp == 1) {
return true return true
} }
return false return false
} }
public static setBoolean(key: string, value: boolean) { public static setBoolean(key: string, value: boolean) {
if (value) { if (value) {
LocalStorage.setInt(key, 1) LocalStorage.setInt(key, 1)
} else { } else {
LocalStorage.setInt(key, 0) LocalStorage.setInt(key, 0)
} }
} }
public static clear() { public static clear() {
sys.localStorage.clear() sys.localStorage.clear()
} }
} }

View File

@@ -1,133 +1,138 @@
import { error, _decorator } from 'cc'
class LOG_LEVEL_TYPES { class LOG_LEVEL_TYPES {
public static DEBUG = 0 public static DEBUG = 0
public static LOG = 1 public static LOG = 1
public static INFO = 2 public static INFO = 2
public static WARN = 3 public static WARN = 3
public static ERROR = 4 public static ERROR = 4
} }
const Log_Level_Names: Array<string> = ['debug', 'log', 'info', 'warn', 'error'] const Log_Level_Names: Array<string> = ['debug', 'log', 'info', 'warn', 'error']
export class Logger { export class Logger {
public static tag: string = '[HaoJslog]' //可以设置当前游戏的前缀 public static tag: string = '[HaoJslog]' //可以设置当前游戏的前缀
public static LEVEL: number = LOG_LEVEL_TYPES.WARN //当前Logger等级 public static LEVEL: number = LOG_LEVEL_TYPES.WARN //当前Logger等级
public static Log_Color_Config: Array<string> = [ public static Log_Color_Config: Array<string> = [
'color:#890;font-size:10px;', 'color:#890;font-size:10px;',
'color:#000;font-size:11px;', 'color:#000;font-size:11px;',
'color:#09f;font-size:12px;', 'color:#09f;font-size:12px;',
'color:#f90;font-size:13px;', 'color:#f90;font-size:13px;',
'color:#f00;font-size:15px;', 'color:#f00;font-size:15px;'
] ]
private static Terminal_Log: boolean = false private static Terminal_Log: boolean = false
public static formatNow() {
let date: Date = new Date() //后端返回的时间戳是秒 public static formatNow() {
return ( let date: Date = new Date() //后端返回的时间戳是秒
date.getFullYear() + return (
'-' + date.getFullYear() +
(date.getMonth() + 1) + '-' +
'-' + (date.getMonth() + 1) +
date.getDate() + '-' +
' ' + date.getDate() +
date.getHours() + ' ' +
':' + date.getHours() +
date.getMinutes() + ':' +
':' + date.getMinutes() +
date.getSeconds() + ':' +
':' + date.getSeconds() +
date.getMilliseconds() ':' +
) date.getMilliseconds()
} )
private static getLogPreKey(nowLevel: number): string { }
let str: string =
'[' + private static getLogPreKey(nowLevel: number): string {
Logger.formatNow() + return '[' +
'] ' + Logger.formatNow() +
Logger.tag + '] ' +
' [' + Logger.tag +
Log_Level_Names[nowLevel] + ' [' +
'] ' Log_Level_Names[nowLevel] +
return str '] '
} }
public static debug(...params: any) {
if (Logger.LEVEL > LOG_LEVEL_TYPES.DEBUG) { public static debug(...params: any) {
return if (Logger.LEVEL > LOG_LEVEL_TYPES.DEBUG) {
} return
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.DEBUG) }
let fileStr: string = str + params.join(' ') let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.DEBUG)
// LogErrorFileUtil.debug(fileStr); let fileStr: string = str + params.join(' ')
if (this.Terminal_Log) { // LogErrorFileUtil.debug(fileStr);
console.log( if (this.Terminal_Log) {
'%c' + str, console.log(
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], '%c' + str,
...params this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
) ...params
} else { )
console.info(fileStr) } else {
} console.info(fileStr)
} }
public static log(...params: any) { }
if (Logger.LEVEL > LOG_LEVEL_TYPES.LOG) {
return public static log(...params: any) {
} if (Logger.LEVEL > LOG_LEVEL_TYPES.LOG) {
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.LOG) return
let fileStr: string = str + params.join(' ') }
// LogErrorFileUtil.log(fileStr); let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.LOG)
if (this.Terminal_Log) { let fileStr: string = str + params.join(' ')
console.log( // LogErrorFileUtil.log(fileStr);
'%c' + str, if (this.Terminal_Log) {
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], console.log(
...params '%c' + str,
) this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
} else { ...params
console.info(fileStr) //console.log(str, ...params) )
} } else {
} console.info(fileStr) //console.log(str, ...params)
public static info(...params: any) { }
if (Logger.LEVEL > LOG_LEVEL_TYPES.INFO) { }
return
} public static info(...params: any) {
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.INFO) if (Logger.LEVEL > LOG_LEVEL_TYPES.INFO) {
let fileStr: string = str + params.join(' ') return
if (this.Terminal_Log) { }
console.info( let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.INFO)
'%c' + str, let fileStr: string = str + params.join(' ')
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], if (this.Terminal_Log) {
...params console.info(
) '%c' + str,
} else { this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
console.info(fileStr) ...params
} )
} } else {
public static warn(...params: any) { console.info(fileStr)
if (Logger.LEVEL > LOG_LEVEL_TYPES.WARN) { }
return }
}
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.WARN) public static warn(...params: any) {
let fileStr: string = str + params.join(' ') if (Logger.LEVEL > LOG_LEVEL_TYPES.WARN) {
if (this.Terminal_Log) { return
console.warn( }
'%c' + str, let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.WARN)
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], let fileStr: string = str + params.join(' ')
...params if (this.Terminal_Log) {
) console.warn(
} else { '%c' + str,
console.warn(fileStr) this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
} ...params
} )
public static error(...params: any) { } else {
if (Logger.LEVEL > LOG_LEVEL_TYPES.ERROR) { console.warn(fileStr)
return }
} }
let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.ERROR)
let fileStr: string = str + params.join(' ') public static error(...params: any) {
if (this.Terminal_Log) { if (Logger.LEVEL > LOG_LEVEL_TYPES.ERROR) {
console.error( return
'%c' + str, }
this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG], let str: string = this.getLogPreKey(LOG_LEVEL_TYPES.ERROR)
...params let fileStr: string = str + params.join(' ')
) if (this.Terminal_Log) {
} else { console.error(
console.error(fileStr) '%c' + str,
} this.Log_Color_Config[LOG_LEVEL_TYPES.DEBUG],
} ...params
)
} else {
console.error(fileStr)
}
}
} }

View File

@@ -1,61 +1,64 @@
import { _decorator, Vec2 } from 'cc' import { Vec2 } from 'cc'
export default class MathUtils { export default class MathUtils {
/** /**
* 2个点之前的直线距离 * 2个点之前的直线距离
* @param p1 * @param x1
* @param p2 * @param y1
*/ * @param x2
public static distance(x1: number, y1: number, x2: number, y2: number) { * @param y2
// 设两点AX1,Y1,BX2,Y2 */
// 距离D=X2-X1的平方+Y2-Y1平方的和开平方 public static distance(x1: number, y1: number, x2: number, y2: number) {
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)) // 设两点AX1,Y1,BX2,Y2
} // 距离D=X2-X1的平方+Y2-Y1平方的和开平方
return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2))
}
/** /**
* 2点间的向量 * 2点间的向量
* @param p1 * @param p1
* @param p2 * @param p2
*/ */
public static sub(p1: Vec2, p2: Vec2) { public static sub(p1: Vec2, p2: Vec2) {
return new Vec2(p1.x - p2.x, p1.y - p2.y) return new Vec2(p1.x - p2.x, p1.y - p2.y)
} }
/** /**
* 弧度转角度 * 弧度转角度
* @param radians * @param radians
*/ */
public static radiansToDegrees(radians: number) { public static radiansToDegrees(radians: number) {
return (180 / Math.PI) * radians return (180 / Math.PI) * radians
} }
/** /**
* 角度转弧度 * 角度转弧度
* @param degrees * @param degrees
*/ */
public static degreesToRadians(degrees: number) { public static degreesToRadians(degrees: number) {
return (Math.PI * degrees) / 180 return (Math.PI * degrees) / 180
} }
/** /**
* 返回2点间的弧度 * 返回2点间的弧度
* @param startP * @param startP
* @param endP * @param endP
*/ */
public static p2pRad(startP: Vec2, endP: Vec2) { public static p2pRad(startP: Vec2, endP: Vec2) {
let rad: number = Math.atan2(endP.y - startP.y, endP.x - startP.x) let rad: number = Math.atan2(endP.y - startP.y, endP.x - startP.x)
return rad return rad
} }
/** /**
* 针对捕鱼鱼的方向特定实现的鱼方向转换 * 针对捕鱼鱼的方向特定实现的鱼方向转换
* @param rot * @param rot
*/ */
public static rotation2Fish(rot: number) { public static rotation2Fish(rot: number) {
if (rot >= 0 && rot <= 180) { if (rot >= 0 && rot <= 180) {
rot = 180 - rot rot = 180 - rot
} else { } else {
rot = -180 - rot rot = -180 - rot
} }
return rot return rot
} }
} }

View File

@@ -1,62 +1,62 @@
import { _decorator, Node, Vec3, Vec2 } from 'cc' import { Node, Vec2, Vec3 } from 'cc'
import { Logger } from './Logger'
import MathUtils from './MathUtils' import MathUtils from './MathUtils'
export class MoveHelper { export class MoveHelper {
public static _vec3: Vec3 = new Vec3() public static _vec3: Vec3 = new Vec3()
public static _vec2_0: Vec2 = new Vec2() public static _vec2_0: Vec2 = new Vec2()
public static _vec2_1: Vec2 = new Vec2() public static _vec2_1: Vec2 = new Vec2()
public static moveNode(
moveNode: Node, public static moveNode(
speed: number, moveNode: Node,
tx: number, speed: number,
ty: number, tx: number,
minSpeed: number = 0.01 ty: number,
) { minSpeed: number = 0.01
let isMoving: boolean = false ) {
let times: number = 0 let isMoving: boolean = false
moveNode.getPosition(MoveHelper._vec3) let times: number = 0
MoveHelper._vec2_0.x = MoveHelper._vec3.x moveNode.getPosition(MoveHelper._vec3)
MoveHelper._vec2_0.y = MoveHelper._vec3.y MoveHelper._vec2_0.x = MoveHelper._vec3.x
MoveHelper._vec2_1.x = tx MoveHelper._vec2_0.y = MoveHelper._vec3.y
MoveHelper._vec2_1.y = ty MoveHelper._vec2_1.x = tx
let rad: number = MathUtils.p2pRad(MoveHelper._vec2_0, MoveHelper._vec2_1) MoveHelper._vec2_1.y = ty
let speedX: number = speed * Math.cos(rad) let rad: number = MathUtils.p2pRad(MoveHelper._vec2_0, MoveHelper._vec2_1)
let speedY: number = speed * Math.sin(rad) let speedX: number = speed * Math.cos(rad)
if (Math.abs(MoveHelper._vec3.x - tx) > minSpeed) { let speedY: number = speed * Math.sin(rad)
times = Math.floor(Math.abs(speedX / minSpeed)) if (Math.abs(MoveHelper._vec3.x - tx) > minSpeed) {
for (let i = 0; i < times; i++) { times = Math.floor(Math.abs(speedX / minSpeed))
if (MoveHelper._vec3.x > tx) { for (let i = 0; i < times; i++) {
MoveHelper._vec3.x -= minSpeed if (MoveHelper._vec3.x > tx) {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.x -= minSpeed
} else { moveNode.setPosition(MoveHelper._vec3)
MoveHelper._vec3.x += minSpeed } else {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.x += minSpeed
} moveNode.setPosition(MoveHelper._vec3)
if (Math.abs(MoveHelper._vec3.x - tx) <= minSpeed * 2) { }
MoveHelper._vec3.x = tx if (Math.abs(MoveHelper._vec3.x - tx) <= minSpeed * 2) {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.x = tx
} moveNode.setPosition(MoveHelper._vec3)
} }
isMoving = true }
} isMoving = true
if (Math.abs(MoveHelper._vec3.y - ty) > minSpeed) { }
times = Math.floor(Math.abs(speedY / minSpeed)) if (Math.abs(MoveHelper._vec3.y - ty) > minSpeed) {
for (let j = 0; j < times; j++) { times = Math.floor(Math.abs(speedY / minSpeed))
if (MoveHelper._vec3.y > ty) { for (let j = 0; j < times; j++) {
MoveHelper._vec3.y -= minSpeed if (MoveHelper._vec3.y > ty) {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.y -= minSpeed
} else { moveNode.setPosition(MoveHelper._vec3)
MoveHelper._vec3.y += minSpeed } else {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.y += minSpeed
} moveNode.setPosition(MoveHelper._vec3)
if (Math.abs(MoveHelper._vec3.x - ty) <= minSpeed * 2) { }
MoveHelper._vec3.y = ty if (Math.abs(MoveHelper._vec3.x - ty) <= minSpeed * 2) {
moveNode.setPosition(MoveHelper._vec3) MoveHelper._vec3.y = ty
} moveNode.setPosition(MoveHelper._vec3)
} }
isMoving = true }
} isMoving = true
return isMoving }
} return isMoving
}
} }

View File

@@ -1,30 +1,30 @@
import { AssetManager, Prefab, _decorator } from 'cc' import { _decorator, AssetManager, Prefab } from 'cc'
const { ccclass, property } = _decorator
import { Logger } from './Logger' import { Logger } from './Logger'
const { ccclass, property } = _decorator
@ccclass('PrefabLoader') @ccclass('PrefabLoader')
export default class PrefabLoader { export default class PrefabLoader {
private static isLoading: boolean = false private static isLoading: boolean = false
public static loadPrefab(url: string, callback: Function) { public static loadPrefab(url: string, callback: Function) {
if (this.isLoading) return if (this.isLoading) return
this.isLoading = true this.isLoading = true
AssetManager.instance.resources.load( AssetManager.instance.resources.load(
url, url,
Prefab, Prefab,
(error: Error, loadedResource) => { (error: Error, loadedResource) => {
if (error) { if (error) {
Logger.warn(this, '载入Prefab失败, 原因:', url, error.message) Logger.warn(this, '载入Prefab失败, 原因:', url, error.message)
return return
} }
if (!(loadedResource instanceof Prefab)) { if (!(loadedResource instanceof Prefab)) {
Logger.warn(this, '你载入的不是Prefab, 你做了什么事?') Logger.warn(this, '你载入的不是Prefab, 你做了什么事?')
return return
} }
callback(loadedResource) callback(loadedResource)
this.isLoading = false this.isLoading = false
} }
) )
} }
} }

View File

@@ -1,50 +1,49 @@
import { Vec2, _decorator } from 'cc' import { Vec2 } from 'cc'
export default class RandomUtil { export default class RandomUtil {
//随机minNum到maxNum的数字 包含maxNum //随机minNum到maxNum的数字 包含maxNum
public static nextInt(minNum: number, maxNum: number) { public static nextInt(minNum: number, maxNum: number) {
return Math.floor(Math.random() * (maxNum - minNum + 1) + minNum) return Math.floor(Math.random() * (maxNum - minNum + 1) + minNum)
} }
public static nextNumber(minNum: number, maxNum: number) { public static nextNumber(minNum: number, maxNum: number) {
return Math.random() * (maxNum - minNum) + minNum return Math.random() * (maxNum - minNum) + minNum
} }
public static nextSign() { public static nextSign() {
let temp = Math.random() let temp = Math.random()
if (temp < 0.5) { if (temp < 0.5) {
return 1 return 1
} }
return -1 return -1
} }
public static nextBoolean() { public static nextBoolean() {
let temp = Math.random() let temp = Math.random()
if (temp < 0.5) { return temp < 0.5;
return true
}
return false
}
public static randomArr(nowArr: Array<any>, needNum: number) { }
let tempArr: Array<any> = nowArr.concat()
let resultArr: Array<any> = []
for (let index = 0; index < needNum; index++) {
if (tempArr.length <= 0) {
break
}
let randomIndex: number = RandomUtil.nextInt(0, tempArr.length - 1)
resultArr.push(tempArr.splice(randomIndex, 1)[0])
}
return resultArr
}
public static randomItem(nowArr: Array<any>) { public static randomArr(nowArr: Array<any>, needNum: number) {
return this.randomArr(nowArr, 1)[0] let tempArr: Array<any> = nowArr.concat()
} let resultArr: Array<any> = []
for (let index = 0; index < needNum; index++) {
if (tempArr.length <= 0) {
break
}
let randomIndex: number = RandomUtil.nextInt(0, tempArr.length - 1)
resultArr.push(tempArr.splice(randomIndex, 1)[0])
}
return resultArr
}
public static randomP(left: number, right: number, up: number, down: number) { public static randomItem(nowArr: Array<any>) {
let randomX: number = RandomUtil.nextNumber(left, right) return this.randomArr(nowArr, 1)[0]
let randomY: number = RandomUtil.nextNumber(up, down) }
return new Vec2(randomX, randomY)
} public static randomP(left: number, right: number, up: number, down: number) {
let randomX: number = RandomUtil.nextNumber(left, right)
let randomY: number = RandomUtil.nextNumber(up, down)
return new Vec2(randomX, randomY)
}
} }

View File

@@ -1,436 +1,428 @@
import { import { Color, Material, Node, UIRenderer, UITransform, Vec2 } from 'cc'
_decorator,
Node,
Material,
Color,
UIRenderer,
Vec2,
UITransform,
} from 'cc'
import ShaderMaterialPrefab from '../../game/prefab/ShaderMaterialPrefab' import ShaderMaterialPrefab from '../../game/prefab/ShaderMaterialPrefab'
import { Logger } from './Logger'
export default class ShaderHelper { export default class ShaderHelper {
/** /**
* 清除所有shader * 清除所有shader
* @param showNode * @param showNode
* @param material * @param material
*/ */
public static clearAllEffect( public static clearAllEffect(
showNode: Node, showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).default ).default
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 设置图片灰白程度 * 设置图片灰白程度
* @param showNode * @param showNode
* @param material * @param grayLevel
* @param grayLevel [0.0, 1.0] * @param material
*/ */
public static setGrayEffect( public static setGrayEffect(
showNode: Node, showNode: Node,
grayLevel: number = 1, grayLevel: number = 1,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).grayMaterial ).grayMaterial
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel) material.setProperty('grayLevel', grayLevel)
renderComponent.setMaterial(material, 0) renderComponent.setMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('grayLevel', grayLevel) material.setProperty('grayLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 播放变灰过程动画 * 播放变灰过程动画
*/ */
public static showGrayMv(showNode: Node) { public static showGrayMv(showNode: Node) {
let grayValue: number = 0.5 let grayValue: number = 0.5
let intervalId = setInterval(() => { let intervalId = setInterval(() => {
grayValue += 0.01 grayValue += 0.01
if (grayValue >= 1) { if (grayValue >= 1) {
grayValue = 1 grayValue = 1
clearInterval(intervalId) clearInterval(intervalId)
} }
if (showNode) { if (showNode) {
ShaderHelper.setGrayEffect(showNode, grayValue) ShaderHelper.setGrayEffect(showNode, grayValue)
} }
}, 1) }, 1)
} }
/** /**
* 设置图片老化 * 设置图片老化
* @param showNode * @param showNode
* @param grayLevel [0.0, 1.0] * @param grayLevel
* @param material * @param material
*/ */
public static setOldPhotoEffect( public static setOldPhotoEffect(
showNode: Node, showNode: Node,
grayLevel: number = 1, grayLevel: number = 1,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).oldPhoto ).oldPhoto
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('oldLevel', grayLevel) material.setProperty('oldLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('oldLevel', grayLevel) material.setProperty('oldLevel', grayLevel)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 播放变灰过程动画 * 播放变灰过程动画
*/ */
public static showOldPhotoMv(showNode: Node) { public static showOldPhotoMv(showNode: Node) {
let grayValue: number = 0 let grayValue: number = 0
let intervalId = setInterval(() => { let intervalId = setInterval(() => {
grayValue += 0.01 grayValue += 0.01
if (grayValue >= 1) { if (grayValue >= 1) {
grayValue = 1 grayValue = 1
clearInterval(intervalId) clearInterval(intervalId)
} }
if (showNode) { if (showNode) {
ShaderHelper.setOldPhotoEffect(showNode, grayValue) ShaderHelper.setOldPhotoEffect(showNode, grayValue)
} }
}, 1) }, 1)
} }
/** /**
* 增加内发光特效 * 增加内发光特效
* showNode:要增加特效的节点或者他的子节点 * showNode:要增加特效的节点或者他的子节点
* material:发光特效材质 * material:发光特效材质
* materialParam: {} * materialParam: {}
* materialParam.glowColor:cc.v4(r,g,b,a) 颜色rbga值的结构体 * materialParam.glowColor:cc.v4(r,g,b,a) 颜色rbga值的结构体
* materialParam.glowColorSize:这里为约束一下值发光宽度值在 [0.0, 0.1] 因为 0.1+ 之后的效果可能不明显,也可以自己尝试修改,个人测试感觉0.01效果最佳 * materialParam.glowColorSize:这里为约束一下值发光宽度值在 [0.0, 0.1] 因为 0.1+ 之后的效果可能不明显,也可以自己尝试修改,个人测试感觉0.01效果最佳
* materialParam.glowThreshold:这里为约束一下值发光阈值值在 [0.0, 0.5] 因为 0.5+ 之后的效果可能就是其他效果个人感觉0.1效果最佳 * materialParam.glowThreshold:这里为约束一下值发光阈值值在 [0.0, 0.5] 因为 0.5+ 之后的效果可能就是其他效果个人感觉0.1效果最佳
*/ */
public static setGlowInner( public static setGlowInner(
showNode: Node, showNode: Node,
materialParam: any, materialParam: any,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).glowInner ).glowInner
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('glowColor', materialParam.glowColor) material.setProperty('glowColor', materialParam.glowColor)
material.setProperty('glowColorSize', materialParam.glowColorSize) material.setProperty('glowColorSize', materialParam.glowColorSize)
material.setProperty('glowThreshold', materialParam.glowThreshold) material.setProperty('glowThreshold', materialParam.glowThreshold)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('glowColor', materialParam.glowColor) material.setProperty('glowColor', materialParam.glowColor)
material.setProperty('glowColorSize', materialParam.glowColorSize) material.setProperty('glowColorSize', materialParam.glowColorSize)
material.setProperty('glowThreshold', materialParam.glowThreshold) material.setProperty('glowThreshold', materialParam.glowThreshold)
renderComponent.setMaterial(material, 0) renderComponent.setMaterial(material, 0)
}) })
}) })
} }
/** /**
* 设置不同颜色的发光 * 设置不同颜色的发光
* @param showNode * @param showNode
* @param color * @param color
*/ */
public static setCommonGlowInner(showNode: Node, color: Color = Color.WHITE) { public static setCommonGlowInner(showNode: Node, color: Color = Color.WHITE) {
this.setGlowInner(showNode, { this.setGlowInner(showNode, {
glowColor: color, glowColor: color,
glowColorSize: 0.015, glowColorSize: 0.015,
glowThreshold: 0.1, glowThreshold: 0.1
}) })
} }
/** /**
* 播放被攻击闪烁过程动画 * 播放被攻击闪烁过程动画
*/ */
public static showFlash(showNode: Node, totalFlashTimes: number = 1) { public static showFlash(showNode: Node, totalFlashTimes: number = 1) {
let timeCount: number = 0 let timeCount: number = 0
let color: Color = Color.WHITE let color: Color = Color.WHITE
let flashTimes: number = 0 let flashTimes: number = 0
let intervalId = setInterval(() => { let intervalId = setInterval(() => {
timeCount += 1 timeCount += 1
if (timeCount % 50 == 0) { if (timeCount % 50 == 0) {
let tempCount: number = timeCount / 50 let tempCount: number = timeCount / 50
if (tempCount % 2 == 0) { if (tempCount % 2 == 0) {
color.a = 100 color.a = 100
this.setGlowInner(showNode, { this.setGlowInner(showNode, {
glowColor: color, glowColor: color,
glowColorSize: 0.1, glowColorSize: 0.1,
glowThreshold: 0, glowThreshold: 0
}) })
} else { } else {
flashTimes++ flashTimes++
this.setGlowInner(showNode, { this.setGlowInner(showNode, {
glowColor: color, glowColor: color,
glowColorSize: 0, glowColorSize: 0,
glowThreshold: 0, glowThreshold: 0
}) })
if (flashTimes > totalFlashTimes) { if (flashTimes > totalFlashTimes) {
clearInterval(intervalId) clearInterval(intervalId)
} }
} }
} }
}, 1) }, 1)
} }
/** /**
* 马赛克 * 马赛克
* @param showNode * @param showNode
* @param materialParam * @param materialParam
* @param material * @param material
*/ */
public static setMosaic( public static setMosaic(
showNode: Node, showNode: Node,
materialParam: any, materialParam: any,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).mosaic ).mosaic
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('xBlockCount', materialParam.xBlockCount) material.setProperty('xBlockCount', materialParam.xBlockCount)
material.setProperty('yBlockCount', materialParam.yBlockCount) material.setProperty('yBlockCount', materialParam.yBlockCount)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('xBlockCount', materialParam.xBlockCount) material.setProperty('xBlockCount', materialParam.xBlockCount)
material.setProperty('yBlockCount', materialParam.yBlockCount) material.setProperty('yBlockCount', materialParam.yBlockCount)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 播放被攻击闪烁过程动画 * 播放被攻击闪烁过程动画
*/ */
public static showMosaicMv(showNode: Node, callback: Function = null) { public static showMosaicMv(showNode: Node, callback: Function = null) {
let masaicTimes: number = 500 let masaicTimes: number = 500
let intervalId = setInterval(() => { let intervalId = setInterval(() => {
masaicTimes -= 2 masaicTimes -= 2
this.setMosaic(showNode, { this.setMosaic(showNode, {
xBlockCount: masaicTimes, xBlockCount: masaicTimes,
yBlockCount: masaicTimes, yBlockCount: masaicTimes
}) })
if (masaicTimes <= 30) { if (masaicTimes <= 30) {
clearInterval(intervalId) clearInterval(intervalId)
if (callback) { if (callback) {
callback() callback()
} }
} }
}, 1) }, 1)
} }
/** /**
* 设置圆角剪切 * 设置圆角剪切
* @param showNode * @param showNode
* @param roundCornerRadius [0, 1] * @param roundCornerRadius
*/ * @param material
public static setRoundCornerCrop( */
showNode: Node, public static setRoundCornerCrop(
roundCornerRadius: number = 0.1, showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent( roundCornerRadius: number = 0.1,
ShaderMaterialPrefab material: Material = ShaderMaterialPrefab.instance.getComponent(
).roundCornerCrop ShaderMaterialPrefab
) { ).roundCornerCrop
showNode ) {
.getComponents(UIRenderer) showNode
.forEach((renderComponent: UIRenderer) => { .getComponents(UIRenderer)
// material.setProperty("roundCornerRadius", roundCornerRadius); .forEach((renderComponent: UIRenderer) => {
material.setProperty('xRadius', roundCornerRadius) // material.setProperty("roundCornerRadius", roundCornerRadius);
material.setProperty('yRadius', roundCornerRadius) material.setProperty('xRadius', roundCornerRadius)
renderComponent.setSharedMaterial(material, 0) material.setProperty('yRadius', roundCornerRadius)
}) renderComponent.setSharedMaterial(material, 0)
showNode.children.forEach((childNode) => { })
childNode showNode.children.forEach((childNode) => {
.getComponents(UIRenderer) childNode
.forEach((renderComponent: UIRenderer) => { .getComponents(UIRenderer)
// material.setProperty("roundCornerRadius", roundCornerRadius); .forEach((renderComponent: UIRenderer) => {
material.setProperty('xRadius', roundCornerRadius) // material.setProperty("roundCornerRadius", roundCornerRadius);
material.setProperty('yRadius', roundCornerRadius) material.setProperty('xRadius', roundCornerRadius)
renderComponent.setSharedMaterial(material, 0) material.setProperty('yRadius', roundCornerRadius)
}) renderComponent.setSharedMaterial(material, 0)
}) })
} })
}
/** /**
* 设置闪光 * 设置闪光
* @param showNode * @param showNode
* @param lightColor 光颜色 * @param lightColor 光颜色
* @param lightWidth 光的宽度 * @param lightWidth 光的宽度
* @param lightAngle 光的角度 * @param lightAngle 光的角度
* @param enableGradient * @param enableGradient
* @param cropAlpha * @param cropAlpha
* @param enableFog * @param enableFog
* @param material * @param material
*/ */
public static setFlashLight( public static setFlashLight(
showNode: Node, showNode: Node,
lightColor: Color, lightColor: Color,
lightWidth: number, lightWidth: number,
lightAngle: number = 0, lightAngle: number = 0,
enableGradient: boolean = true, enableGradient: boolean = true,
cropAlpha: boolean = true, cropAlpha: boolean = true,
enableFog: boolean = false, enableFog: boolean = false,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).flashLight ).flashLight
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('lightColor', lightColor) material.setProperty('lightColor', lightColor)
material.setProperty('lightWidth', lightWidth) material.setProperty('lightWidth', lightWidth)
material.setProperty('lightAngle', lightAngle) material.setProperty('lightAngle', lightAngle)
material.setProperty('enableGradient', enableGradient ? 1 : 0) material.setProperty('enableGradient', enableGradient ? 1 : 0)
material.setProperty('cropAlpha', cropAlpha ? 1 : 0) material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
material.setProperty('enableFog', enableFog ? 1 : 0) material.setProperty('enableFog', enableFog ? 1 : 0)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
material.setProperty('lightColor', lightColor) material.setProperty('lightColor', lightColor)
material.setProperty('lightWidth', lightWidth) material.setProperty('lightWidth', lightWidth)
material.setProperty('lightAngle', lightAngle) material.setProperty('lightAngle', lightAngle)
material.setProperty('enableGradient', enableGradient ? 1 : 0) material.setProperty('enableGradient', enableGradient ? 1 : 0)
material.setProperty('cropAlpha', cropAlpha ? 1 : 0) material.setProperty('cropAlpha', cropAlpha ? 1 : 0)
material.setProperty('enableFog', enableFog ? 1 : 0) material.setProperty('enableFog', enableFog ? 1 : 0)
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 玩家升级shader动画 * 玩家升级shader动画
* @param showNode * @param showNode
* @param callback * @param callback
*/ */
public static showFlashLightMv(showNode: Node, callback: Function = null) { public static showFlashLightMv(showNode: Node, callback: Function = null) {
let nowClor: Color = new Color(0, 0, 0, 255) let nowClor: Color = new Color(0, 0, 0, 255)
let colorIndex: number = 0 let colorIndex: number = 0
let lightAngle: number = 0 let lightAngle: number = 0
let intervalId = setInterval(() => { let intervalId = setInterval(() => {
if (colorIndex == 0) { if (colorIndex == 0) {
nowClor.r = nowClor.r + 2 nowClor.r = nowClor.r + 2
if (nowClor.r >= 255) { if (nowClor.r >= 255) {
colorIndex += 1 colorIndex += 1
} }
} else if (colorIndex == 1) { } else if (colorIndex == 1) {
nowClor.g = nowClor.g + 2 nowClor.g = nowClor.g + 2
if (nowClor.g >= 255) { if (nowClor.g >= 255) {
colorIndex += 1 colorIndex += 1
} }
} else { } else {
nowClor.b = nowClor.b + 2 nowClor.b = nowClor.b + 2
if (nowClor.b >= 255) { if (nowClor.b >= 255) {
clearInterval(intervalId) clearInterval(intervalId)
ShaderHelper.clearAllEffect(showNode) ShaderHelper.clearAllEffect(showNode)
if (callback) { if (callback) {
callback() callback()
} }
return return
} }
} }
lightAngle += 1 lightAngle += 1
this.setFlashLight(showNode, nowClor, 1, lightAngle) this.setFlashLight(showNode, nowClor, 1, lightAngle)
}, 1) }, 1)
} }
public static setFlag( public static setFlag(
showNode: Node, showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).flag ).flag
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
/** /**
* 设置高斯模糊 * 设置高斯模糊
* @param showNode * @param showNode
* @param material * @param material
*/ */
public static setGaussian( public static setGaussian(
showNode: Node, showNode: Node,
material: Material = ShaderMaterialPrefab.instance.getComponent( material: Material = ShaderMaterialPrefab.instance.getComponent(
ShaderMaterialPrefab ShaderMaterialPrefab
).gaussian ).gaussian
) { ) {
showNode showNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
let tran = renderComponent.node.getComponent(UITransform) let tran = renderComponent.node.getComponent(UITransform)
material.setProperty( material.setProperty(
'textureSize', 'textureSize',
new Vec2(tran.contentSize.width, tran.contentSize.height) new Vec2(tran.contentSize.width, tran.contentSize.height)
) )
renderComponent.setMaterial(material, 0) renderComponent.setMaterial(material, 0)
}) })
showNode.children.forEach((childNode) => { showNode.children.forEach((childNode) => {
childNode childNode
.getComponents(UIRenderer) .getComponents(UIRenderer)
.forEach((renderComponent: UIRenderer) => { .forEach((renderComponent: UIRenderer) => {
let tran = renderComponent.node.getComponent(UITransform) let tran = renderComponent.node.getComponent(UITransform)
material.setProperty( material.setProperty(
'textureSize', 'textureSize',
new Vec2(tran.contentSize.width, tran.contentSize.height) new Vec2(tran.contentSize.width, tran.contentSize.height)
) )
// material.setProperty("textureSize", cc.v2(showNode.width, showNode.height)); // material.setProperty("textureSize", cc.v2(showNode.width, showNode.height));
renderComponent.setSharedMaterial(material, 0) renderComponent.setSharedMaterial(material, 0)
}) })
}) })
} }
} }

View File

@@ -1,139 +1,140 @@
import { sys, _decorator } from 'cc' import { sys } from 'cc'
import ManifestConfig from '../config/ManifestConfig' import ManifestConfig from '../config/ManifestConfig'
import EventManager from './EventManager' import EventManager from './EventManager'
import HotUpdate from './HotUpdate' import HotUpdate from './HotUpdate'
export default class VersionManager { export default class VersionManager {
public static instance: VersionManager = new VersionManager() public static instance: VersionManager = new VersionManager()
public static Config_Game_Name: Array<string> = ['游戏大厅'] public static Config_Game_Name: Array<string> = ['游戏大厅']
//热更文件下载来后存放文件夹 //热更文件下载来后存放文件夹
public static Config_Key: Array<string> = ['main-remote-asset'] public static Config_Key: Array<string> = ['main-remote-asset']
private static Config_ManifestName: string = 'project.manifest' private static Config_ManifestName: string = 'project.manifest'
public static Config_Url_Key: Array<string> = ['main'] public static Config_Url_Key: Array<string> = ['main']
public iosStoreUrl: string = '' public iosStoreUrl: string = ''
public apkStoreUrl: string = '' public apkStoreUrl: string = ''
public nowVersion: string = ManifestConfig.version //网页显示版本号,如果是热更会替换改值 public nowVersion: string = ManifestConfig.version //网页显示版本号,如果是热更会替换改值
public targetVersion: string = '1.0.0' public targetVersion: string = '1.0.0'
public isOpenHotUpdate: boolean = true //是否打开热更 public isOpenHotUpdate: boolean = true //是否打开热更
private hotUpdateList: Array<HotUpdate> = [] private hotUpdateList: Array<HotUpdate> = []
private noUpdateIndex: number = -1 // private noUpdateIndex: number = -1 //
public init() { public init() {
this.reInitAll() this.reInitAll()
} }
public reInitAll() {
this.releaseAll()
for (let i = 0; i < VersionManager.Config_Key.length; i++) {
this.reInit(i)
}
}
public releaseAll() { public reInitAll() {
for (let i = 0; i < VersionManager.Config_Key.length; i++) { this.releaseAll()
if (this.hotUpdateList[i]) { for (let i = 0; i < VersionManager.Config_Key.length; i++) {
this.hotUpdateList[i].disposeUpdate() this.reInit(i)
} }
} }
}
public reInit(index: number) { public releaseAll() {
if (!this.hotUpdateList[index]) { for (let i = 0; i < VersionManager.Config_Key.length; i++) {
this.hotUpdateList[index] = new HotUpdate() if (this.hotUpdateList[i]) {
} this.hotUpdateList[i].disposeUpdate()
this.hotUpdateList[index].init( }
index, }
VersionManager.Config_Key[index], }
VersionManager.Config_ManifestName
)
if (!this.isOpenHotUpdate) {
this.hotUpdateList[index].isCheck = true
this.hotUpdateList[index].isFinishUpdate = true
}
}
public checkUpdate(keyIndex: number) { public reInit(index: number) {
if (keyIndex < this.hotUpdateList.length) { if (!this.hotUpdateList[index]) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] this.hotUpdateList[index] = new HotUpdate()
if (sys.isNative) { }
if (keyIndex == this.noUpdateIndex) { this.hotUpdateList[index].init(
//在大厅热更,不用子游戏热更了 index,
hotUpdate.isCheck = true VersionManager.Config_Key[index],
hotUpdate.isFinishUpdate = true VersionManager.Config_ManifestName
EventManager.instance.dispatchEvent( )
HotUpdate.Event_On_ALREADY_UP_TO_DATE, if (!this.isOpenHotUpdate) {
VersionManager.Config_Key[keyIndex] this.hotUpdateList[index].isCheck = true
) this.hotUpdateList[index].isFinishUpdate = true
} else { }
hotUpdate.checkUpdate() }
}
} else {
hotUpdate.isCheck = true
hotUpdate.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
)
}
} else {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
)
}
}
public startUpdate(keyIndex: number) { public checkUpdate(keyIndex: number) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] if (keyIndex < this.hotUpdateList.length) {
hotUpdate.startUpdate() let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
} if (sys.isNative) {
if (keyIndex == this.noUpdateIndex) {
//在大厅热更,不用子游戏热更了
hotUpdate.isCheck = true
hotUpdate.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
)
} else {
hotUpdate.checkUpdate()
}
} else {
hotUpdate.isCheck = true
hotUpdate.isFinishUpdate = true
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
)
}
} else {
EventManager.instance.dispatchEvent(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
VersionManager.Config_Key[keyIndex]
)
}
}
public isCheck(keyIndex: number) { public startUpdate(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) { let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] hotUpdate.startUpdate()
if (keyIndex == this.noUpdateIndex) { }
return true
}
return hotUpdate.isCheck
}
return true
}
public needUpdate(keyIndex: number) { public isCheck(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) { if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) { if (keyIndex == this.noUpdateIndex) {
return false return true
} }
return hotUpdate.needUpdate return hotUpdate.isCheck
} }
return false return true
} }
public isUpdating(keyIndex: number) { public needUpdate(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) { if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
return hotUpdate.isUpdating if (keyIndex == this.noUpdateIndex) {
} return false
return false }
} return hotUpdate.needUpdate
}
return false
}
public isFinishUpdate(keyIndex: number) { public isUpdating(keyIndex: number) {
if (keyIndex < this.hotUpdateList.length) { if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex] let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) { return hotUpdate.isUpdating
return true }
} return false
return hotUpdate.isFinishUpdate }
}
return true public isFinishUpdate(keyIndex: number) {
} if (keyIndex < this.hotUpdateList.length) {
let hotUpdate: HotUpdate = this.hotUpdateList[keyIndex]
if (keyIndex == this.noUpdateIndex) {
return true
}
return hotUpdate.isFinishUpdate
}
return true
}
} }

View File

@@ -1,44 +1,44 @@
import { _decorator } from 'cc'
import { FishInfo } from './FishInfo' import { FishInfo } from './FishInfo'
export class FishConfig { export class FishConfig {
public static readonly config: ReadonlyArray<FishInfo> = [ public static readonly config: ReadonlyArray<FishInfo> = [
new FishInfo(1, '蝴蝶鱼', 2, 2), new FishInfo(1, '蝴蝶鱼', 2, 2),
new FishInfo(2, '鲶鱼', 2, 1), new FishInfo(2, '鲶鱼', 2, 1),
new FishInfo(3, '狮子鱼', 2, 2), new FishInfo(3, '狮子鱼', 2, 2),
new FishInfo(4, '条纹鱼', 2, 2), new FishInfo(4, '条纹鱼', 2, 2),
new FishInfo(5, '沙丁鱼', 2, 2), new FishInfo(5, '沙丁鱼', 2, 2),
new FishInfo(6, '石斑鱼', 2, 2), new FishInfo(6, '石斑鱼', 2, 2),
new FishInfo(7, '河豚', 3, 1.2), new FishInfo(7, '河豚', 3, 1.2),
new FishInfo(8, '海螺', 3, 2), new FishInfo(8, '海螺', 3, 2),
new FishInfo(9, '接吻鱼', 3, 1.2), new FishInfo(9, '接吻鱼', 3, 1.2),
new FishInfo(10, '海姆', 4, 1), new FishInfo(10, '海姆', 4, 1),
new FishInfo(11, '绿鳍鱼', 4, 1.2), new FishInfo(11, '绿鳍鱼', 4, 1.2),
new FishInfo(12, '鲎', 4, 1.2), new FishInfo(12, '鲎', 4, 1.2),
new FishInfo(13, '魔鬼鱼', 5, 0.6), new FishInfo(13, '魔鬼鱼', 5, 0.6),
new FishInfo(14, '小海龟', 5, 2), new FishInfo(14, '小海龟', 5, 2),
new FishInfo(15, '锤头鲨', 6, 0.5), new FishInfo(15, '锤头鲨', 6, 0.5),
new FishInfo(16, '金枪鱼', 6, 0.5), new FishInfo(16, '金枪鱼', 6, 0.5),
new FishInfo(17, '大三元', 6, 0.5), new FishInfo(17, '大三元', 6, 0.5),
new FishInfo(18, '黄金鲎', 6, 1.2), new FishInfo(18, '黄金鲎', 6, 1.2),
new FishInfo(19, '大四喜', 7, 0.5), new FishInfo(19, '大四喜', 7, 0.5),
new FishInfo(20, '黄金锤头鲨', 7, 0.5), new FishInfo(20, '黄金锤头鲨', 7, 0.5),
new FishInfo(21, '金海姆', 7, 0.6), new FishInfo(21, '金海姆', 7, 0.6),
new FishInfo(22, '五福临门', 8, 0.4), new FishInfo(22, '五福临门', 8, 0.4),
new FishInfo(23, '金海龟', 8, 0.7), new FishInfo(23, '金海龟', 8, 0.7),
new FishInfo(24, '金鲨', 8, 0.5), new FishInfo(24, '金鲨', 8, 0.5),
new FishInfo(25, '蓝鲨', 8, 0.5), new FishInfo(25, '蓝鲨', 8, 0.5),
new FishInfo(26, '美人鱼', 14, 0.4), new FishInfo(26, '美人鱼', 14, 0.4),
new FishInfo(27, '金龙', 14, 0.3), new FishInfo(27, '金龙', 14, 0.3),
new FishInfo(28, '章鱼', 10, 0.5), new FishInfo(28, '章鱼', 10, 0.5),
new FishInfo(29, '电鳗鱼', 3, 0.8), new FishInfo(29, '电鳗鱼', 3, 0.8)
] ]
public static getFishInfoByType(fishType: number) {
for (let i = 0; i < this.config.length; i++) { public static getFishInfoByType(fishType: number) {
let fishInfo: FishInfo = this.config[i] for (let i = 0; i < this.config.length; i++) {
if (fishInfo.fishType == fishType) { let fishInfo: FishInfo = this.config[i]
return fishInfo if (fishInfo.fishType == fishType) {
} return fishInfo
} }
} }
}
} }

View File

@@ -1,18 +1,18 @@
import { _decorator } from 'cc'
export class FishInfo { export class FishInfo {
public fishType: number public fishType: number
public name: string public name: string
public blood: number public blood: number
public wikiScale: number public wikiScale: number
constructor(
fishType: number, constructor(
name: string, fishType: number,
blood: number, name: string,
wikiScale: number blood: number,
) { wikiScale: number
this.fishType = fishType ) {
this.name = name this.fishType = fishType
this.blood = blood this.name = name
this.wikiScale = wikiScale this.blood = blood
} this.wikiScale = wikiScale
}
} }

View File

@@ -1,11 +1,11 @@
import { _decorator } from 'cc'
import { FishMapInfo } from './FishMapInfo' import { FishMapInfo } from './FishMapInfo'
export class FishMap { export class FishMap {
public mapId: number public mapId: number
public fishMapInfoList: Array<FishMapInfo> public fishMapInfoList: Array<FishMapInfo>
constructor(mapId: number, list: Array<FishMapInfo>) {
this.mapId = mapId constructor(mapId: number, list: Array<FishMapInfo>) {
this.fishMapInfoList = list this.mapId = mapId
} this.fishMapInfoList = list
}
} }

View File

@@ -1,21 +1,21 @@
import { _decorator } from 'cc'
export class FishMapInfo { export class FishMapInfo {
public fishType: number public fishType: number
public scale: number public scale: number
public side: number //1: -1: public side: number //1: -1:
public x: number public x: number
public y: number public y: number
constructor(
fishType: number, constructor(
scale: number, fishType: number,
side: number, scale: number,
x: number, side: number,
y: number x: number,
) { y: number
this.fishType = fishType ) {
this.scale = scale this.fishType = fishType
this.side = side this.scale = scale
this.x = x this.side = side
this.y = y this.x = x
} this.y = y
}
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,9 +1,11 @@
import { _decorator, Vec2 } from 'cc' import { Vec2 } from 'cc'
export class FishPathInfo { export class FishPathInfo {
public pathId: number public pathId: number
public path: Array<Vec2> = [] public path: Array<Vec2> = []
constructor(pathId: number, path: Array<Vec2>) {
this.pathId = pathId constructor(pathId: number, path: Array<Vec2>) {
this.path = path this.pathId = pathId
} this.path = path
}
} }

View File

@@ -1,4 +1,3 @@
import { _decorator } from 'cc'
export class GameConfig { export class GameConfig {
public static GameName: string = 'FishSingle' public static GameName: string = 'FishSingle'
} }

View File

@@ -1,2 +1,2 @@
import { _decorator } from 'cc' export default class GameEvent {
export default class GameEvent {} }

View File

@@ -1,21 +1,16 @@
import { import {
_decorator, _decorator,
Component, Component,
Prefab, EventTouch,
NodePool, instantiate,
Event, Node,
Node, NodePool,
Vec3, Prefab,
Vec2, sys,
EventTouch, UITransform,
UITransform, Vec2,
instantiate, Vec3
sys,
error,
} from 'cc' } from 'cc'
const { ccclass, property } = _decorator
import { Logger } from '../../engine/utils/Logger'
import FishBulletBase from '../../../fish/script/FishBulletBase' import FishBulletBase from '../../../fish/script/FishBulletBase'
import MathUtils from '../../engine/utils/MathUtils' import MathUtils from '../../engine/utils/MathUtils'
import CannonManager from './CannonManager' import CannonManager from './CannonManager'
@@ -25,136 +20,140 @@ import GameMusicHelper from '../utils/GameMusicHelper'
import FishUI from '../../../fish/script/FishUI' import FishUI from '../../../fish/script/FishUI'
import CommonTips from '../../engine/uicomponent/CommonTips' import CommonTips from '../../engine/uicomponent/CommonTips'
const { ccclass, property } = _decorator
@ccclass('BulletManager') @ccclass('BulletManager')
export default class BulletManager extends Component { export default class BulletManager extends Component {
public static instance: BulletManager = null public static instance: BulletManager = null
@property({ type: [Prefab] }) @property({ type: [Prefab] })
private bulletPrefabList: Prefab[] = [] private bulletPrefabList: Prefab[] | [] = []
private bulletPool: Array<NodePool> = [] private bulletPool: Array<NodePool> = []
private bulletList: Array<FishBulletBase> = [] private bulletList: Array<FishBulletBase> = []
private bulletMoveSpeed: number = 30 private bulletMoveSpeed: number = 30
private _vec3Cache private _vec3Cache: Vec3
private _vec2Cache private _vec2Cache: Vec2
private _fireTime: number = 0 private _fireTime: number = 0
private _fireTimeNew: number private _fireTimeNew: number
onLoad() {
this._vec3Cache = new Vec3()
this._vec2Cache = new Vec2()
BulletManager.instance = this
this.node.on(Node.EventType.TOUCH_START, this.onShootBullet, this)
// this.node.on(Node.EventType.TOUCH_MOVE, this.onShootBullet, this)
}
start() {} onLoad() {
this._vec3Cache = new Vec3()
this._vec2Cache = new Vec2()
BulletManager.instance = this
this.node.on(Node.EventType.TOUCH_START, this.onShootBullet, this)
// this.node.on(Node.EventType.TOUCH_MOVE, this.onShootBullet, this)
}
update() { start() {
this.checkMoveBullet() }
}
private checkMoveBullet() { update() {
for (let i = this.bulletList.length - 1; i >= 0; i--) { this.checkMoveBullet()
let bullet: FishBulletBase = this.bulletList[i] }
let isMoving: boolean = MoveHelper.moveNode(
bullet.node,
this.bulletMoveSpeed,
bullet.targetP.x,
bullet.targetP.y
)
if (!isMoving) {
bullet.node.getPosition(this._vec3Cache)
this._vec2Cache.x = this._vec3Cache.x
this._vec2Cache.y = this._vec3Cache.y
FishNetManager.instance.addFishNet(bullet.bulletType, this._vec2Cache)
this.bulletList.splice(i, 1)
this.destroyBullet(bullet)
}
}
}
private onShootBullet(event: EventTouch) { private checkMoveBullet() {
//TOUCH_START 在Editor上连续触发2次导致发2次炮弹bug for (let i = this.bulletList.length - 1; i >= 0; i--) {
if (sys.platform == 'EDITOR_PAGE') { let bullet: FishBulletBase = this.bulletList[i]
this._fireTimeNew = new Date().getTime() let isMoving: boolean = MoveHelper.moveNode(
if (this._fireTimeNew - this._fireTime < 100) { bullet.node,
return this.bulletMoveSpeed,
} bullet.targetP.x,
this._fireTime = this._fireTimeNew bullet.targetP.y
} )
if (!isMoving) {
bullet.node.getPosition(this._vec3Cache)
this._vec2Cache.x = this._vec3Cache.x
this._vec2Cache.y = this._vec3Cache.y
FishNetManager.instance.addFishNet(bullet.bulletType, this._vec2Cache)
this.bulletList.splice(i, 1)
this.destroyBullet(bullet)
}
}
}
let tran = this.node.getComponent(UITransform) private onShootBullet(event: EventTouch) {
let location = event.getUILocation() //TOUCH_START 在Editor上连续触发2次导致发2次炮弹bug
this._vec3Cache.x = location.x if (sys.platform == 'EDITOR_PAGE') {
this._vec3Cache.y = location.y this._fireTimeNew = new Date().getTime()
this._vec3Cache.z = 0 if (this._fireTimeNew - this._fireTime < 100) {
tran.convertToNodeSpaceAR(this._vec3Cache, this._vec3Cache) return
let localP: Vec2 = new Vec2(this._vec3Cache.x, this._vec3Cache.y) }
FishUI.instance.playClickEffect(localP) this._fireTime = this._fireTimeNew
// 子弹发射 }
if (FishUI.instance.dz_score >= CannonManager.instance.cannonType) {
FishUI.instance.dz_score -= CannonManager.instance.cannonType
FishUI.instance.refreshScore()
this._vec3Cache = CannonManager.instance.getCannonPosition()
let rad: number = MathUtils.p2pRad( let tran = this.node.getComponent(UITransform)
new Vec2(this._vec3Cache.x, this._vec3Cache.y), let location = event.getUILocation()
localP this._vec3Cache.x = location.x
) this._vec3Cache.y = location.y
let rot: number = MathUtils.radiansToDegrees(rad) this._vec3Cache.z = 0
let bullet: FishBulletBase = this.createBullet( tran.convertToNodeSpaceAR(this._vec3Cache, this._vec3Cache)
CannonManager.instance.cannonType - 1 let localP: Vec2 = new Vec2(this._vec3Cache.x, this._vec3Cache.y)
) FishUI.instance.playClickEffect(localP)
bullet.targetP = localP // 子弹发射
this.node.addChild(bullet.node) if (FishUI.instance.dz_score >= CannonManager.instance.cannonType) {
bullet.node.setPosition(CannonManager.instance.getCannonPosition()) FishUI.instance.dz_score -= CannonManager.instance.cannonType
this._vec3Cache.x = 1 FishUI.instance.refreshScore()
this._vec3Cache.y = 1 this._vec3Cache = CannonManager.instance.getCannonPosition()
this._vec3Cache.y = 1
Vec3.multiplyScalar(this._vec3Cache, this._vec3Cache, 2)
bullet.node.setScale(this._vec3Cache)
bullet.node.angle = rot
this.bulletList.push(bullet)
GameMusicHelper.playFire()
//旋转炮台 let rad: number = MathUtils.p2pRad(
CannonManager.instance.rotateCannon(location) new Vec2(this._vec3Cache.x, this._vec3Cache.y),
} else { localP
CommonTips.showMsg('豆子不足!') )
} let rot: number = MathUtils.radiansToDegrees(rad)
} let bullet: FishBulletBase = this.createBullet(
CannonManager.instance.cannonType - 1
)
bullet.targetP = localP
this.node.addChild(bullet.node)
bullet.node.setPosition(CannonManager.instance.getCannonPosition())
this._vec3Cache.x = 1
this._vec3Cache.y = 1
this._vec3Cache.y = 1
Vec3.multiplyScalar(this._vec3Cache, this._vec3Cache, 2)
bullet.node.setScale(this._vec3Cache)
bullet.node.angle = rot
this.bulletList.push(bullet)
GameMusicHelper.playFire()
private createBullet(bulletType: number) { //旋转炮台
let bulletNode: Node CannonManager.instance.rotateCannon(location)
if (this.bulletPool[bulletType] && this.bulletPool[bulletType].size() > 0) { } else {
bulletNode = this.bulletPool[bulletType].get() CommonTips.showMsg('豆子不足!')
} else { }
bulletNode = instantiate(this.bulletPrefabList[bulletType]) }
}
bulletNode.getComponent(FishBulletBase).bulletType = bulletType
return bulletNode.getComponent(FishBulletBase)
}
public killBullet(bullet: FishBulletBase) { private createBullet(bulletType: number) {
let index: number = this.bulletList.indexOf(bullet) let bulletNode: Node
if (index >= 0) { if (this.bulletPool[bulletType] && this.bulletPool[bulletType].size() > 0) {
this.bulletList.splice(index, 1) bulletNode = this.bulletPool[bulletType].get()
this.destroyBullet(bullet) } else {
} bulletNode = instantiate(this.bulletPrefabList[bulletType])
} }
bulletNode.getComponent(FishBulletBase).bulletType = bulletType
return bulletNode.getComponent(FishBulletBase)
}
private destroyBullet(bullet: FishBulletBase) { public killBullet(bullet: FishBulletBase) {
//临时代码,因为回收在内存卡顿。后面在优化 2023-2-10 let index: number = this.bulletList.indexOf(bullet)
if (sys.platform == 'EDITOR_PAGE') { if (index >= 0) {
bullet.node.destroy() this.bulletList.splice(index, 1)
return this.destroyBullet(bullet)
} }
}
if (!this.bulletPool[bullet.bulletType]) { private destroyBullet(bullet: FishBulletBase) {
this.bulletPool[bullet.bulletType] = new NodePool() //临时代码,因为回收在内存卡顿。后面在优化 2023-2-10
} if (sys.platform == 'EDITOR_PAGE') {
this.bulletPool[bullet.bulletType].put(bullet.node) bullet.node.destroy()
} return
}
onDestroy() { if (!this.bulletPool[bullet.bulletType]) {
BulletManager.instance = null this.bulletPool[bullet.bulletType] = new NodePool()
} }
this.bulletPool[bullet.bulletType].put(bullet.node)
}
onDestroy() {
BulletManager.instance = null
}
} }

View File

@@ -1,66 +1,58 @@
import { import { _decorator, Component, EventMouse, Node, Sprite, SpriteFrame, UITransform, Vec2, Vec3 } from 'cc'
_decorator,
Component,
Node,
SpriteFrame,
Event,
EventMouse,
Sprite,
Vec2,
UITransform,
Vec3,
} from 'cc'
const { ccclass, property } = _decorator
import MathUtils from '../../engine/utils/MathUtils' import MathUtils from '../../engine/utils/MathUtils'
const { ccclass, property } = _decorator
@ccclass('CannonManager') @ccclass('CannonManager')
export default class CannonManager extends Component { export default class CannonManager extends Component {
public static instance: CannonManager = null public static instance: CannonManager = null
@property({ type: Node }) @property({ type: Node })
private view: Node | null = null private view: Node | null = null
@property({ type: [SpriteFrame] }) @property({ type: [SpriteFrame] })
private cannonSpriteFrame: Array<SpriteFrame> = [] private cannonSpriteFrame: Array<SpriteFrame> | [] = []
// 炮塔倍数 // 炮塔倍数
public cannonType: number = 1 public cannonType: number = 1
private _vec3Cache private _vec3Cache: Vec3
onLoad() { onLoad() {
this._vec3Cache = new Vec3() this._vec3Cache = new Vec3()
CannonManager.instance = this CannonManager.instance = this
this.node.parent.on(Node.EventType.MOUSE_MOVE, this.onMeMove.bind(this)) this.node.parent.on(Node.EventType.MOUSE_MOVE, this.onMeMove.bind(this))
this.refreshCannon() this.refreshCannon()
} }
private onMeMove(event: EventMouse) {
this.rotateCannon(event.getUILocation())
}
public rotateCannon(uilocation: Vec2) { private onMeMove(event: EventMouse) {
let location = uilocation this.rotateCannon(event.getUILocation())
this._vec3Cache.x = location.x }
this._vec3Cache.y = location.y
this._vec3Cache.z = 0
let tran = this.node.getComponent(UITransform)
tran.convertToNodeSpaceAR(this._vec3Cache, this._vec3Cache)
let localTouch: Vec2 = new Vec2(this._vec3Cache.x, this._vec3Cache.y) public rotateCannon(uilocation: Vec2) {
this.view.getPosition(this._vec3Cache) let location = uilocation
let rad: number = MathUtils.p2pRad( this._vec3Cache.x = location.x
new Vec2(this._vec3Cache.x, this._vec3Cache.y), this._vec3Cache.y = location.y
localTouch this._vec3Cache.z = 0
) let tran = this.node.getComponent(UITransform)
let rot: number = MathUtils.radiansToDegrees(rad) tran.convertToNodeSpaceAR(this._vec3Cache, this._vec3Cache)
this.view.angle = rot - 90
}
public refreshCannon() { let localTouch: Vec2 = new Vec2(this._vec3Cache.x, this._vec3Cache.y)
this.view.getComponent(Sprite).spriteFrame = this.view.getPosition(this._vec3Cache)
this.cannonSpriteFrame[this.cannonType - 1] let rad: number = MathUtils.p2pRad(
} new Vec2(this._vec3Cache.x, this._vec3Cache.y),
public getCannonPosition() { localTouch
return this.view.getPosition() )
} let rot: number = MathUtils.radiansToDegrees(rad)
onDestroy() { this.view.angle = rot - 90
CannonManager.instance = null }
}
public refreshCannon() {
this.view.getComponent(Sprite).spriteFrame =
this.cannonSpriteFrame[this.cannonType - 1]
}
public getCannonPosition() {
return this.view.getPosition()
}
onDestroy() {
CannonManager.instance = null
}
} }

View File

@@ -1,21 +1,6 @@
import { import { _decorator, Animation, Component, game, instantiate, Node, NodePool, Prefab, Vec2, Vec3 } from 'cc'
_decorator,
Component,
Node,
Prefab,
NodePool,
game,
Vec3,
sys,
instantiate,
Animation,
Vec2,
} from 'cc'
const { ccclass, property } = _decorator
import RandomUtil from '../../engine/utils/RandomUtil' import RandomUtil from '../../engine/utils/RandomUtil'
import FishBase from '../../../fish/script/FishBase' import FishBase from '../../../fish/script/FishBase'
import { FishPathInfo } from '../config/FishPathInfo'
import { FishPathConfig } from '../config/FishPathConfig' import { FishPathConfig } from '../config/FishPathConfig'
import FishMover from '../../../fish/script/FishMover' import FishMover from '../../../fish/script/FishMover'
import { Logger } from '../../engine/utils/Logger' import { Logger } from '../../engine/utils/Logger'
@@ -28,195 +13,198 @@ import { FishMapInfo } from '../config/FishMapInfo'
import FishUI from '../../../fish/script/FishUI' import FishUI from '../../../fish/script/FishUI'
import TimeHelper from '../utils/TimeHelper' import TimeHelper from '../utils/TimeHelper'
const { ccclass, property } = _decorator
@ccclass('FishManager') @ccclass('FishManager')
export default class FishManager extends Component { export default class FishManager extends Component {
public static instance: FishManager = null public static instance: FishManager = null
@property({ type: Node }) @property({ type: Node })
private fishContainer: Node | null = null private fishContainer: Node | null = null
@property({ type: [Prefab] }) @property({ type: [Prefab] })
public fishPrefabList: Array<Prefab> = [] public fishPrefabList: Array<Prefab> = []
private fishPool: Array<NodePool> = [] private fishPool: Array<NodePool> = []
private fishList: Array<FishBase> = [] private fishList: Array<FishBase> = []
private nextRandomFishTime: number = 0 private nextRandomFishTime: number = 0
private minRandomTime: number = 2 * (game.frameRate as number) private minRandomTime: number = 2 * (game.frameRate as number)
private maxRandomTime: number = 5 * (game.frameRate as number) private maxRandomTime: number = 5 * (game.frameRate as number)
private isFishMap: boolean = false private isFishMap: boolean = false
private mapCount: number = 0 private mapCount: number = 0
private minMapCount: number = 30 * (game.frameRate as number) private minMapCount: number = 30 * (game.frameRate as number)
private maxMapCount: number = 60 * (game.frameRate as number) private maxMapCount: number = 60 * (game.frameRate as number)
// // private minMapCount: number = 2 * cc.game.getFrameRate(); // // private minMapCount: number = 2 * cc.game.getFrameRate();
// // private maxMapCount: number = 5 * cc.game.getFrameRate(); // // private maxMapCount: number = 5 * cc.game.getFrameRate();
private _fishPosCache private _fishPosCache: Vec3
onLoad() {
FishManager.instance = this
this._fishPosCache = new Vec3()
Logger.log(
'maxRandomTime=',
this.minRandomTime,
this.maxRandomTime,
game.frameRate
)
}
start() { onLoad() {
this.randomFish() FishManager.instance = this
} this._fishPosCache = new Vec3()
Logger.log(
'maxRandomTime=',
this.minRandomTime,
this.maxRandomTime,
game.frameRate
)
}
update() { start() {
this.checkRandomFish() this.randomFish()
this.checkFishMoveEnd() }
this.checkFishMap()
}
private checkFishMap() { update() {
if (!this.isFishMap) { this.checkRandomFish()
if (this.mapCount > 0) { this.checkFishMoveEnd()
this.mapCount-- this.checkFishMap()
if (this.mapCount <= 0) { }
FishUI.instance.playWaveEffect()
}
}
}
}
private checkRandomFish() { private checkFishMap() {
if (!this.isFishMap) { if (!this.isFishMap) {
if (this.nextRandomFishTime > 0) { if (this.mapCount > 0) {
this.nextRandomFishTime-- this.mapCount--
if (this.nextRandomFishTime == 0) { if (this.mapCount <= 0) {
this.randomFish() FishUI.instance.playWaveEffect()
} }
} }
} }
} }
private checkFishMoveEnd() { private checkRandomFish() {
for (let i = this.fishList.length - 1; i >= 0; i--) { if (!this.isFishMap) {
let fish: FishBase = this.fishList[i] if (this.nextRandomFishTime > 0) {
if (this.isFishMap) { this.nextRandomFishTime--
if (!fish.isDead) { if (this.nextRandomFishTime == 0) {
fish.node.getPosition(this._fishPosCache) this.randomFish()
this._fishPosCache.x -= 2 }
fish.node.setPosition(this._fishPosCache) }
if (this._fishPosCache.x <= -screen.width / 2) { }
//winSize.width }
this.destroyFish(fish)
this.fishList.splice(i, 1)
this.checkEndFishMap()
}
}
} else if (!fish.getComponent(FishMover).isMoving) {
this.destroyFish(fish)
this.fishList.splice(i, 1)
}
}
}
private checkEndFishMap() { private checkFishMoveEnd() {
Logger.log('checkEndFishMap==', this.isFishMap, this.fishList) for (let i = this.fishList.length - 1; i >= 0; i--) {
if (this.isFishMap && this.fishList.length <= 0) { let fish: FishBase = this.fishList[i]
this.isFishMap = false if (this.isFishMap) {
this.randomFish() if (!fish.isDead) {
} fish.node.getPosition(this._fishPosCache)
} this._fishPosCache.x -= 2
fish.node.setPosition(this._fishPosCache)
if (this._fishPosCache.x <= -screen.width / 2) {
//winSize.width
this.destroyFish(fish)
this.fishList.splice(i, 1)
this.checkEndFishMap()
}
}
} else if (!fish.getComponent(FishMover).isMoving) {
this.destroyFish(fish)
this.fishList.splice(i, 1)
}
}
}
private randomFish() { private checkEndFishMap() {
if (this.isFishMap) return Logger.log('checkEndFishMap==', this.isFishMap, this.fishList)
let randomNum: number = RandomUtil.nextInt(1, 10) if (this.isFishMap && this.fishList.length <= 0) {
// let randomNum: number = RandomUtil.nextInt(1, 1); this.isFishMap = false
for (let i = 0; i < randomNum; i++) { this.randomFish()
let fishType: number = RandomUtil.nextInt(1, 29) }
// let fishType: number = RandomUtil.nextInt(1, 1); }
let fish: FishBase = this.createFishByType(fishType)
fish.fishPathInfo = FishPathConfig.randomPathInfo()
this._fishPosCache.z = 0
this._fishPosCache.x = fish.fishPathInfo.path[0].x
this._fishPosCache.y = fish.fishPathInfo.path[0].y
fish.node.setPosition(this._fishPosCache)
fish.getComponent(FishMover).bezierPList = fish.fishPathInfo.path
fish.getComponent(FishMover).startMove()
this.fishList.push(fish)
this.fishContainer.addChild(fish.node)
}
Logger.log('checkFishMoveEnd=randomFish=', this.fishList)
this.nextRandomFishTime = RandomUtil.nextInt(
this.minRandomTime,
this.maxRandomTime
)
if (this.mapCount <= 0) {
this.mapCount = RandomUtil.nextInt(this.minMapCount, this.maxMapCount)
}
}
public createFishByType(fishType: number): FishBase { private randomFish() {
let fishNode: Node if (this.isFishMap) return
if (this.fishPool[fishType - 1] && this.fishPool[fishType - 1].size() > 0) { let randomNum: number = RandomUtil.nextInt(1, 10)
fishNode = this.fishPool[fishType - 1].get() // let randomNum: number = RandomUtil.nextInt(1, 1);
} else { for (let i = 0; i < randomNum; i++) {
fishNode = instantiate(this.fishPrefabList[fishType - 1]) let fishType: number = RandomUtil.nextInt(1, 29)
} // let fishType: number = RandomUtil.nextInt(1, 1);
//fishNode.getComponent(Animation).play() //v3 当前帧 不能播放 let fish: FishBase = this.createFishByType(fishType)
TimeHelper.exeNextFrame(fishNode, () => fish.fishPathInfo = FishPathConfig.randomPathInfo()
fishNode.getComponent(Animation).play() this._fishPosCache.z = 0
) this._fishPosCache.x = fish.fishPathInfo.path[0].x
let fishInfo: FishInfo = FishConfig.getFishInfoByType(fishType) this._fishPosCache.y = fish.fishPathInfo.path[0].y
fishNode.getComponent(FishBase).fishInfo = fishInfo fish.node.setPosition(this._fishPosCache)
fishNode.getComponent(FishBase).fishType = fishType fish.getComponent(FishMover).bezierPList = fish.fishPathInfo.path
fishNode.getComponent(FishBase).blood = fishInfo.blood fish.getComponent(FishMover).startMove()
fishNode.getComponent(FishBase).isDead = false this.fishList.push(fish)
return fishNode.getComponent(FishBase) this.fishContainer.addChild(fish.node)
} }
Logger.log('checkFishMoveEnd=randomFish=', this.fishList)
this.nextRandomFishTime = RandomUtil.nextInt(
this.minRandomTime,
this.maxRandomTime
)
if (this.mapCount <= 0) {
this.mapCount = RandomUtil.nextInt(this.minMapCount, this.maxMapCount)
}
}
public killFish(fish: FishBase) { public createFishByType(fishType: number): FishBase {
let index: number = this.fishList.indexOf(fish) let fishNode: Node
if (index >= 0) { if (this.fishPool[fishType - 1] && this.fishPool[fishType - 1].size() > 0) {
// console.log("鱼挂了") fishNode = this.fishPool[fishType - 1].get()
GameMusicHelper.playFishDead(fish.fishType) } else {
fish.node.getPosition(this._fishPosCache) fishNode = instantiate(this.fishPrefabList[fishType - 1])
let vec2 = new Vec2(this._fishPosCache.x, this._fishPosCache.y) }
ScoreManager.instance.addScore(fish.fishInfo.blood, vec2) //fishNode.getComponent(Animation).play() //v3 当前帧 不能播放
this.fishList.splice(index, 1) TimeHelper.exeNextFrame(fishNode, () =>
this.destroyFish(fish) fishNode.getComponent(Animation).play()
this.checkEndFishMap() )
} let fishInfo: FishInfo = FishConfig.getFishInfoByType(fishType)
} fishNode.getComponent(FishBase).fishInfo = fishInfo
fishNode.getComponent(FishBase).fishType = fishType
fishNode.getComponent(FishBase).blood = fishInfo.blood
fishNode.getComponent(FishBase).isDead = false
return fishNode.getComponent(FishBase)
}
private destroyFish(fish: FishBase) { public killFish(fish: FishBase) {
if (!this.fishPool[fish.fishType - 1]) { let index: number = this.fishList.indexOf(fish)
this.fishPool[fish.fishType - 1] = new NodePool() if (index >= 0) {
} // console.log("鱼挂了")
this.fishPool[fish.fishType - 1].put(fish.node) GameMusicHelper.playFishDead(fish.fishType)
} fish.node.getPosition(this._fishPosCache)
let vec2 = new Vec2(this._fishPosCache.x, this._fishPosCache.y)
ScoreManager.instance.addScore(fish.fishInfo.blood, vec2)
this.fishList.splice(index, 1)
this.destroyFish(fish)
this.checkEndFishMap()
}
}
public playFishMap() { private destroyFish(fish: FishBase) {
this.isFishMap = true if (!this.fishPool[fish.fishType - 1]) {
for (let i = this.fishList.length - 1; i >= 0; i--) { this.fishPool[fish.fishType - 1] = new NodePool()
let fish: FishBase = this.fishList[i] }
this.destroyFish(fish) this.fishPool[fish.fishType - 1].put(fish.node)
this.fishList.splice(i, 1) }
}
}
public startFishMap() { public playFishMap() {
// this.playFishMap(); this.isFishMap = true
// this.fishList = []; for (let i = this.fishList.length - 1; i >= 0; i--) {
let fish: FishBase = this.fishList[i]
this.destroyFish(fish)
this.fishList.splice(i, 1)
}
}
let map: FishMap = FishPathConfig.randomFishMap() public startFishMap() {
let fishMapInfoList: Array<FishMapInfo> = map.fishMapInfoList // this.playFishMap();
Logger.log('startFishMap==', this.isFishMap, this.fishList, map) // this.fishList = [];
for (let i = 0; i < fishMapInfoList.length; i++) {
let fishMapInfo: FishMapInfo = fishMapInfoList[i]
let fish: FishBase = this.createFishByType(fishMapInfo.fishType)
fish.node.angle = 0
// fish.node.setScale(fishMapInfo.scale);
this.fishContainer.addChild(fish.node)
fish.node.setPosition(fishMapInfo.x + screen.width, fishMapInfo.y)
this.fishList.push(fish)
}
}
onDestroy() { let map: FishMap = FishPathConfig.randomFishMap()
FishManager.instance = null let fishMapInfoList: Array<FishMapInfo> = map.fishMapInfoList
} Logger.log('startFishMap==', this.isFishMap, this.fishList, map)
for (let i = 0; i < fishMapInfoList.length; i++) {
let fishMapInfo: FishMapInfo = fishMapInfoList[i]
let fish: FishBase = this.createFishByType(fishMapInfo.fishType)
fish.node.angle = 0
// fish.node.setScale(fishMapInfo.scale);
this.fishContainer.addChild(fish.node)
fish.node.setPosition(fishMapInfo.x + screen.width, fishMapInfo.y)
this.fishList.push(fish)
}
}
onDestroy() {
FishManager.instance = null
}
} }

View File

@@ -1,53 +1,45 @@
import { import { _decorator, Component, instantiate, Node, NodePool, Prefab, Vec2, Vec3 } from 'cc'
_decorator,
Component,
Prefab,
NodePool,
Vec2,
instantiate,
Vec3,
Node,
} from 'cc'
const { ccclass, property } = _decorator
import FishNetBase from '../../../fish/script/FishNetBase' import FishNetBase from '../../../fish/script/FishNetBase'
const { ccclass, property } = _decorator
@ccclass('FishNetManager') @ccclass('FishNetManager')
export default class FishNetManager extends Component { export default class FishNetManager extends Component {
public static instance: FishNetManager = null public static instance: FishNetManager = null
@property({ type: [Prefab] }) @property({ type: [Prefab] })
private netPrefabList: Prefab[] = [] private netPrefabList: Prefab[] | [] = []
private fishNetPool: Array<NodePool> = [] private fishNetPool: Array<NodePool> = []
onLoad() {
FishNetManager.instance = this
}
public addFishNet(netType: number, p: Vec2) { onLoad() {
let fishNet: FishNetBase = this.createFishNet(netType) FishNetManager.instance = this
this.node.addChild(fishNet.node) }
fishNet.node.setPosition(new Vec3(p.x, p.y, 0))
fishNet.playMv()
}
private createFishNet(netType: number) { public addFishNet(netType: number, p: Vec2) {
let fishNetNode: Node let fishNet: FishNetBase = this.createFishNet(netType)
if (this.fishNetPool[netType] && this.fishNetPool[netType].size() > 0) { this.node.addChild(fishNet.node)
fishNetNode = this.fishNetPool[netType].get() fishNet.node.setPosition(new Vec3(p.x, p.y, 0))
} else { fishNet.playMv()
fishNetNode = instantiate(this.netPrefabList[netType]) }
}
fishNetNode.getComponent(FishNetBase).netType = netType
return fishNetNode.getComponent(FishNetBase)
}
public destroyFishNet(fishNet: FishNetBase) { private createFishNet(netType: number) {
if (!this.fishNetPool[fishNet.netType]) { let fishNetNode: Node
this.fishNetPool[fishNet.netType] = new NodePool() if (this.fishNetPool[netType] && this.fishNetPool[netType].size() > 0) {
} fishNetNode = this.fishNetPool[netType].get()
this.fishNetPool[fishNet.netType].put(fishNet.node) } else {
} fishNetNode = instantiate(this.netPrefabList[netType])
}
fishNetNode.getComponent(FishNetBase).netType = netType
return fishNetNode.getComponent(FishNetBase)
}
onDestroy() { public destroyFishNet(fishNet: FishNetBase) {
FishNetManager.instance = null if (!this.fishNetPool[fishNet.netType]) {
} this.fishNetPool[fishNet.netType] = new NodePool()
}
this.fishNetPool[fishNet.netType].put(fishNet.node)
}
onDestroy() {
FishNetManager.instance = null
}
} }

View File

@@ -1,57 +1,51 @@
import { import { _decorator, Component, instantiate, Node, NodePool, Prefab, Vec2, Vec3 } from 'cc'
_decorator,
Component,
Prefab,
NodePool,
Vec2,
instantiate,
Node,
Vec3,
} from 'cc'
const { ccclass, property } = _decorator
import ScorePrefab from '../prefab/ScorePrefab' import ScorePrefab from '../prefab/ScorePrefab'
import FishUI from '../../../fish/script/FishUI' import FishUI from '../../../fish/script/FishUI'
const { ccclass, property } = _decorator
@ccclass('ScoreManager') @ccclass('ScoreManager')
export default class ScoreManager extends Component { export default class ScoreManager extends Component {
public static instance: ScoreManager = null public static instance: ScoreManager = null
@property({ type: Prefab }) @property({ type: Prefab })
private scrorePrefab: Prefab | null = null private scrorePrefab: Prefab | null = null
private scorePool: NodePool private scorePool: NodePool
onLoad() {
ScoreManager.instance = this
this.scorePool = new NodePool()
}
public addScore(score: number, p: Vec2) { onLoad() {
let scorePrefab: ScorePrefab = this.createScore(score) ScoreManager.instance = this
this.node.addChild(scorePrefab.node) this.scorePool = new NodePool()
scorePrefab.node.setPosition(new Vec3(p.x, p.y, 0)) }
scorePrefab.init(score)
scorePrefab.playMoveEffect(new Vec2(-472.398, -547.481), () => {
this.destroyScore(scorePrefab)
FishUI.instance.jf_score += score
FishUI.instance.refreshScore()
})
}
private createScore(score: number): ScorePrefab { public addScore(score: number, p: Vec2) {
let scoreNode: Node let scorePrefab: ScorePrefab = this.createScore(score)
if (this.scorePool && this.scorePool.size() > 0) { this.node.addChild(scorePrefab.node)
scoreNode = this.scorePool.get() scorePrefab.node.setPosition(new Vec3(p.x, p.y, 0))
} else { scorePrefab.init(score)
scoreNode = instantiate(this.scrorePrefab) scorePrefab.playMoveEffect(new Vec2(-472.398, -547.481), () => {
} this.destroyScore(scorePrefab)
return scoreNode.getComponent(ScorePrefab) FishUI.instance.jf_score += score
} FishUI.instance.refreshScore()
})
}
private destroyScore(scorePrefab: ScorePrefab) { private createScore(score: number): ScorePrefab {
this.scorePool.put(scorePrefab.node) let scoreNode: Node
} if (this.scorePool && this.scorePool.size() > 0) {
scoreNode = this.scorePool.get()
} else {
scoreNode = instantiate(this.scrorePrefab)
}
return scoreNode.getComponent(ScorePrefab)
}
onDisable() {} private destroyScore(scorePrefab: ScorePrefab) {
onDestroy() { this.scorePool.put(scorePrefab.node)
ScoreManager.instance = null }
}
onDisable() {
}
onDestroy() {
ScoreManager.instance = null
}
} }

View File

@@ -1,9 +1,9 @@
import { _decorator, Component, Prefab, Node, instantiate } from 'cc' import { _decorator, Component, instantiate, Node, Prefab } from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../../engine/utils/PrefabLoader' import PrefabLoader from '../../engine/utils/PrefabLoader'
import { GameConfig } from '../config/GameConfig' import { GameConfig } from '../config/GameConfig'
const { ccclass, property } = _decorator
@ccclass('ResourcePrefab') @ccclass('ResourcePrefab')
export default class ResourcePrefab extends Component { export default class ResourcePrefab extends Component {
private static prefab: Prefab | null = null private static prefab: Prefab | null = null

View File

@@ -1,4 +1,5 @@
import { _decorator, Component, Label, Vec2, tween, Vec3, Tween } from 'cc' import { _decorator, Component, Label, tween, Tween, Vec2, Vec3 } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
@ccclass('ScorePrefab') @ccclass('ScorePrefab')

View File

@@ -1,41 +1,42 @@
import { _decorator, Component, Node, Material, instantiate, Prefab } from 'cc' import { _decorator, Component, instantiate, Material, Node, Prefab } from 'cc'
const { ccclass, property } = _decorator
import PrefabLoader from '../../engine/utils/PrefabLoader' import PrefabLoader from '../../engine/utils/PrefabLoader'
import { GameConfig } from '../config/GameConfig' import { GameConfig } from '../config/GameConfig'
const { ccclass, property } = _decorator
@ccclass('ShaderMaterialPrefab') @ccclass('ShaderMaterialPrefab')
export default class ShaderMaterialPrefab extends Component { export default class ShaderMaterialPrefab extends Component {
public static instance: Node public static instance: Node
@property({ type: Material }) @property({ type: Material })
public default: Material | null = null public default: Material | null = null
@property({ type: Material }) @property({ type: Material })
public grayMaterial: Material | null = null public grayMaterial: Material | null = null
@property({ type: Material }) @property({ type: Material })
public oldPhoto: Material | null = null public oldPhoto: Material | null = null
@property({ type: Material }) @property({ type: Material })
public glowInner: Material | null = null public glowInner: Material | null = null
@property({ type: Material }) @property({ type: Material })
public mosaic: Material | null = null public mosaic: Material | null = null
@property({ type: Material }) @property({ type: Material })
public roundCornerCrop: Material | null = null public roundCornerCrop: Material | null = null
@property({ type: Material }) @property({ type: Material })
public flashLight: Material | null = null public flashLight: Material | null = null
@property({ type: Material }) @property({ type: Material })
public flag: Material | null = null public flag: Material | null = null
@property({ type: Material }) @property({ type: Material })
public gaussian: Material | null = null public gaussian: Material | null = null
public static preLoad(): Promise<void> {
return new Promise((resolve, reject) => { public static preLoad(): Promise<void> {
PrefabLoader.loadPrefab( return new Promise((resolve, reject) => {
GameConfig.GameName + '/' + 'game/prefab/ShaderMaterialPrefab', PrefabLoader.loadPrefab(
(loadedResource: Prefab) => { GameConfig.GameName + '/' + 'game/prefab/ShaderMaterialPrefab',
ShaderMaterialPrefab.instance = instantiate(loadedResource) (loadedResource: Prefab) => {
resolve() ShaderMaterialPrefab.instance = instantiate(loadedResource)
} resolve()
) }
}) )
} })
}
} }

View File

@@ -1,6 +1,4 @@
import { _decorator, Sprite, Prefab, Node, instantiate, Vec3, Tween } from 'cc' import { _decorator, instantiate, Node, Prefab, Sprite, Tween, Vec3 } from 'cc'
const { ccclass, property } = _decorator
import SceneBase from './SceneBase' import SceneBase from './SceneBase'
import TextureMgr from '../../engine/uicomponent/TextureMgr' import TextureMgr from '../../engine/uicomponent/TextureMgr'
import RandomUtil from '../../engine/utils/RandomUtil' import RandomUtil from '../../engine/utils/RandomUtil'
@@ -11,62 +9,65 @@ import { Logger } from '../../engine/utils/Logger'
import FishWiki from '../../../fish/script/FishWiki' import FishWiki from '../../../fish/script/FishWiki'
import GameMusicHelper from '../utils/GameMusicHelper' import GameMusicHelper from '../utils/GameMusicHelper'
const { ccclass, property } = _decorator
@ccclass('FishGameScene') @ccclass('FishGameScene')
export default class FishGameScene extends SceneBase { export default class FishGameScene extends SceneBase {
@property(Sprite) @property(Sprite)
private bg: Sprite | null = null private bg: Sprite | null = null
@property({ type: [Prefab] }) @property({ type: [Prefab] })
private fishPrefabList: Array<Prefab> = [] private fishPrefabList: Array<Prefab> | null = []
private showNode: Node | null = null private showNode: Node | null = null
onLoadMe() {
GameMusicHelper.playBg()
FishPathConfig.init()
this.initBg()
// this.testPathPlay()
}
private initBg() { onLoadMe() {
let textureMgr: TextureMgr = this.bg.getComponent(TextureMgr) GameMusicHelper.playBg()
this.bg.spriteFrame = FishPathConfig.init()
textureMgr.Spriteset[ this.initBg()
RandomUtil.nextInt(0, textureMgr.Spriteset.length - 1) // this.testPathPlay()
] }
}
private initShowNode() { private initBg() {
if (this.showNode) { let textureMgr: TextureMgr = this.bg.getComponent(TextureMgr)
this.showNode.destroy() this.bg.spriteFrame =
this.showNode = null textureMgr.Spriteset[
} RandomUtil.nextInt(0, textureMgr.Spriteset.length - 1)
let fishType: number = 29 ]
if (fishType < 1 || fishType > 29) { }
return
}
this.showNode = instantiate(this.fishPrefabList[fishType - 1])
this.showNode.getComponent(FishMover).speed = 2
this.showNode.getComponent(FishMover).node.setScale(new Vec3(2, 2, 1))
this.node.addChild(this.showNode)
}
private testPathPlay() { private initShowNode() {
this.initShowNode() if (this.showNode) {
let pathInfo: FishPathInfo = FishPathConfig.getPathInfo(3) this.showNode.destroy()
Logger.log('testPathPlay=pathInfo=', pathInfo) this.showNode = null
let params = pathInfo.path }
let param0 = params[0] let fishType: number = 29
Logger.log('testPathPlay=11=', param0) if (fishType < 1 || fishType > 29) {
this.showNode.setPosition(new Vec3(param0.x, param0.y, 0)) return
this.showNode.getComponent(FishMover).bezierPList = params }
this.showNode.getComponent(FishMover).startMove() this.showNode = instantiate(this.fishPrefabList[fishType - 1])
} this.showNode.getComponent(FishMover).speed = 2
this.showNode.getComponent(FishMover).node.setScale(new Vec3(2, 2, 1))
this.node.addChild(this.showNode)
}
private onClickWiki() { private testPathPlay() {
FishWiki.show() this.initShowNode()
} let pathInfo: FishPathInfo = FishPathConfig.getPathInfo(3)
Logger.log('testPathPlay=pathInfo=', pathInfo)
let params = pathInfo.path
let param0 = params[0]
Logger.log('testPathPlay=11=', param0)
this.showNode.setPosition(new Vec3(param0.x, param0.y, 0))
this.showNode.getComponent(FishMover).bezierPList = params
this.showNode.getComponent(FishMover).startMove()
}
onDestroyMe() { private onClickWiki() {
this.unscheduleAllCallbacks() FishWiki.show()
//this.node.stopAllActions(); }
Tween.stopAllByTarget(this.node)
} onDestroyMe() {
this.unscheduleAllCallbacks()
//this.node.stopAllActions();
Tween.stopAllByTarget(this.node)
}
} }

View File

@@ -1,13 +1,4 @@
import { import { _decorator, DynamicAtlasManager, Node, PhysicsSystem2D, profiler, sys } from 'cc'
_decorator,
Node,
sys,
profiler,
DynamicAtlasManager,
PhysicsSystem2D,
} from 'cc'
const { ccclass, property } = _decorator
import MusicConfig from '../../engine/config/MusicConfig' import MusicConfig from '../../engine/config/MusicConfig'
import CommonTips from '../../engine/uicomponent/CommonTips' import CommonTips from '../../engine/uicomponent/CommonTips'
import Progress from '../../engine/uicomponent/Progress' import Progress from '../../engine/uicomponent/Progress'
@@ -19,138 +10,141 @@ import ResourcePreload from '../utils/ResourcePreload'
import SceneBase from './SceneBase' import SceneBase from './SceneBase'
import SceneManager from './SceneManager' import SceneManager from './SceneManager'
const { ccclass, property } = _decorator
@ccclass('LoadingScene') @ccclass('LoadingScene')
export default class LoadingScene extends SceneBase { export default class LoadingScene extends SceneBase {
public static scriptName: string = 'LoadingScene' public static scriptName: string = 'LoadingScene'
@property({ type: Node }) @property({ type: Node })
private progressNode: Node | null = null private progressNode: Node | null = null
onLoadMe() {
this.baseInit()
EventManager.instance.addListener(
HotUpdate.Event_On_NeedUpdate,
this.onNeedUpdate,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_Progress,
this.onUpdateProgress,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_Fail_Update,
this.onUpdateFail,
this
)
EventManager.instance.addListener(
HotUpdate.Event_Finish_Update,
this.onUpdateFinish,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
this.onUpdateFinish,
this
)
if (sys.isNative && VersionManager.instance.isOpenHotUpdate) {
this.checkUpdate()
} else {
this.preLoadRes()
}
}
private baseInit() { async onLoadMe() {
profiler.hideStats() //showStats this.baseInit()
//let collisionManager:cc.CollisionManager = director.getCollisionManager(); EventManager.instance.addListener(
PhysicsSystem2D.instance.enable = true HotUpdate.Event_On_NeedUpdate,
this.onNeedUpdate,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_Progress,
this.onUpdateProgress,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_Fail_Update,
this.onUpdateFail,
this
)
EventManager.instance.addListener(
HotUpdate.Event_Finish_Update,
this.onUpdateFinish,
this
)
EventManager.instance.addListener(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
this.onUpdateFinish,
this
)
if (sys.isNative && VersionManager.instance.isOpenHotUpdate) {
this.checkUpdate()
} else {
await this.preLoadRes()
}
}
// PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Aabb | private baseInit() {
// EPhysics2DDrawFlags.Pair | profiler.hideStats() //showStats
// EPhysics2DDrawFlags.CenterOfMass | //let collisionManager:cc.CollisionManager = director.getCollisionManager();
// EPhysics2DDrawFlags.Joint | PhysicsSystem2D.instance.enable = true
// EPhysics2DDrawFlags.Shape;
//if(collisionManager){ // PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Aabb |
//collisionManager.enabled = true; // EPhysics2DDrawFlags.Pair |
// collisionManager.enabledDebugDraw = true; // EPhysics2DDrawFlags.CenterOfMass |
// collisionManager.enabledDrawBoundingBox = true; // EPhysics2DDrawFlags.Joint |
//} // EPhysics2DDrawFlags.Shape;
if (DynamicAtlasManager.instance) { //if(collisionManager){
DynamicAtlasManager.instance.enabled = false //collisionManager.enabled = true;
} // collisionManager.enabledDebugDraw = true;
MusicConfig.init() // collisionManager.enabledDrawBoundingBox = true;
// cc.director.getCollisionManager().enabled=true;//这是一个全局属性,开启后就代表碰撞检测组件可以进行检测了 //}
// cc.director.getCollisionManager().enabledDebugDraw = true; //绘制碰撞区域
}
private checkUpdate() { if (DynamicAtlasManager.instance) {
Logger.log(this, 'checkUpdate====') DynamicAtlasManager.instance.enabled = false
VersionManager.instance.checkUpdate(0) }
} MusicConfig.init()
// cc.director.getCollisionManager().enabled=true;//这是一个全局属性,开启后就代表碰撞检测组件可以进行检测了
// cc.director.getCollisionManager().enabledDebugDraw = true; //绘制碰撞区域
}
private onNeedUpdate(event: HaoEvent, key: string) { private checkUpdate() {
Logger.log(this, 'onNeedUpdate=====', key, VersionManager.Config_Key) Logger.log(this, 'checkUpdate====')
if (key == VersionManager.Config_Key[0]) { VersionManager.instance.checkUpdate(0)
VersionManager.instance.startUpdate(0) }
}
}
private onUpdateProgress(event, loadedFiles, totalFiles, key) { private onNeedUpdate(event: HaoEvent, key: string) {
if (key == VersionManager.Config_Key[0]) { Logger.log(this, 'onNeedUpdate=====', key, VersionManager.Config_Key)
let msg: string = if (key == VersionManager.Config_Key[0]) {
Math.min(100, (loadedFiles / totalFiles) * 100).toFixed(2) + '%' VersionManager.instance.startUpdate(0)
this.progressNode }
.getComponent(Progress) }
.updateProgress(loadedFiles, totalFiles, msg)
}
}
private onUpdateFail(event, key: string) { private onUpdateProgress(event: Function, loadedFiles: number, totalFiles: number, key: string) {
if (key == VersionManager.Config_Key[0]) { if (key == VersionManager.Config_Key[0]) {
Logger.warn(this, '热更新失败========') let msg: string =
CommonTips.showMsg('热更新失败') Math.min(100, (loadedFiles / totalFiles) * 100).toFixed(2) + '%'
ResourcePreload.instance.restartGame() this.progressNode
} .getComponent(Progress)
} .updateProgress(loadedFiles, totalFiles, msg)
}
}
private onUpdateFinish(event, key: string, needRestart: boolean) { private onUpdateFail(event, key: string) {
Logger.log(this, 'onUpdateFinish========') if (key == VersionManager.Config_Key[0]) {
if (key == VersionManager.Config_Key[0] && !needRestart) { Logger.warn(this, '热更新失败========')
this.preLoadRes() CommonTips.showMsg('热更新失败')
} ResourcePreload.instance.restartGame()
} }
}
private async preLoadRes() { private onUpdateFinish(event, key: string, needRestart: boolean) {
ResourcePreload.instance.preLoad(() => { Logger.log(this, 'onUpdateFinish========')
this.startGame() if (key == VersionManager.Config_Key[0] && !needRestart) {
}, this.progressNode.getComponent(Progress)) this.preLoadRes()
} }
}
private startGame() { private async preLoadRes() {
Logger.info(this, 'startGame') ResourcePreload.instance.preLoad(() => {
SceneManager.instance.sceneSwitch('FishGameScene', true) this.startGame()
} }, this.progressNode.getComponent(Progress))
}
onDestroyMe() { private startGame() {
EventManager.instance.removeListener( Logger.info(this, 'startGame')
HotUpdate.Event_On_NeedUpdate, SceneManager.instance.sceneSwitch('FishGameScene', true)
this.onNeedUpdate }
)
EventManager.instance.removeListener( onDestroyMe() {
HotUpdate.Event_On_Progress, EventManager.instance.removeListener(
this.onUpdateProgress HotUpdate.Event_On_NeedUpdate,
) this.onNeedUpdate
EventManager.instance.removeListener( )
HotUpdate.Event_On_Fail_Update, EventManager.instance.removeListener(
this.onUpdateFail HotUpdate.Event_On_Progress,
) this.onUpdateProgress
EventManager.instance.removeListener( )
HotUpdate.Event_Finish_Update, EventManager.instance.removeListener(
this.onUpdateFinish HotUpdate.Event_On_Fail_Update,
) this.onUpdateFail
EventManager.instance.removeListener( )
HotUpdate.Event_On_ALREADY_UP_TO_DATE, EventManager.instance.removeListener(
this.onUpdateFinish HotUpdate.Event_Finish_Update,
) this.onUpdateFinish
} )
EventManager.instance.removeListener(
HotUpdate.Event_On_ALREADY_UP_TO_DATE,
this.onUpdateFinish
)
}
} }

View File

@@ -1,25 +1,31 @@
import { _decorator, Component } from 'cc' import { _decorator, Component } from 'cc'
const { ccclass, property } = _decorator
import AdapterHelper from '../../engine/utils/AdapterHelper' import AdapterHelper from '../../engine/utils/AdapterHelper'
import PrefabLoader from '../../engine/utils/PrefabLoader'
import { Logger } from '../../engine/utils/Logger' const { ccclass, property } = _decorator
import ResourcePrefab from '../prefab/ResourcePrefab'
@ccclass('SceneBase') @ccclass('SceneBase')
export default class SceneBase extends Component { export default class SceneBase extends Component {
public static scriptName: string = 'SceneBase' public static scriptName: string = 'SceneBase'
onLoad() {
AdapterHelper.fixApdater() onLoad() {
this.onLoadMe() AdapterHelper.fixApdater()
} this.onLoadMe()
onLoadMe() {} }
start() {
this.onStartMe() onLoadMe() {
} }
onStartMe() {}
onDestroy() { start() {
this.onDestroyMe() this.onStartMe()
} }
onDestroyMe() {}
onStartMe() {
}
onDestroy() {
this.onDestroyMe()
}
onDestroyMe() {
}
} }

View File

@@ -1,4 +1,4 @@
import { director, SceneAsset, sys, _decorator } from 'cc' import { director, SceneAsset, sys } from 'cc'
import { Logger } from '../../engine/utils/Logger' import { Logger } from '../../engine/utils/Logger'
import LoadingScenePrefab from '../../engine/uicomponent/LoadingScenePrefab' import LoadingScenePrefab from '../../engine/uicomponent/LoadingScenePrefab'
import CommonTips from '../../engine/uicomponent/CommonTips' import CommonTips from '../../engine/uicomponent/CommonTips'
@@ -6,67 +6,67 @@ import EventManager from '../../engine/utils/EventManager'
import CommonEvent from '../../engine/config/CommonEvent' import CommonEvent from '../../engine/config/CommonEvent'
export default class SceneManager { export default class SceneManager {
public static instance: SceneManager = new SceneManager() public static instance: SceneManager = new SceneManager()
private loadingSceneName: string private loadingSceneName: string
public currentSceneName: string public currentSceneName: string
public initFullScreenPrefab(isShow: boolean = false) { public initFullScreenPrefab(isShow: boolean = false) {
if (sys.isBrowser && !sys.isMobile) { if (sys.isBrowser && !sys.isMobile) {
if (isShow) { if (isShow) {
// FullscreenPrefab.show(); // FullscreenPrefab.show();
} else { } else {
// FullscreenPrefab.close(); // FullscreenPrefab.close();
} }
} }
} }
public sceneSwitch(name: string, showProgress: boolean = false) { public async sceneSwitch(name: string, showProgress: boolean = false) {
if (this.loadingSceneName == name) return if (this.loadingSceneName == name) return
Logger.log(this, 'sceneSwitch==', name) Logger.log(this, 'sceneSwitch==', name)
if (sys.isBrowser) { if (sys.isBrowser) {
// showProgress = true; // showProgress = true;
} }
this.initFullScreenPrefab(false) this.initFullScreenPrefab(false)
this.loadingSceneName = name this.loadingSceneName = name
if (showProgress) { if (showProgress) {
LoadingScenePrefab.show() await LoadingScenePrefab.show()
director.preloadScene( director.preloadScene(
name, name,
(completedCount: number, totalCount: number, item: any) => { (completedCount: number, totalCount: number, item: any) => {
LoadingScenePrefab.updateLoading(completedCount, totalCount) LoadingScenePrefab.updateLoading(completedCount, totalCount)
}, },
(error: Error, asset: SceneAsset) => { (error: Error, asset: SceneAsset) => {
if (error) { if (error) {
Logger.warn(this, 'preloadScene=error', error.message) Logger.warn(this, 'preloadScene=error', error.message)
CommonTips.showMsg('加载场景失败') CommonTips.showMsg('加载场景失败')
} else { } else {
//director.getScene().destroy();//director.getScene().cleanup(); //director.getScene().destroy();//director.getScene().cleanup();
director.loadScene(name, this.loadSceneOK.bind(this)) director.loadScene(name, this.loadSceneOK.bind(this))
} }
} }
) )
} else { } else {
//director.getScene().destroy();//director.getScene().cleanup(); //director.getScene().destroy();//director.getScene().cleanup();
director.loadScene(name, this.loadSceneOK.bind(this)) director.loadScene(name, this.loadSceneOK.bind(this))
} }
} }
private loadSceneOK() { private loadSceneOK() {
LoadingScenePrefab.close() LoadingScenePrefab.close()
this.initFullScreenPrefab(true) this.initFullScreenPrefab(true)
this.currentSceneName = this.loadingSceneName this.currentSceneName = this.loadingSceneName
this.loadingSceneName = '' this.loadingSceneName = ''
Logger.log(this, 'scene load ok=', this.currentSceneName) Logger.log(this, 'scene load ok=', this.currentSceneName)
EventManager.instance.dispatchEvent(CommonEvent.Event_Scene_Switch) EventManager.instance.dispatchEvent(CommonEvent.Event_Scene_Switch)
} }
public preloadScene( public preloadScene(
sceneName: string, sceneName: string,
onProgressCallback: any = null, onProgressCallback: any = null,
onLoadedCallback: any = null onLoadedCallback: any = null
) { ) {
director.preloadScene(sceneName, onProgressCallback, onLoadedCallback) director.preloadScene(sceneName, onProgressCallback, onLoadedCallback)
} }
} }

View File

@@ -1,15 +1,18 @@
import { _decorator } from 'cc' import { _decorator } from 'cc'
const { ccclass, property } = _decorator
import EventManager, { HaoEvent } from '../../engine/utils/EventManager'
import SceneBase from './SceneBase' import SceneBase from './SceneBase'
import SceneManager from './SceneManager'
const { ccclass, property } = _decorator
@ccclass('StartScene') @ccclass('StartScene')
export default class StartScene extends SceneBase { export default class StartScene extends SceneBase {
public static scriptName: string = 'StartScene' public static scriptName: string = 'StartScene'
onLoadMe() {}
update() {}
onDestroyMe() {} onLoadMe() {
}
update() {
}
onDestroyMe() {
}
} }

View File

@@ -1,196 +1,200 @@
import { _decorator, Component, Vec2 } from 'cc' import { _decorator, Component, Vec2 } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
import { Logger } from '../../engine/utils/Logger'
export enum AstarGridType { export enum AstarGridType {
Hider = 0, //不能走 Hider = 0, //不能走
Normal = 1, //能走 Normal = 1, //能走
End = 2, //终点 End = 2, //终点
} }
@ccclass('Astar') @ccclass('Astar')
export class AstarGrid { export class AstarGrid {
public x: number = 0 public x: number = 0
public y: number = 0 public y: number = 0
public f: number = 0 public f: number = 0
public g: number = 0 public g: number = 0
public h: number = 0 public h: number = 0
public type: number = 0 public type: number = 0
public parent: AstarGrid = null public parent: AstarGrid = null
} }
export class Astar extends Component { export class Astar extends Component {
public mapW: number = 24 // 横向格子数量 public mapW: number = 24 // 横向格子数量
public mapH: number = 13 // 纵向格子数量 public mapH: number = 13 // 纵向格子数量
public is8dir: boolean = false // 是否8方向寻路 //4方向:代表只能走上下左右 8方向:代表可以走上下左右,左上,右上,左下,右下 public is8dir: boolean = false // 是否8方向寻路 //4方向:代表只能走上下左右 8方向:代表可以走上下左右,左上,右上,左下,右下
private openList: Array<AstarGrid> = [] private openList: Array<AstarGrid> = []
private closeList: Array<AstarGrid> = [] private closeList: Array<AstarGrid> = []
private path: Array<AstarGrid> = [] private path: Array<AstarGrid> = []
private gridsList: Array<Array<AstarGrid>> = [] private gridsList: Array<Array<AstarGrid>> = []
onLoad() {}
/** onLoad() {
* @param mapW 宽格子数 }
* @param mapH 高格子数
* @param is8dir 是8方向(上,下,左,右,左上,右上,左下,右下)寻路还是4方向(上,下,左,右)
*/
public init(mapW: number, mapH: number, is8dir: boolean = false) {
this.mapW = mapW
this.mapH = mapH
this.is8dir = is8dir
this.initMap()
}
/** /**
* 初始化map的格子 * @param mapW 宽格子
*/ * @param mapH 高格子数
private initMap() { * @param is8dir 是8方向(上,下,左,右,左上,右上,左下,右下)寻路还是4方向(上,下,左,右)
this.openList = [] */
this.closeList = [] public init(mapW: number, mapH: number, is8dir: boolean = false) {
this.path = [] this.mapW = mapW
// 初始化格子二维数组 this.mapH = mapH
this.gridsList = new Array(this.mapW + 1) this.is8dir = is8dir
for (let col = 0; col < this.gridsList.length; col++) { this.initMap()
this.gridsList[col] = new Array(this.mapH + 1) }
}
for (let col = 0; col <= this.mapW; col++) {
for (let row = 0; row <= this.mapH; row++) {
this.addGrid(col, row, AstarGridType.Normal)
}
}
}
/** /**
* 创建一个格子到地图 * 初始化map的格子
* @param x */
* @param y private initMap() {
* @param type this.openList = []
*/ this.closeList = []
private addGrid(x: number, y: number, type: number = AstarGridType.Hider) { this.path = []
let grid = new AstarGrid() // 初始化格子二维数组
grid.x = x this.gridsList = new Array(this.mapW + 1)
grid.y = y for (let col = 0; col < this.gridsList.length; col++) {
grid.type = type this.gridsList[col] = new Array(this.mapH + 1)
this.gridsList[x][y] = grid }
} for (let col = 0; col <= this.mapW; col++) {
for (let row = 0; row <= this.mapH; row++) {
this.addGrid(col, row, AstarGridType.Normal)
}
}
}
/** /**
* 设置格子类型 * 创建一个格子到地图
* @param x * @param x
* @param y * @param y
* @param type * @param type
*/ */
public setGridType(x: number, y: number, type: number) { private addGrid(x: number, y: number, type: number = AstarGridType.Hider) {
let curGrid: AstarGrid = this.gridsList[x][y] let grid = new AstarGrid()
curGrid.type = type grid.x = x
} grid.y = y
grid.type = type
this.gridsList[x][y] = grid
}
/** /**
* 开始搜索路径 * 设置格子类型
* @param startPos * @param x
* @param endPos * @param y
*/ * @param type
public findPath(startPos: Vec2, endPos: Vec2, callback: Function = null) { */
let startGrid = this.gridsList[startPos.x][startPos.y] public setGridType(x: number, y: number, type: number) {
this.openList.push(startGrid) let curGrid: AstarGrid = this.gridsList[x][y]
let curGrid: AstarGrid = this.openList[0] curGrid.type = type
while (this.openList.length > 0 && curGrid.type != AstarGridType.End) { }
// 每次都取出f值最小的节点进行查找
curGrid = this.openList[0]
if (curGrid.type == AstarGridType.End) {
// Logger.log(this,"find path success.");
this.generatePath(curGrid)
if (callback) {
callback(this.path)
}
return
}
for (let i: number = -1; i <= 1; i++) { /**
for (let j: number = -1; j <= 1; j++) { * 开始搜索路径
if (i != 0 || j != 0) { * @param startPos
let col = curGrid.x + i * @param endPos
let row = curGrid.y + j * @param callback
if ( */
col >= 0 && public findPath(startPos: Vec2, endPos: Vec2, callback: Function = null) {
row >= 0 && let startGrid = this.gridsList[startPos.x][startPos.y]
col <= this.mapW && this.openList.push(startGrid)
row <= this.mapH && let curGrid: AstarGrid = this.openList[0]
this.gridsList[col][row].type != AstarGridType.Hider && while (this.openList.length > 0 && curGrid.type != AstarGridType.End) {
this.closeList.indexOf(this.gridsList[col][row]) < 0 // 每次都取出f值最小的节点进行查找
) { curGrid = this.openList[0]
if (this.is8dir) { if (curGrid.type == AstarGridType.End) {
// 8方向 斜向走动时要考虑相邻的是不是障碍物 // Logger.log(this,"find path success.");
if ( this.generatePath(curGrid)
this.gridsList[col - i][row].type == AstarGridType.Hider || if (callback) {
this.gridsList[col][row - j].type == AstarGridType.Hider callback(this.path)
) { }
continue return
} }
} else {
// 四方形行走
if (Math.abs(i) == Math.abs(j)) {
continue
}
}
// 计算g值
let g =
curGrid.g +
Math.floor(Math.sqrt(Math.pow(i * 10, 2)) + Math.pow(j * 10, 2))
if (
this.gridsList[col][row].g == 0 ||
this.gridsList[col][row].g > g
) {
this.gridsList[col][row].g = g
// 更新父节点
this.gridsList[col][row].parent = curGrid
}
// 计算h值 manhattan估算法
this.gridsList[col][row].h =
Math.abs(endPos.x - col) + Math.abs(endPos.y - row)
// 更新f值
this.gridsList[col][row].f =
this.gridsList[col][row].g + this.gridsList[col][row].h
// 如果不在开放列表里则添加到开放列表里
if (this.openList.indexOf(this.gridsList[col][row]) < 0) {
this.openList.push(this.gridsList[col][row])
}
// // 重新按照f值排序升序排列)
}
}
}
}
// 遍历完四周节点后把当前节点加入关闭列表
this.closeList.push(curGrid)
// 从开放列表把当前节点移除
this.openList.splice(this.openList.indexOf(curGrid), 1)
if (this.openList.length <= 0) {
// Logger.log(this,"find path failed.");
this.path = []
if (callback) {
callback(this.path)
}
break
}
// 重新按照f值排序升序排列)
this.openList.sort((x, y) => {
return x.f - y.f
})
}
}
/** for (let i: number = -1; i <= 1; i++) {
* 生成路径 for (let j: number = -1; j <= 1; j++) {
* @param grid if (i != 0 || j != 0) {
*/ let col = curGrid.x + i
private generatePath(grid: AstarGrid) { let row = curGrid.y + j
this.path.push(grid) if (
while (grid.parent) { col >= 0 &&
grid = grid.parent row >= 0 &&
this.path.push(grid) col <= this.mapW &&
} row <= this.mapH &&
return this.path this.gridsList[col][row].type != AstarGridType.Hider &&
} this.closeList.indexOf(this.gridsList[col][row]) < 0
) {
if (this.is8dir) {
// 8方向 斜向走动时要考虑相邻的是不是障碍物
if (
this.gridsList[col - i][row].type == AstarGridType.Hider ||
this.gridsList[col][row - j].type == AstarGridType.Hider
) {
continue
}
} else {
// 四方形行走
if (Math.abs(i) == Math.abs(j)) {
continue
}
}
// 计算g值
let g =
curGrid.g +
Math.floor(Math.sqrt(Math.pow(i * 10, 2)) + Math.pow(j * 10, 2))
if (
this.gridsList[col][row].g == 0 ||
this.gridsList[col][row].g > g
) {
this.gridsList[col][row].g = g
// 更新父节点
this.gridsList[col][row].parent = curGrid
}
// 计算h值 manhattan估算法
this.gridsList[col][row].h =
Math.abs(endPos.x - col) + Math.abs(endPos.y - row)
// 更新f值
this.gridsList[col][row].f =
this.gridsList[col][row].g + this.gridsList[col][row].h
// 如果不在开放列表里则添加到开放列表里
if (this.openList.indexOf(this.gridsList[col][row]) < 0) {
this.openList.push(this.gridsList[col][row])
}
// // 重新按照f值排序升序排列)
}
}
}
}
// 遍历完四周节点后把当前节点加入关闭列表
this.closeList.push(curGrid)
// 从开放列表把当前节点移除
this.openList.splice(this.openList.indexOf(curGrid), 1)
if (this.openList.length <= 0) {
// Logger.log(this,"find path failed.");
this.path = []
if (callback) {
callback(this.path)
}
break
}
// 重新按照f值排序升序排列)
this.openList.sort((x, y) => {
return x.f - y.f
})
}
}
onDestroy() {} /**
* 生成路径
* @param grid
*/
private generatePath(grid: AstarGrid) {
this.path.push(grid)
while (grid.parent) {
grid = grid.parent
this.path.push(grid)
}
return this.path
}
onDestroy() {
}
} }

View File

@@ -1,19 +1,18 @@
import { _decorator } from 'cc'
import SoundPrefab from '../../engine/uicomponent/SoundPrefab' import SoundPrefab from '../../engine/uicomponent/SoundPrefab'
import MusicPrefab from '../../engine/uicomponent/MusicPrefab' import MusicPrefab from '../../engine/uicomponent/MusicPrefab'
import RandomUtil from '../../engine/utils/RandomUtil' import RandomUtil from '../../engine/utils/RandomUtil'
export default class GameMusicHelper { export default class GameMusicHelper {
public static playBg() { public static playBg() {
let randomIndex: number = RandomUtil.nextInt(1, 3) let randomIndex: number = RandomUtil.nextInt(1, 3)
MusicPrefab.play('background_' + randomIndex) MusicPrefab.play('background_' + randomIndex)
} }
public static playFishDead(fishType: number) { public static playFishDead(fishType: number) {
SoundPrefab.play('deadfish_' + fishType) SoundPrefab.play('deadfish_' + fishType)
} }
public static playFire() { public static playFire() {
SoundPrefab.play('fire') SoundPrefab.play('fire')
} }
} }

View File

@@ -1,64 +1,64 @@
import { error, game, _decorator } from 'cc' import { error, game } from 'cc'
import DarkLayer from '../../engine/uicomponent/DarkLayer' import DarkLayer from '../../engine/uicomponent/DarkLayer'
import LoadingPrefab from '../../engine/uicomponent/LoadingPrefab' import LoadingPrefab from '../../engine/uicomponent/LoadingPrefab'
import LoadingScenePrefab from '../../engine/uicomponent/LoadingScenePrefab' import LoadingScenePrefab from '../../engine/uicomponent/LoadingScenePrefab'
import MusicPrefab from '../../engine/uicomponent/MusicPrefab' import MusicPrefab from '../../engine/uicomponent/MusicPrefab'
import Progress from '../../engine/uicomponent/Progress' import Progress from '../../engine/uicomponent/Progress'
import SoundPrefab from '../../engine/uicomponent/SoundPrefab' import SoundPrefab from '../../engine/uicomponent/SoundPrefab'
import { Logger } from '../../engine/utils/Logger'
import ResourcePrefab from '../prefab/ResourcePrefab' import ResourcePrefab from '../prefab/ResourcePrefab'
import ShaderMaterialPrefab from '../prefab/ShaderMaterialPrefab' import ShaderMaterialPrefab from '../prefab/ShaderMaterialPrefab'
export default class ResourcePreload { export default class ResourcePreload {
public static instance: ResourcePreload = new ResourcePreload() public static instance: ResourcePreload = new ResourcePreload()
private isPreloaded: boolean = false private isPreloaded: boolean = false
private totalNum: number = 6 private totalNum: number = 6
private nowIndex: number = 0 private nowIndex: number = 0
private progress: Progress private progress: Progress
public async preLoad(callback: Function, progress: Progress) {
if (this.isPreloaded) {
callback()
return
}
this.isPreloaded = true
this.progress = progress
if (this.progress) {
progress.updateProgress(this.nowIndex, this.totalNum)
}
await LoadingPrefab.preLoad() //1
this.finishOneItemLoad()
await DarkLayer.preLoad() //2
this.finishOneItemLoad()
await MusicPrefab.preLoad() //3
this.finishOneItemLoad()
await SoundPrefab.preLoad() //4
this.finishOneItemLoad()
await ResourcePrefab.preLoad() //5
this.finishOneItemLoad()
await ShaderMaterialPrefab.preLoad() //6
this.finishOneItemLoad() //
callback()
}
private finishOneItemLoad() { public async preLoad(callback: Function, progress: Progress) {
this.nowIndex++ if (this.isPreloaded) {
if (this.progress) { callback()
this.progress.updateProgress(this.nowIndex, this.totalNum) return
} }
} this.isPreloaded = true
this.progress = progress
if (this.progress) {
progress.updateProgress(this.nowIndex, this.totalNum)
}
await LoadingPrefab.preLoad() //1
this.finishOneItemLoad()
await DarkLayer.preLoad() //2
this.finishOneItemLoad()
await MusicPrefab.preLoad() //3
this.finishOneItemLoad()
await SoundPrefab.preLoad() //4
this.finishOneItemLoad()
await ResourcePrefab.preLoad() //5
this.finishOneItemLoad()
await ShaderMaterialPrefab.preLoad() //6
this.finishOneItemLoad() //
callback()
}
public restartGame() { private finishOneItemLoad() {
this.isPreloaded = false this.nowIndex++
// GameSocket.getInstance().closeSocket(false); if (this.progress) {
LoadingScenePrefab.clear() this.progress.updateProgress(this.nowIndex, this.totalNum)
LoadingPrefab.clear() }
error('需要获取游戏里所有的AudioSource停止音乐') }
//audioEngine.stopAll();
// VersionManager.instance.releaseAll(); public restartGame() {
MusicPrefab.destory() this.isPreloaded = false
SoundPrefab.destory() // GameSocket.getInstance().closeSocket(false);
ResourcePrefab.clear() LoadingScenePrefab.clear()
game.restart() LoadingPrefab.clear()
} error('需要获取游戏里所有的AudioSource停止音乐')
//audioEngine.stopAll();
// VersionManager.instance.releaseAll();
MusicPrefab.destory()
SoundPrefab.destory()
ResourcePrefab.clear()
game.restart()
}
} }

View File

@@ -1,7 +1,7 @@
import { tween, Node } from 'cc' import { Node, tween } from 'cc'
export default class TimeHelper { export default class TimeHelper {
public static exeNextFrame(node: Node, callback: Function) { public static exeNextFrame(node: Node, callback: Function) {
tween(node).delay(0.02).call(callback).start() tween(node).delay(0.02).call(callback).start()
} }
} }

View File

@@ -1,9 +1,10 @@
import { _decorator, Component, Node } from 'cc' import { _decorator, Component } from 'cc'
const { ccclass, property } = _decorator const { ccclass, property } = _decorator
@ccclass('UIRoot') @ccclass('UIRoot')
export class UIRoot extends Component { export class UIRoot extends Component {
public static Instance public static Instance: UIRoot
onLoad() { onLoad() {
UIRoot.Instance = this UIRoot.Instance = this
} }

View File

@@ -6,5 +6,19 @@
"version": "3.8.2" "version": "3.8.2"
}, },
"_sourceId": "f769f6bf-2fe4-41a7-b7ad-f38f57e2d1b9", "_sourceId": "f769f6bf-2fe4-41a7-b7ad-f38f57e2d1b9",
"_storeId": "2898572b8dca79ebffc4f4584f234c2c" "_storeId": "2898572b8dca79ebffc4f4584f234c2c",
"devDependencies": {
"@eslint/eslintrc": "^3.0.2",
"@eslint/js": "^9.0.0",
"@typescript-eslint/eslint-plugin": "^6.4.0",
"acorn": "^8.11.3",
"eslint": "^9.0.0",
"eslint-config-standard-with-typescript": "^43.0.1",
"eslint-plugin-import": "^2.29.1",
"eslint-plugin-n": "^16.6.2",
"eslint-plugin-promise": "^6.1.1",
"globals": "^15.0.0",
"prettier": "^3.2.5",
"typescript": "^5.4.5"
}
} }

1832
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,7 +1,7 @@
{ {
"__version__": "3.0.5", "__version__": "3.0.5",
"game": { "game": {
"name": "未知游戏", "name": "UNKNOW GAME",
"app_id": "UNKNOW", "app_id": "UNKNOW",
"c_id": "0" "c_id": "0"
}, },

View File

@@ -4,19 +4,19 @@
"customSplash": { "customSplash": {
"id": "customSplash", "id": "customSplash",
"label": "customSplash", "label": "customSplash",
"enable": true, "enable": false,
"customSplash": { "customSplash": {
"complete": false, "complete": false,
"form": "https://creator-api.cocos.com/api/form/show?sid=5d73e8c847732207609c34c0adf271fb" "form": "https://creator-api.cocos.com/api/form/show?"
} }
}, },
"removeSplash": { "removeSplash": {
"id": "removeSplash", "id": "removeSplash",
"label": "removeSplash", "label": "removeSplash",
"enable": true, "enable": false,
"removeSplash": { "removeSplash": {
"complete": true, "complete": false,
"form": "https://creator-api.cocos.com/api/form/show?sid=5d73e8c847732207609c34c0adf271fb" "form": "https://creator-api.cocos.com/api/form/show?"
} }
} }
} }