Mini Game Quick Start
Through this guide, you will learn how to use cloud development in mini-games, including core features such as cloud database, cloud storage, and cloud functions, to quickly build mini-games with backend capabilities.
🎮 WeChat Mini Game
📋 Preparations
Before you begin, ensure you have completed the following preparations:
- Development Tools: Download and install WeChat Developer Tools
- Mini Game Account: Register a WeChat Mini Game, obtain the mini-game's AppID
- Base Library Version: Ensure the mini-game base library version is ≥ 2.2.3
- Game Engine: Supports mainstream game engines such as Cocos Creator, Laya, and Egret
🚀 Step 1: Create Mini Game Project
Open WeChat Developer Tools and log in by scanning the QR code with WeChat
Create New Mini Game Project: Fill in your mini-game AppID
- Select the project storage directory
☁️ Step 2: Activate Cloud Development Environment
Follow the steps to Activate Cloud Development Environment
💻 Step 3: Initialize CloudBase
Initialize cloud development in game.js
:
// game.js
// Initialize CloudBase
if (!wx.cloud) {
console.error('Please use base library version 2.2.3 or above to use cloud capabilities');
} else {
wx.cloud.init({
env: 'your-env-id', // Replace with your environment ID
traceUser: true,
});
}
// Main Game Logic
class Game {
constructor() {
this.init();
}
init() {
// Game Initialization Logic
console.log('Game initialization completed');
this.loadGameData();
}
// Load game data
async loadGameData() {
try {
const db = wx.cloud.database();
const result = await db.collection('gameData').get();
console.log('Game data loaded successfully', result.data);
} catch (error) {
console.error('Game data loading failed', error);
}
}
}
// Launch the game
new Game();
🎯 Step 4: Integrate the game engine
Cocos Creator Integration
Install the CloudBase plugin:
- Open "Extensions" > "Extension Store" in Cocos Creator
- Search for and install the "WeChat Mini Game Cloud Development" plugin
Configure CloudBase:
// In Cocos Creator scripts
cc.Class({
extends: cc.Component,
onLoad() {
// Initialize CloudBase
if (typeof wx !== 'undefined' && wx.cloud) {
wx.cloud.init({
env: 'your-env-id'
});
}
},
// Save game score
async saveScore(score) {
try {
const db = wx.cloud.database();
await db.collection('scores').add({
data: {
score: score,
timestamp: new Date(),
openid: '{openid}' // Automatically filled
}
});
console.log('Score saved successfully');
} catch (error) {
console.error('Score save failed', error);
}
}
});
🎮 Step 5: Implement core game functionality
User System
// User login and data management
class UserManager {
constructor() {
this.userInfo = null;
this.db = wx.cloud.database();
}
// User login
async login() {
try {
// Get user information
const loginResult = await wx.cloud.callFunction({
name: 'login'
});
this.userInfo = loginResult.result;
await this.initUserData();
} catch (error) {
console.error('Login failed', error);
}
}
// Initialize user data
async initUserData() {
try {
const userCollection = this.db.collection('users');
const userDoc = await userCollection.doc(this.userInfo.openid).get();
if (userDoc.data.length === 0) {
// New user, creating initial data
await userCollection.add({
data: {
_id: this.userInfo.openid,
nickname: 'New Player',
level: 1,
score: 0,
coins: 100,
createTime: new Date()
}
});
}
} catch (error) {
console.error('User data initialization failed', error);
}
}
}
Leaderboard System
// Leaderboard Management
class LeaderboardManager {
constructor() {
this.db = wx.cloud.database();
}
// Submit score
async submitScore(score) {
try {
await this.db.collection('leaderboard').add({
data: {
score: score,
timestamp: new Date(),
openid: '{openid}' // Automatically filled
}
});
console.log('Score submitted successfully');
} catch (error) {
console.error('Score submission failed', error);
}
}
// Get leaderboard
async getLeaderboard(limit = 10) {
try {
const result = await this.db.collection('leaderboard')
.orderBy('score', 'desc')
.limit(limit)
.get();
return result.data;
} catch (error) {
console.error('Leaderboard retrieval failed', error);
return [];
}
}
}
🎯 Step 6: Experience CloudBase features
After creating the project, you can experience the following features:
- Cloud database: Stores game data, user information, leaderboards, etc.
- Cloud Storage: Upload game screenshots, audio resources, etc.
- Cloud Function: Implements game logic, data processing, and third-party API calls
📚 Deep Dive
- Cloud Database Operations
- Cloud Storage Management
- Cloud Function Development
- WeChat MiniGame Official Documentation
🎮 QQ Mini Game
📋 Preparations
- Development Tools: Download and install QQ MiniGame Developer Tools
- QQ Mini Game Account: Register a QQ Mini Game developer account
- Tencent Cloud account: Must be bound to a Tencent Cloud account.
🚀 Quick Start
Create Project:
- Open QQ MiniGame Developer Tools
- Create a new Mini Game project
- Select Cloud Development Template
Enable CloudBase:
- Access the CloudBase Console via QQ MiniGame IDE
- Follow the prompts to enable the CloudBase environment
Account Binding:
- The system will automatically guide you to complete the binding between your QQ MiniGame account and Tencent Cloud account.
- After binding, you can utilize the full capabilities of CloudBase.
📚 Learning Resources
To facilitate developers using CloudBase in QQ MiniGame, the system automatically establishes the following binding relationships:
- Create the identity provider "TcbSamlProvider_qq" in Identity Provider
- Create the role "TcbSamlRole_qq" in Role
Important: The above information is essential for using CloudBase in QQ MiniGame. Please do not delete it.
🎮 Complete Game Example: Cloud Airplane Battle
Let's demonstrate how to use various features of cloud development in mini-games through a complete airplane battle game example.
The current case is developed based on the WeChat Mini Game template.
Game Features
- Real-time Leaderboard: Uses cloud database to store and display player scores
Core Code Implementation
1. Leaderboard Main Logic (only shows the data interaction logic here)
// js/runtime/leaderboard.js
import Emitter from '../libs/tinyemitter';
import {
SCREEN_WIDTH,
SCREEN_HEIGHT
} from '../render';
import leaderboardService from '../../services/leaderboard';
/**
* Leaderboard UI Component
* Handles the display and interaction of the leaderboard
*/
export default class Leaderboard extends Emitter {
constructor() {
super();
this.leaderboardData = []; // Leaderboard data
this.loading = false; // Whether loading is in progress
this.playerRank = 0; // Player's current rank
}
/**
* Load leaderboard data
*/
async loadLeaderboard() {
try {
const result = await leaderboardService.getLeaderboard(10);
if (result.success) {
this.leaderboardData = result.data;
} else {
console.error('Leaderboard loading failed:', result.error);
this.leaderboardData = [];
}
} catch (error) {
console.error('Leaderboard loading exception:', error);
this.leaderboardData = [];
}
}
/**
* Load player ranking
*/
async loadPlayerRank(score) {
try {
const result = await leaderboardService.getPlayerRank(score);
if (result.success) {
this.playerRank = result.rank;
}
} catch (error) {
console.error('Ranking retrieval failed:', error);
this.playerRank = 0;
}
}
/**
* Render leaderboard
*/
render(ctx) {
if (!this.visible) return;
// Render UI
this.renderBackground(ctx);
this.renderRankings(ctx);
this.renderPlayerRank(ctx);
// Other rendering logic...
}
}
2. Leaderboard Service Layer
// services/leaderboard.js - Leaderboard data management
class LeaderboardService {
constructor() {
this.db = wx.cloud.database();
this.collection = this.db.collection('leaderboard');
}
/**
* Submit player score
* @param {Object} scoreData - Score data
* @param {string} scoreData.nickname - Player nickname
* @param {number} scoreData.score - Player score
* @param {string} scoreData.avatar - Player avatar URL (optional)
* @returns {Promise} Submission Result
*/
async submitScore(scoreData) {
try {
const {
nickname,
score,
avatar = ''
} = scoreData;
// Validate data
if (!nickname || typeof score !== 'number') {
throw new Error('Nickname and score cannot be empty');
}
// Preparing data for insertion
const data = {
nickname,
score,
avatar,
timestamp: new Date().toISOString(),
createTime: new Date(),
};
const result = await this.collection.add({
data,
});
return {
success: true,
data: result,
message: 'Score submitted successfully',
};
} catch (error) {
console.error('Score submission failed:', error);
return {
success: false,
error: error.message,
};
}
}
/**
* Retrieve leaderboard data
* @param {number} limit - The number of records to retrieve, default: 10 records
* @returns {Promise} Leaderboard data
*/
async getLeaderboard(limit = 10) {
try {
const result = await this.collection
.orderBy('score', 'desc') // Sort by score in descending order
.limit(limit)
.get();
return {
success: true,
data: result.data,
total: result.data.length,
};
} catch (error) {
console.error('Leaderboard retrieval failed:', error);
return {
success: false,
error: error.message,
data: [],
};
}
}
/**
* Retrieve player ranking
* @param {number} score - Player score
* @returns {Promise} Ranking information
*/
async getPlayerRank(score) {
try {
// Retrieve the number of records with scores higher than the current score
const result = await this.collection
.where({
score: this.db.command.gt(score),
})
.count();
const rank = result.total + 1; // Ranking starts from 1
return {
success: true,
rank,
message: `Current rank: ${rank}`,
};
} catch (error) {
console.error('Ranking retrieval failed:', error);
return {
success: false,
error: error.message,
rank: 0,
};
}
}
}
Deployment and Testing
Create a database collection:
leaderboard
: Stores leaderboard informationusers
: Store user information
Set database permissions:
{
"read": "auth != null",
"write": "auth != null && doc._openid == auth.openid"
}
🔗 Related Resources
Example Project
Development Tools
Learning Documentation
🎉 Start your Minigame CloudBase journey! Choose the platform and game engine that suit you to quickly build powerful cloud-based minigames.