[add] first

This commit is contained in:
2023-11-07 09:17:57 +08:00
commit 23924175a2
1102 changed files with 313997 additions and 0 deletions

405
goberts/GOBERTS.d.ts vendored Normal file
View File

@@ -0,0 +1,405 @@
export declare interface ActionArgs {
sender: string;
gameData: string;
roomId: string;
SDK: {
/**
* 请求补帧
* @param beginFrameId - 起始帧号
* @param size - 请求帧数量
*/
requestFrame: (beginFrameId: number, size: number) => Promise<void>;
sendData: (data: string, players?: string[]) => Promise<void>;
setCache: (key: string, value: string, expireTime: number) => Promise<void>;
getCache: (key: string) => Promise<CacheValue>;
deleteCache: (key: string) => Promise<void>;
setCacheIfNotExist: (key: string, value: string, expireTime: number) => Promise<void>;
getRoomInfo: () => Promise<RoomInfo>;
log: {
info: (message: string) => void;
warn: (message: string) => void;
error: (message: string) => void;
};
updateRoomProperties: (updateRoomInfo: UpdateRoomInfo) => Promise<void>;
removePlayer: (playerId: string) => Promise<void>;
dismiss: () => Promise<void>;
getAutoFrame: () => boolean;
getFrameRate: () => number;
};
}
declare interface ArgsConfig {
sender: string;
roomId: string;
appId: string;
ticket: string;
domain: string;
projectId: string;
gameData?: string;
autoFrame: boolean;
frameRate: number;
frameRequesting: boolean;
frameRequestSize: number;
logger?: any;
}
export declare const enum AutoFrame {
AUTO_FRAME_OFF = 0,
AUTO_FRAME_ON = 1
}
declare interface BaseResponse {
ret: {
code: number;
msg?: string;
};
}
export declare interface CacheValue {
value?: string;
}
declare interface CacheValue_2 {
value?: string;
}
export declare type CommonFunc = (args: ActionArgs) => void;
declare interface CreateChannelResponse extends BaseResponse {
data: CreateChannelResponseData;
}
declare interface CreateChannelResponseData {
setupTicket: string;
joinTicket: string;
}
export declare type ErrorFunc = (error: GOBEError, args: ActionArgs) => void;
/**
* 附加信息
* @public
*/
export declare interface FrameExtInfo {
seed: number;
}
/**
* 帧数据信息
* @public
*/
export declare interface FrameInfo extends FramePlayerInfo {
data: string[];
timestamp: number;
}
/**
* 帧数据玩家信息
* @public
*/
export declare interface FramePlayerInfo {
playerId: string;
}
export declare type FramePlayerInfoFunc = (playerInfo: FramePlayerInfo, args: ActionArgs) => void;
/**
* 帧数据玩家信息
* @public
*/
export declare interface FramePlayerPropInfo {
playerId: string;
customProp: string;
}
/**
* 帧数据玩家信息
* @public
*/
export declare interface FramePlayerStatusInfo {
playerId: string;
customStatus: number;
}
/**
* 帧数据房间信息
* @public
*/
export declare interface FrameRoomInfo {
roomId: string;
roomName: string;
customProp: string;
roomOwner: string;
isPrivate: number;
isLock: boolean;
}
export declare interface GameServer {
onCreateRoom: CommonFunc;
onConnect?: CommonFunc;
onDisconnect?: CommonFunc;
onRecvFromClient?: CommonFunc;
onDestroyRoom: CommonFunc;
onJoin?: FramePlayerInfoFunc;
onLeave?: FramePlayerInfoFunc;
onStartFrameSync?: CommonFunc;
onStopFrameSync?: CommonFunc;
onRecvFrame?: OnRecvFrameFunc;
onRecvFromClientV2?: OnRecvFromClientFunc;
onRequestFrameError?: ErrorFunc;
onRoomPropertiesChange?: OnRoomPropertiesChangeFunc;
onUpdateCustomProperties?: OnUpdateCustomPropertiesFunc;
onUpdateCustomStatus?: OnUpdateCustomStatusFunc;
onRealTimeServerDisconnected?: CommonFunc;
onRealTimeServerConnected?: CommonFunc;
}
declare interface GetCacheResponse extends BaseResponse {
value?: string;
}
declare interface GetRoomInfoResponse extends BaseResponse {
roomInfo: RoomInfo_2;
}
export declare interface gobeDevloperCode {
appId: string;
gameServer: GameServer;
}
/**
* 自定义错误类
* @public
*/
export declare class GOBEError extends Error {
code: number;
constructor(code: number, message?: string);
}
export declare const enum ImType {
ALL_PLAYERS_EXCEPT_ME = 1,
SPECIFILED_PLAYERS = 2
}
/**
* 云侧sdk接口定义文档
*/
declare interface MethodRoute {
createRoom: (request: ServerLessMethodRequest) => void;
}
export declare const myHandler: (event: serverInterface.ServerLessEvent, context: serverInterface.ServerLessContext, callback: (res: any) => void, logger: any) => void;
export declare type OnRecvFrameFunc = (msg: RecvFrameMessage | RecvFrameMessage[], args: ActionArgs) => void;
export declare type OnRecvFromClientFunc = (msg: RecvFromClientInfo, args: ActionArgs) => void;
export declare type OnRoomPropertiesChangeFunc = (msg: FrameRoomInfo, args: ActionArgs) => void;
export declare type OnUpdateCustomPropertiesFunc = (player: FramePlayerPropInfo, args: ActionArgs) => void;
export declare type OnUpdateCustomStatusFunc = (msg: FramePlayerStatusInfo, args: ActionArgs) => void;
export declare interface PlayerInfo {
playerId: string;
status?: number;
customPlayerStatus?: number;
customPlayerProperties?: string;
teamId?: string;
isRobot?: number;
robotName?: string;
matchParams?: Record<string, string>;
}
declare interface PlayerInfo_2 {
playerId: string;
status?: number;
customPlayerStatus?: number;
customPlayerProperties?: string;
teamId?: string;
isRobot?: number;
robotName?: string;
matchParams?: Record<string, string>;
}
/**
* 帧广播消息
* @public
*/
export declare interface RecvFrameMessage extends ServerFrameMessage {
isReplay: boolean;
time: number;
}
/**
* 房间消息广播回调参数
* @param roomId - 房间ID
* @param sendPlayerId - 发送者playerId
* @param msg - 消息内容
* @public
*/
export declare interface RecvFromClientInfo {
srcPlayer: string;
msg: string;
}
export declare interface RoomInfo {
appId: string;
roomId: string;
roomType: string;
roomCode: string;
roomName: string;
roomStatus: number;
customRoomProperties: string;
ownerId: string;
maxPlayers: number;
players: PlayerInfo[];
router: RouterInfo;
isPrivate: number;
createTime: number;
}
declare interface RoomInfo_2 {
appId: string;
roomId: string;
roomType: string;
roomCode: string;
roomName: string;
roomStatus: number;
customRoomProperties: string;
ownerId: string;
maxPlayers: number;
players: PlayerInfo_2[];
router: RouterInfo_2;
isPrivate: number;
createTime: number;
}
export declare interface RouterInfo {
routerId: number;
routerType: number;
routerAddr: string;
}
declare interface RouterInfo_2 {
routerId: number;
routerType: number;
routerAddr: string;
}
/**
* 服务端 ACK 消息
*/
declare interface ServerAckMessage {
rtnCode: number;
msg: string;
}
/**
* 服务端推送消息
* @public
*/
export declare interface ServerFrameMessage {
currentRoomFrameId: number;
frameInfo: FrameInfo[];
ext: FrameExtInfo;
}
/**
* 服务端返回帧数据玩家信息
* @public
*/
export declare interface ServerFramePlayerInfo extends FramePlayerInfo {
extraInfo?: string;
}
declare namespace serverInterface {
export {
MethodRoute,
ServerLessEvent,
ServerLessEventBody,
ServerLessEventBodyRequest,
ServerLessContext,
ServerLessMethodRequest,
ArgsConfig,
ServerAckMessage,
BaseResponse,
GetRoomInfoResponse,
CreateChannelResponse,
GetCacheResponse,
CreateChannelResponseData,
RoomInfo_2 as RoomInfo,
PlayerInfo_2 as PlayerInfo,
RouterInfo_2 as RouterInfo,
CacheValue_2 as CacheValue
}
}
declare interface ServerLessContext {
env: {
GOBE_EDGE_DOMAIN: string;
DEVELOPER_PROJECT_ID: string;
DEVELOPER_APP_ID: string;
WS_HEARTBEAT_CYCLE: string;
};
}
declare interface ServerLessEvent {
body: string;
headers: {
ticket: string;
};
}
declare interface ServerLessEventBody {
method: keyof MethodRoute;
request: string;
data: string;
}
declare interface ServerLessEventBodyRequest {
roomId: string;
operator?: string;
epAddress: string;
setupTicket: string;
joinTicket: string;
autoFrame: string;
frameRate: string;
}
declare interface ServerLessMethodRequest {
roomId: string;
operator?: string;
ticket: string;
domain: string;
data: string;
projectId: string;
logger: any;
appId: string;
epAddress: string;
setupTicket: string;
joinTicket: string;
autoFrame: string;
frameRate: string;
wsHeartbeatCycle: string;
}
/**
* 可以更新的房间信息属性
* @public
* @param roomName - 房间名称
* @param customRoomProperties - 房间自定义属性
* @param ownerId - 房主ID
* @param isPrivate - 是否私有
* @param isLock - 是否锁定房间 0非锁定允许加入房间1锁定不允许加入房间
*/
export declare interface UpdateRoomInfo {
roomName?: string;
customRoomProperties?: string;
ownerId?: string;
isPrivate?: number;
isLock?: number;
}
export { }
export as namespace GOBERTS

