feat: update web api

main
tiendat3699 2024-04-26 14:48:20 +07:00
parent 81635f7de8
commit 26c032a861
7 changed files with 191 additions and 138 deletions

View File

@ -1,37 +1,24 @@
import { _decorator } from 'cc'; import CryptoES from 'crypto-es';
import * as CryptoES from 'crypto-es'; import { get, post } from './HttpRequest';
import Singleton from '../Singleton';
export let CryptoESDefault = CryptoES.default;
const { ccclass, property } = _decorator; export default class BEConnector {
private static token: string;
@ccclass('BEConnector') private static skinId: string;
export default class BEConnector extends Singleton<BEConnector>('BEConnector') { private static tournamentId: string;
private token: string; private static key: string;
private skinId: string; private static deviceInfo: string;
private tournamentId: string;
private key: string;
private deviceInfo: string;
// Ticket info // Ticket info
public numberTicket: number; public static numberTicket: number;
public maxScore: number; public static maxScore: number;
public currentScore: number; public static currentScore: number;
public topScores: [] = []; public static topScores: [] = [];
private mileStone: string; private static mileStone: string;
public static gameScore: number = 0;
private static gameURL: string = '';
public gameScore: number = 0; public static getGameData() {
private gameURL: string = '';
constructor() {
super();
this.getGameData();
}
public getGameData() {
let url = new URLSearchParams(window.location.search); let url = new URLSearchParams(window.location.search);
this.token = url.get('token'); this.token = url.get('token');
this.skinId = url.get('skinId'); this.skinId = url.get('skinId');
this.tournamentId = url.get('tournamentId'); this.tournamentId = url.get('tournamentId');
@ -44,54 +31,40 @@ export default class BEConnector extends Singleton<BEConnector>('BEConnector') {
this.gameURL = ENV_CONFIG[url.get('env')]; this.gameURL = ENV_CONFIG[url.get('env')];
} }
public async getInfo() { public static async authenticate() {
try { try {
const res = await fetch(`${this.gameURL}/promotions/detail/${this.tournamentId}`); const res = await get(
const json = await res.json(); `${this.gameURL}/promotions/authenticate-tournament?token=${this.token}&tournamentId=${this.tournamentId}&skinId=${this.skinId}&deviceInfo=${this.deviceInfo}`,
this.topScores = json.tScores; );
const data = await res.json();
if (data.ResultCode == 1) {
this.key = data.Data.Key;
console.log('Authenticate success');
}
} catch (error) {
console.log('Authenticate failed', error);
}
}
public static async ticketMinus(type: 'auth' | 'revive') {
const numberTicket = type === 'auth' ? 1 : this.getTicketCanBeMinus();
const dataEncrypted: string = this.getDataEncrypted({ type: type, total: numberTicket });
const JsonData = JSON.stringify({ data: dataEncrypted });
try {
await post(
`${this.gameURL}/promotions/ticket-minus/${this.tournamentId}/${this.skinId}?cocos=1`,
this.token,
JsonData,
);
this.numberTicket -= numberTicket;
return numberTicket;
} catch (error) { } catch (error) {
console.log(error); console.log(error);
} }
} }
public async authenticate() { public static calculatingTicketToContinue(scoreRange: object, yourScore: number) {
await fetch(
`${this.gameURL}/promotions/authenticate-tournament?token=${this.token}&tournamentId=${this.tournamentId}&skinId=${this.skinId}&deviceInfo=${this.deviceInfo}`,
)
.then((response) => {
if (response.ok) {
return response.json();
}
})
.then((data) => {
if (data.ResultCode == 1) {
this.key = data.Data.Key;
console.log('authen success', this.key);
} else {
throw new Error('');
}
})
.catch((err) => console.log('authen failed'));
}
public ticketMinus(type: 'auth' | 'revive') {
let numberTicket = type === 'auth' ? 1 : this.getTicketCanBeMinus();
let dataEncrypted: string = this.getDataEncrypted({ type: type, total: numberTicket });
fetch(`${this.gameURL}/promotions/ticket-minus/${this.tournamentId}/${this.skinId}?cocos=1`, {
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
'x-access-refactor-token': this.token,
},
method: 'POST',
body: JSON.stringify({ data: dataEncrypted }),
}).then(() => {
this.numberTicket -= numberTicket;
});
}
public calculatingTicketToContinue(scoreRange: object, yourScore: number) {
let closestMilestone: number = 0; let closestMilestone: number = 0;
for (const milestone in scoreRange) { for (const milestone in scoreRange) {
if (parseInt(milestone) <= yourScore) { if (parseInt(milestone) <= yourScore) {
@ -105,25 +78,25 @@ export default class BEConnector extends Singleton<BEConnector>('BEConnector') {
return closestMilestone; return closestMilestone;
} }
public async checkGameScoreTicket() { public static async checkGameScoreTicket() {
let totalScore: number = this.gameScore; const totalScore: number = this.gameScore;
let dataEncrypted: string = this.getDataEncrypted({ const dataEncrypted: string = this.getDataEncrypted({
score: totalScore, score: totalScore,
ticket: this.getTicketCanBeMinus(), ticket: this.getTicketCanBeMinus(),
}); });
const data = JSON.stringify({ data: dataEncrypted });
await fetch(`${this.gameURL}/promotions/check-game-score-ticket/${this.tournamentId}/${this.skinId}?cocos=1`, { try {
headers: { await post(
Accept: 'application/json', `${this.gameURL}/promotions/check-game-score-ticket/${this.tournamentId}/${this.skinId}?cocos=1`,
'Content-Type': 'application/json', this.token,
'x-access-refactor-token': this.token, data,
}, );
method: 'POST', } catch (error) {
body: JSON.stringify({ data: dataEncrypted }), console.log(error);
}); }
} }
public postMessage() { public static postMessage() {
let totalScore: number = this.gameScore + this.currentScore; let totalScore: number = this.gameScore + this.currentScore;
window.parent.postMessage( window.parent.postMessage(
JSON.stringify({ JSON.stringify({
@ -136,47 +109,45 @@ export default class BEConnector extends Singleton<BEConnector>('BEConnector') {
); );
} }
public postScoreToServer() { public static async postScoreToServer() {
let dataEncrypted: string = this.getDataEncrypted({ const dataEncrypted: string = this.getDataEncrypted({
Score: this.gameScore, Score: this.gameScore,
TournamentId: this.tournamentId, TournamentId: this.tournamentId,
SkinId: this.skinId, SkinId: this.skinId,
}); });
fetch( const data = JSON.stringify({ data: dataEncrypted });
`${this.gameURL}/promotions/store-score-tournament?tournamentId=${this.tournamentId}&skinId=${this.skinId}&cocos=1`, try {
{ const res = await post(
headers: { `${this.gameURL}/promotions/store-score-tournament?tournamentId=${this.tournamentId}&skinId=${this.skinId}&cocos=1`,
Accept: 'application/json', this.token,
'Content-Type': 'application/json', data,
'x-access-refactor-token': this.token, );
},
method: 'POST',
body: JSON.stringify({ data: dataEncrypted }),
},
).catch((err) => console.log(err));
console.log('send score to server: ' + this.gameScore);
window.parent.postMessage( console.log('send score to server: ' + this.gameScore);
JSON.stringify({ window.parent.postMessage(
error: false, JSON.stringify({
message: 'Hello World', error: false,
score: this.gameScore + this.currentScore, message: 'Hello World',
type: 'game_tournament', score: this.gameScore + this.currentScore,
}), type: 'game_tournament',
'*', }),
); '*',
);
} catch (error) {
console.log(error);
}
} }
private getDataEncrypted(data: any): string { private static getDataEncrypted(data: any): string {
return CryptoESDefault.AES.encrypt(JSON.stringify(data), this.key, { return CryptoES.AES.encrypt(JSON.stringify(data), this.key, {
iv: CryptoESDefault.enc.Utf8.parse('16'), iv: CryptoES.enc.Utf8.parse('16'),
mode: CryptoESDefault.mode.CBC, mode: CryptoES.mode.CBC,
padding: CryptoESDefault.pad.Pkcs7, padding: CryptoES.pad.Pkcs7,
}).toString(); }).toString();
} }
public getTicketCanBeMinus() { public static getTicketCanBeMinus() {
if (!this.mileStone) return 0; if (!this.mileStone) return 0;
let mileStone = JSON.parse(this.mileStone); let mileStone = JSON.parse(this.mileStone);
let currentScore = this.gameScore; let currentScore = this.gameScore;
@ -184,7 +155,7 @@ export default class BEConnector extends Singleton<BEConnector>('BEConnector') {
return total; return total;
} }
public canRelive() { public static canRelive() {
return this.numberTicket > this.getTicketCanBeMinus(); return this.numberTicket > this.getTicketCanBeMinus();
} }
} }

View File

@ -0,0 +1,67 @@
const headersInit = {
Accept: 'application/json',
'Content-Type': 'application/json',
};
export const get = async (path: RequestInfo) => {
const res = await fetch(path, {
method: 'GET',
});
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
};
export const post = async (path: RequestInfo, token?: string, data?: string) => {
const res = await fetch(path, {
method: 'POST',
headers: {
...headersInit,
'x-access-refactor-token': token,
},
body: data,
});
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
};
export const put = async (path: RequestInfo, token?: string, data?: string) => {
const res = await fetch(path, {
method: 'PUT',
headers: {
...headersInit,
'x-access-refactor-token': token,
},
body: data,
});
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
};
export const del = async (path: RequestInfo, token?: string, data?: string) => {
const res = await fetch(path, {
method: 'DELETE',
headers: {
...headersInit,
'x-access-refactor-token': token,
},
body: data,
});
if (!res.ok) {
throw new Error(res.statusText);
}
return res;
};

View File

@ -0,0 +1,9 @@
{
"ver": "4.0.23",
"importer": "typescript",
"imported": true,
"uuid": "04c2a240-38c0-4d9c-993a-3773d709137f",
"files": [],
"subMetas": {},
"userData": {}
}

View File

@ -16,6 +16,7 @@ enum GameEvent {
ControlTouchStart, ControlTouchStart,
ControlTouchEnd, ControlTouchEnd,
WarningTime, WarningTime,
TicketUpdate,
} }
export interface GameEventCallbackMap { export interface GameEventCallbackMap {
@ -30,6 +31,7 @@ export interface GameEventCallbackMap {
[GameEvent.ControlTouchStart]: (touchSide: ControllerSide) => void; [GameEvent.ControlTouchStart]: (touchSide: ControllerSide) => void;
[GameEvent.ControlTouchEnd]: (touchSide: ControllerSide) => void; [GameEvent.ControlTouchEnd]: (touchSide: ControllerSide) => void;
[GameEvent.WarningTime]: (warning: boolean) => void; [GameEvent.WarningTime]: (warning: boolean) => void;
[GameEvent.TicketUpdate]: (ticket: number) => void;
} }
export interface GameEventArgMap { export interface GameEventArgMap {
@ -44,6 +46,7 @@ export interface GameEventArgMap {
[GameEvent.ControlTouchStart]: ControllerSide; [GameEvent.ControlTouchStart]: ControllerSide;
[GameEvent.ControlTouchEnd]: ControllerSide; [GameEvent.ControlTouchEnd]: ControllerSide;
[GameEvent.WarningTime]: boolean; [GameEvent.WarningTime]: boolean;
[GameEvent.TicketUpdate]: number;
} }
export default GameEvent; export default GameEvent;

View File

@ -35,7 +35,7 @@ window.addEventListener('message', (data) => {
if (objectRes) { if (objectRes) {
const { type, value } = objectRes; const { type, value } = objectRes;
if (type === 'newTicket') { if (type === 'newTicket') {
BEConnector.instance.numberTicket += value; BEConnector.numberTicket += value;
GameManager.instance.gameRelive(); GameManager.instance.gameRelive();
} }
} }
@ -120,12 +120,12 @@ export class GameManager extends Singleton<GameManager>() {
super.onLoad(); super.onLoad();
this._ballPool = new ObjectPool(this._ballPrefab, 10, true, Ball); this._ballPool = new ObjectPool(this._ballPrefab, 10, true, Ball);
this._FloatingScorePool = new ObjectPool(this._floatingScoreText, 10, true); this._FloatingScorePool = new ObjectPool(this._floatingScoreText, 10, true);
BEConnector.getGameData();
if (this._colliderDebug) PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Shape; if (this._colliderDebug) PhysicsSystem2D.instance.debugDrawFlags = EPhysics2DDrawFlags.Shape;
} }
protected start(): void { protected start(): void {
this.changeGameState(GameState.Init); this.changeGameState(GameState.Init);
BEConnector.instance.getInfo();
} }
protected update(dt: number): void { protected update(dt: number): void {
@ -146,23 +146,25 @@ export class GameManager extends Singleton<GameManager>() {
private async changeGameState(state: GameState) { private async changeGameState(state: GameState) {
this._gameState = state; this._gameState = state;
EventManger.instance.emit(GameEvent.GameStateChange, this._gameState); EventManger.instance.emit(GameEvent.GameStateChange, this._gameState);
let ticket = 0;
switch (state) { switch (state) {
case GameState.Init: case GameState.Init:
BEConnector.instance.authenticate(); BEConnector.authenticate();
break; break;
case GameState.Ready: case GameState.Ready:
break; break;
case GameState.Playing: case GameState.Playing:
this.countTime(); this.countTime();
BEConnector.instance.ticketMinus('auth'); ticket = await BEConnector.ticketMinus('auth');
EventManger.instance.emit(GameEvent.TicketUpdate, ticket);
break; break;
case GameState.GameOver: case GameState.GameOver:
break; break;
case GameState.End: case GameState.End:
break; break;
case GameState.Relive: case GameState.Relive:
BEConnector.instance.ticketMinus('revive'); ticket = await BEConnector.ticketMinus('revive');
EventManger.instance.emit(GameEvent.TicketUpdate, ticket);
break; break;
default: default:
throw new Error(`Argument Out Of Range Exception: ${GameState[state]}`); throw new Error(`Argument Out Of Range Exception: ${GameState[state]}`);
@ -306,7 +308,7 @@ export class GameManager extends Singleton<GameManager>() {
this.DisableAllBooster(); this.DisableAllBooster();
SoundManager.instance.playBGM(this._gameOverMusic); SoundManager.instance.playBGM(this._gameOverMusic);
StickerManager.instance.showLabel('TIME UP!!!', { color: new Color('#ed3a18'), outLineColor: Color.WHITE }); StickerManager.instance.showLabel('TIME UP!!!', { color: new Color('#ed3a18'), outLineColor: Color.WHITE });
BEConnector.instance.gameScore = this.score; BEConnector.gameScore = this.score;
if (this.isReplayed) { if (this.isReplayed) {
this.changeGameState(GameState.End); this.changeGameState(GameState.End);
return; return;

View File

@ -48,11 +48,11 @@ export class GameOverPanel extends Component {
} }
protected onEnable(): void { protected onEnable(): void {
this._ticketMinus.string = '-' + BEConnector.instance.getTicketCanBeMinus().toString(); this._ticketMinus.string = '-' + BEConnector.getTicketCanBeMinus().toString();
this.topScore.string = BEConnector.instance.maxScore.toString(); this.topScore.string = BEConnector.maxScore.toString();
this.yourScore.string = BEConnector.instance.currentScore.toString(); this.yourScore.string = BEConnector.currentScore.toString();
const gameScore = GameManager.instance.score; const gameScore = GameManager.instance.score;
const currentScore = BEConnector.instance.currentScore; const currentScore = BEConnector.currentScore;
this.playCollectEffect(gameScore, currentScore); this.playCollectEffect(gameScore, currentScore);
this.scheduleOnce(this.endGame, 60); this.scheduleOnce(this.endGame, 60);
this._active = true; this._active = true;
@ -74,7 +74,7 @@ export class GameOverPanel extends Component {
this._end = true; this._end = true;
if (this._active) { if (this._active) {
await Utilities.delay(1); await Utilities.delay(1);
BEConnector.instance.postScoreToServer(); BEConnector.postScoreToServer();
} }
break; break;
case GameState.Relive: case GameState.Relive:
@ -85,9 +85,8 @@ export class GameOverPanel extends Component {
onClickYesButton() { onClickYesButton() {
if (this._clicked) return; if (this._clicked) return;
this._clicked = true; this._clicked = true;
if (BEConnector.instance.canRelive()) { if (BEConnector.canRelive()) {
BEConnector.instance BEConnector.checkGameScoreTicket()
.checkGameScoreTicket()
.then(() => { .then(() => {
this._clicked = false; this._clicked = false;
GameManager.instance.gameRelive(); GameManager.instance.gameRelive();
@ -98,7 +97,7 @@ export class GameOverPanel extends Component {
}); });
} else { } else {
this._clicked = false; this._clicked = false;
BEConnector.instance.postMessage(); BEConnector.postMessage();
} }
} }
@ -169,7 +168,7 @@ export class GameOverPanel extends Component {
.start(); .start();
if (!this._end) return; if (!this._end) return;
await Utilities.delay(1); await Utilities.delay(1);
BEConnector.instance.postScoreToServer(); BEConnector.postScoreToServer();
} }
} }
} }

View File

@ -1,4 +1,4 @@
import { _decorator, Color, Component, Label, LabelOutline, Node, ParticleSystem, Tween, tween, Vec3 } from 'cc'; import { _decorator, Color, Component, Label, Node, ParticleSystem, Vec3 } from 'cc';
import { EventManger } from '../Manager/EventManger'; import { EventManger } from '../Manager/EventManger';
import GameEvent from '../Events/GameEvent'; import GameEvent from '../Events/GameEvent';
import ScoreType from '../Enum/ScoreType'; import ScoreType from '../Enum/ScoreType';
@ -33,6 +33,7 @@ export class UIController extends Component {
EventManger.instance.on(GameEvent.MultiBall, this.onMultiBall, this); EventManger.instance.on(GameEvent.MultiBall, this.onMultiBall, this);
EventManger.instance.on(GameEvent.BoosterActive, this.onBoosterActive, this); EventManger.instance.on(GameEvent.BoosterActive, this.onBoosterActive, this);
EventManger.instance.on(GameEvent.BoosterDisable, this.onBoosterDisable, this); EventManger.instance.on(GameEvent.BoosterDisable, this.onBoosterDisable, this);
EventManger.instance.on(GameEvent.TicketUpdate, this.onTicketUpdate, this);
} }
private async onScore(score: number, points: number, type: ScoreType) { private async onScore(score: number, points: number, type: ScoreType) {
@ -46,11 +47,15 @@ export class UIController extends Component {
StickerManager.instance.Show('BallOut'); StickerManager.instance.Show('BallOut');
} }
private onTicketUpdate(ticket: number) {
this._ticketLabel.string = ticket.toString();
}
private async onGameStateChange(state: GameState) { private async onGameStateChange(state: GameState) {
switch (state) { switch (state) {
case GameState.Init: case GameState.Init:
this._startPanel.active = true; this._startPanel.active = true;
this._ticketLabel.string = BEConnector.instance.numberTicket.toString(); this._ticketLabel.string = BEConnector.numberTicket.toString();
this._scoreLabel.string = '0'; this._scoreLabel.string = '0';
break; break;
case GameState.Ready: case GameState.Ready:
@ -59,7 +64,6 @@ export class UIController extends Component {
break; break;
case GameState.Playing: case GameState.Playing:
this._overPanel.active = false; this._overPanel.active = false;
this._ticketLabel.string = BEConnector.instance.numberTicket.toString();
break; break;
case GameState.GameOver: case GameState.GameOver:
@ -74,8 +78,6 @@ export class UIController extends Component {
break; break;
case GameState.Relive: case GameState.Relive:
this._overPanel.active = false; this._overPanel.active = false;
this._ticketLabel.string = BEConnector.instance.numberTicket.toString();
break; break;
} }
} }