小游戏管理
1. 游戏启动参数设置
初始化游戏启动参数
接口原型
gameHandle.setGameStartOptions(options)
参数说明
| 参数 | 数据类型 | 必填 | 属性说明 |
|---|---|---|---|
launchKey | String | 是 | 游戏启动项,支持游戏列表启动项,扫码启动项和最近启动项三种。 |
userId | String | 是 | 游戏用户 ID |
customScriptFiles | Array | 否 | js 脚本文件路径列表 |
customScriptContents | Array | 否 | Javascript 文本内容列表 |
enableVConsole | Boolean | 否 | 开启 vConsole, 更改开启或关闭需重启游戏,默认值为 false |
enableInspector | Boolean | 否 | 开启 Chrome DevTools 调试, 默认值为 false |
waitForInspect | Boolean | 否 | 在启动时等待 DevTools 连接, 默认值为 false |
enableDomainWhiteList | Boolean | 否 | 开启合法域名白名单,默认值为 false |
domainWhiteListRequest | Array | 否 | request 合法域名, 以 https:// 开头, 可填写 300 个域名 |
domainWhiteListSocket | Array | 否 | socket 合法域名, 以 wss:// 开头, 可填写 200 个域名 |
domainWhiteListUDP | Array | 否 | udp 合法域名, 以 udp:// 开头, 可填写 200 个域名。注:经 DNS 解析得到的 ip 也能通过白名单 |
domainWhiteListTCP | Array | 否 | tcp 合法域名, 以 tcp:// 开头, 可填写 200 个域名。注:经 DNS 解析得到的 ip 也能通过白名单 |
domainWhiteListUploadFile | Array | 否 | uploadFile 合法域名, 以 https:// 开头, 可填写 200 个域名 |
domainWhiteListDownloadFile | Array | 否 | downloadFile 合法域名, 以 https:// 开头, 可填写 200 个域名 |
enableReportMemory | Boolean | 否 | 统计 memory 信息, 默认值为 false |
enableReportCpu | Boolean | 否 | 统计 cpu 信息, 默认值为 false |
enableReportFps | Boolean | 否 | 统计 帧率相关 信息,包含 fps、jank 和 bigJank,默认值为 false |
splashGameTitle | String | 否 | 替换 Splash 页面游戏标题 |
splashIconUrl | String | 否 | 替换 Splash 页面游戏图标 |
showMenuExploreBtn | Boolean | 否 | 开启右上角菜单按钮 默认值为 true |
showMenuLayout | Boolean | 否 | 开启右上角布局 默认值为 true |
enableTransparentMode | Boolean | 否 | 开启游戏透明背景 默认值为 false |
enableMuteAllAudio | Boolean | 否 | 开启音频静音 默认值为 false |
accessToken | String | 否 | 访问令牌,用于游戏内认证 |
返回值
返回 Promise<void>
代码示例
const { TJConstants } = require('webglhost-runtime-pc');
async function setupGame(gameHandle) {
const options = {
[TJConstants.LAUNCH_KEY]: 'your-launch-key',
[TJConstants.USER_ID]: 'guest-user',
[TJConstants.ENABLE_VCONSOLE]: true,
[TJConstants.ENABLE_INSPECTOR]: false,
[TJConstants.SHOW_MENU_LAYOUT]: true,
[TJConstants.CUSTOM_SCRIPT_FILES]: [
'/path/to/custom-script1.js',
'/path/to/custom-script2.js'
],
[TJConstants.DOMAIN_WHITELIST_REQUEST]: [
'https://api.example.com',
'https://cdn.example.com'
]
};
try {
await gameHandle.setGameStartOptions(options);
console.log('Game start options set successfully');
} catch (error) {
console.error('Failed to set game start options:', error);
throw error;
}
}
游戏启动参数 LAUNCH_KEY 说明
目前,游戏支持三种启动方式:游戏列表启动、二维码扫码启动和最近游玩列表启动。
- 游戏列表启动:在游戏列表接口返回的对象中包含有
launchKey字段,该字段需要在启动游戏时作为启动参数传入给LAUNCH_KEY。- launchKey:
67da9d2961b25a25faf0b143
- launchKey:
- 二维码扫码启动:扫描二维码的结果作为启动参数传入给
LAUNCH_KEY。- 二维码扫码结果:
https://minihost.tuanjie.cn/api/game_app/67da9d2961b25a25faf0b143/temp_session/a0f06587-3def-4a3a-95b2-89286bc325fa/start
- 二维码扫码结果:
- 最近游玩列表启动:最近游玩对象中同样包含有
launchKey字段,该字段也是作为启动参数传入给LAUNCH_KEY。具体参考最近游玩列表功能。- 游戏列表启动时 launchKey:
67da9d2961b25a25faf0b143 - 扫码体验启动时 launchKey:
67da9d2961b25a25faf0b143:67dcc8227ae013b09d23ad23
- 游戏列表启动时 launchKey:
2. 开始游戏
加载、编译游戏资源,游戏界面可见但不可交互,宿主状态转为 RUNNING。
接口原型
gameHandle.start()
返回值
返回 Promise<void>
代码示例
async function startGame(gameHandle) {
try {
await gameHandle.start();
console.log('Game started successfully');
} catch (error) {
console.error('Failed to start game:', error);
throw error;
}
}
3. 运行/恢复游戏
游戏可交互或在应用切换至前台时恢复运行,宿主状态转为 PLAYING。
接口原型
gameHandle.play()
代码示例
// Resume game when window gains focus
gameHandle.play();
console.log('Game resumed');
4. 暂停游戏
暂停游戏,宿主状态转为 PAUSED。
接口原型
gameHandle.pause()
代码示例
// Pause game when window loses focus
gameHandle.pause();
console.log('Game paused');
5. 停止游戏
停止游戏,宿主状态转为 STOPPED。
接口原型
gameHandle.stop()
返回值
返回 Promise<void>
代码示例
async function stopGame(gameHandle) {
try {
await gameHandle.stop();
console.log('Game stopped');
} catch (error) {
console.error('Failed to stop game:', error);
}
}
6. 重启游戏
重启游戏,保留所有启动参数。
接口原型
gameHandle.restart()
返回值
返回 Promise<void>
代码示例
async function restartGame(gameHandle) {
try {
await gameHandle.restart();
console.log('Game restarted');
} catch (error) {
console.error('Failed to restart game:', error);
}
}
7. 设置宿主首帧渲染监听
提供宿主首帧渲染后的回调
接口原型
gameHandle.setOnFirstFrameRenderedListener(callback)
参数说明
| 参数 | 数据类型 | 必填 | 属性说明 |
|---|---|---|---|
callback | Function | 是 | 首帧回调函数 |
代码示例
gameHandle.setOnFirstFrameRenderedListener(() => {
console.log('First frame rendered');
// Hide loading UI, show game UI, etc.
});
8. 设置宿主游戏包下载回调
提供宿主游戏包下载的回调机制,此回调仅会在游戏包首次被下载时触发,若仅是读取缓存中的游戏包,则不会触发该回调。
接口原型
gameHandle.setOnGamePackageDownloadListener(callbacks)
参数说明
| 参数 | 数据类型 | 必填 | 属性说明 |
|---|---|---|---|
callbacks.onStart | Function | 是 | 游戏包开始下载回调 () => {} |
callbacks.onProgress | Function | 是 | 游戏包下载进度回调 (progress, totalBytesWritten, totalBytesExpected) |
callbacks.onSuccess | Function | 是 | 游戏包下载成功回调 () => {} |
callbacks.onFailure | Function | 是 | 游戏包下载失败回调 (error) => {} |
onProgress 参数说明
- progress: 下载进度 (0-1)
- totalBytesWritten: 已下载大小(字节)
- totalBytesExpected: 文件总大小(字节)
代码示例
gameHandle.setOnGamePackageDownloadListener({
onStart: () => {
console.log('Game package download started');
},
onProgress: (progress, totalBytesWritten, totalBytesExpected) => {
const percent = (progress * 100).toFixed(2);
const downloadedMB = (totalBytesWritten / 1024 / 1024).toFixed(2);
const totalMB = (totalBytesExpected / 1024 / 1024).toFixed(2);
console.log(`Download progress: ${percent}% (${downloadedMB}MB / ${totalMB}MB)`);
},
onSuccess: () => {
console.log('Game package download completed');
},
onFailure: (error) => {
console.error('Game package download failed:', error);
}
});
9. 设置游戏失败监听
提供游戏运行失败的回调
接口原型
gameHandle.setOnHostFailureListener(callback)
参数说明
| 参数 | 数据类型 | 必填 | 属性说明 |
|---|---|---|---|
callback | Function | 是 | 失败回调 (error) => {} |
代码示例
gameHandle.setOnHostFailureListener((error) => {
console.error('Game host failure:', error);
// Handle error, show error UI, restart game, etc.
});
10. 音频控制
静音所有音频
接口原型
gameHandle.muteAllAudio()
代码示例
// Mute all game audio
gameHandle.muteAllAudio();
console.log('All audio muted');
取消静音
接口原型
gameHandle.unmuteAllAudio()
代码示例
// Unmute all game audio
gameHandle.unmuteAllAudio();
console.log('All audio unmuted');
切换静音状态
接口原型
gameHandle.toggleAudioMute()
代码示例
// Toggle audio mute state
gameHandle.toggleAudioMute();
console.log('Audio mute toggled');
检查静音状态
接口原型
gameHandle.isMuted()
返回值
返回 Boolean - 是否静音
代码示例
// Check if audio is muted
if (gameHandle.isMuted()) {
console.log('Audio is currently muted');
} else {
console.log('Audio is currently playing');
}
音频控制完整示例
class AudioController {
constructor(gameHandle) {
this.gameHandle = gameHandle;
}
mute() {
this.gameHandle.muteAllAudio();
console.log('Muted');
}
unmute() {
this.gameHandle.unmuteAllAudio();
console.log('Unmuted');
}
toggle() {
this.gameHandle.toggleAudioMute();
console.log(`Audio is now ${this.gameHandle.isMuted() ? 'muted' : 'unmuted'}`);
}
getStatus() {
return this.gameHandle.isMuted() ? 'Muted' : 'Playing';
}
}
// Usage
const audioController = new AudioController(gameHandle);
// Mute audio
audioController.mute();
// Unmute audio
audioController.unmute();
// Toggle mute
audioController.toggle();
// Check status
console.log('Audio status:', audioController.getStatus());
完整游戏生命周期示例
const { TJHostHandle, TJConstants } = require('webglhost-runtime-pc');
class GameController {
constructor() {
this.hostHandle = null;
this.gameHandle = null;
}
async initialize(sdkKey, sdkSecret) {
// Initialize SDK
await new Promise((resolve, reject) => {
TJHostHandle.initialize(sdkKey, sdkSecret, (hostHandle, error) => {
if (error) {
reject(error);
return;
}
this.hostHandle = hostHandle;
resolve();
});
});
// Create game handle
this.gameHandle = await this.hostHandle.createGameHandle();
// Setup listeners
this.setupListeners();
}
setupListeners() {
// First frame rendered
this.gameHandle.setOnFirstFrameRenderedListener(() => {
console.log('Game first frame rendered');
});
// Download progress
this.gameHandle.setOnGamePackageDownloadListener({
onStart: () => console.log('Download started'),
onProgress: (progress) => console.log(`Progress: ${(progress * 100).toFixed(2)}%`),
onSuccess: () => console.log('Download completed'),
onFailure: (error) => console.error('Download failed:', error)
});
// Game failure
this.gameHandle.setOnHostFailureListener((error) => {
console.error('Game failure:', error);
});
}
async launchGame(launchKey, userId) {
// Set start options
await this.gameHandle.setGameStartOptions({
[TJConstants.LAUNCH_KEY]: launchKey,
[TJConstants.USER_ID]: userId,
[TJConstants.ENABLE_VCONSOLE]: true,
[TJConstants.SHOW_MENU_LAYOUT]: true
});
// Start game
await this.gameHandle.start();
// Play game
this.gameHandle.play();
console.log('Game launched successfully');
}
pauseGame() {
this.gameHandle.pause();
}
resumeGame() {
this.gameHandle.play();
}
async stopGame() {
await this.gameHandle.stop();
}
async restartGame() {
await this.gameHandle.restart();
}
async cleanup() {
if (this.gameHandle) {
await this.gameHandle.destroy();
}
}
}
// Usage
const controller = new GameController();
async function main() {
try {
await controller.initialize('sdk-key', 'sdk-secret');
await controller.launchGame('launch-key', 'user-id');
// Game is now running...
} catch (error) {
console.error('Error:', error);
}
}
main();