30
goberts/README.md Normal file
View File

@@ -0,0 +1,30 @@
## 联机对战实时同步服务开发框架说明
- 联机对战实时同步服务必要文件是 index.js。
- 该示例代码使用 TypeScript 开发,需要编译为 JavaScript 后才能使用。
- 开发者可以在此基础上修改 index.ts 文件进行开发。
- 开发完成后执行打包命令并上传构建后的 index.js 文件。
## 使用步骤
### 安装依赖
```
npm install
```
### 开发
- 根据自己的业务逻辑修改 index.ts
- 将 TypeScript 编译为 JavaScript
### 打包步骤
```
npm run build
```
- 该命令会将代码编译,并生成 index.js 文件,开发者将该 js 文件上传即可

86
goberts/index.js Normal file
View File

@@ -0,0 +1,86 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const gameServer = {
// 销毁房间回调接口
onDestroyRoom(args) {
},
// 创建房间回调接口
onCreateRoom(args) {
},
// 实时服务器websocket连接建立回调接口
onRealTimeServerConnected(args) {
},
// 实时服务器websocket连接断开回调接口
onRealTimeServerDisconnected(args) {
},
// 建立连接回调接口
onConnect(args) {
},
// 断开连接回调接口
onDisconnect(args) {
},
// 加入房间回调接口
onJoin(playerInfo, args) {
},
// 离开房间回调接口
onLeave(playerInfo, args) {
},
// 接收帧消息回调接口
onRecvFrame(msg, args) {
},
// // 接收客户端消息回调接口
onRecvFromClient(args) {
if(args.gameData == "dismiss"){
// 解散房间
args.SDK.dismiss().then(() => {
}).catch(err => {
})
}
else if(args.gameData == "start_game_time"){
var info = {msg:"start_game_time", time:(new Date).getTime()};
args.SDK.sendData(JSON.stringify(info)).then( ()=> {
// 发送游戏数据成功
}).catch( err => {
// 发送游戏数据失败
});
}
else{
args.SDK.sendData(args.gameData).then( ()=> {
// 发送游戏数据成功
}).catch( err => {
// 发送游戏数据失败
});
}
},
// 房间信息更新回调接口
onRoomPropertiesChange(msg, args) {
},
// 开始帧同步回调接口
onStartFrameSync(args) {
},
// 停止帧同步回调接口
onStopFrameSync(args) {
},
// 玩家属性更新回调接口
onUpdateCustomProperties(player, args) {
},
// 玩家状态更新回调接口
onUpdateCustomStatus(msg, args) {
},
// 请求补帧错误回调接口
onRequestFrameError(error, args) {
}
};
const gobeDeveloperCode = {
gameServer: gameServer,
appId: 'appId', // 需要手动修改
};
exports.gobeDeveloperCode = gobeDeveloperCode;

87
goberts/index.ts Normal file
View File

@@ -0,0 +1,87 @@
import GOBERTS, {FrameInfo} from './GOBERTS';
const gameServer: GOBERTS.GameServer = {
onDestroyRoom(args: GOBERTS.ActionArgs): void {
// do something
},
onCreateRoom(args: GOBERTS.ActionArgs): void {
args.SDK.getRoomInfo().then( rommInfo => {
// 获取房间信息成功
}).catch( err => {
// 获取房间信息失败
});
},
onRealTimeServerConnected(args: GOBERTS.ActionArgs): void {
// do something
},
onRealTimeServerDisconnected(args: GOBERTS.ActionArgs): void {
// do something
},
onConnect(args: GOBERTS.ActionArgs): void {
// do something
},
onDisconnect(args: GOBERTS.ActionArgs): void {
// do something
},
onJoin(playerInfo: GOBERTS.FramePlayerInfo, args: GOBERTS.ActionArgs): void {
// do something
},
onLeave(playerInfo: GOBERTS.FramePlayerInfo, args: GOBERTS.ActionArgs): void {
// do something
},
onRecvFrame(msg:GOBERTS.RecvFrameMessage | GOBERTS.RecvFrameMessage[], args: GOBERTS.ActionArgs):void {
let unhandleFrames: GOBERTS.RecvFrameMessage[] = Array.isArray(msg)? msg : [msg];
unhandleFrames.forEach(message => {
// seed frames which do not have user data
if (!message.frameInfo || message.frameInfo.length < 1) {
return;
};
// frames which have user data
message.frameInfo.forEach((frameData: FrameInfo) => {
let frameDataList: string[] = frameData.data;
if (frameDataList && frameDataList.length > 0) {
frameDataList.forEach(res => {
args.SDK.log.info('frameData=' + res);
});
}
});
});
},
onRecvFromClient(args: GOBERTS.ActionArgs): void {
args.SDK.getCache('example').then( value => {
// 获取缓存成功
}).catch( err => {
// 获取缓存失败
});
},
onRecvFromClientV2(msg: GOBERTS.RecvFromClientInfo, args: GOBERTS.ActionArgs): void {
// do something, onRecvFromClientV2和onRecvFromClient使用一个即可推荐使用V2
},
onRoomPropertiesChange(msg: GOBERTS.FrameRoomInfo, args: GOBERTS.ActionArgs): void {
// do something
},
onStartFrameSync(args: GOBERTS.ActionArgs): void {
// do something
},
onStopFrameSync(args: GOBERTS.ActionArgs): void {
// do something
},
onUpdateCustomProperties(player: GOBERTS.FramePlayerPropInfo, args: GOBERTS.ActionArgs): void {
// do something
},
onUpdateCustomStatus(msg: GOBERTS.FramePlayerStatusInfo, args: GOBERTS.ActionArgs): void {
// do something
},
onRequestFrameError(error: GOBERTS.GOBEError, args: GOBERTS.ActionArgs): void {
// do something
}
}
export const gobeDeveloperCode = {
gameServer: gameServer,
appId: 'your appId',
};

19
goberts/package.json Normal file
View File

@@ -0,0 +1,19 @@
{
"name": "goberts",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "rollup -c rollup.config.js"
},
"dependencies": {
"@types/node": "^18.7.18"
},
"devDependencies": {
"rollup": "^2.79.0",
"@rollup/plugin-typescript": "^8.3.0",
"ts-node": "^10.9.1",
"tslib": "^2.4.0",
"typescript": "^4.8.3"
}
}

15
goberts/rollup.config.js Normal file
View File

@@ -0,0 +1,15 @@
import typescript from '@rollup/plugin-typescript';
export default {
input: 'index.ts',
output: [
{
name: 'index',
file: 'index.js',
format: 'cjs',
},
],
plugins: [
typescript({ tsconfig: './tsconfig.build.json' }),
],
};

View File

@@ -0,0 +1,6 @@
{
"extends": "./tsconfig.json",
"exclude": [
"node_modules",
]
}

74
goberts/tsconfig.json Normal file
View File

@@ -0,0 +1,74 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', 'ES2021', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', 'react', 'react-jsx' or 'react-jsxdev'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./lib", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an 'override' modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Require undeclared properties from index signatures to use element accesses. */
/* Module Resolution Options */
"resolveJsonModule": true,
"moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}