跳到主要内容

小游戏快速开始

通过本指南,您将学会如何在小游戏中使用云开发,包括数据库、云存储和云函数等核心功能,快速构建具备后端能力的小游戏。

准备工作

在开始之前,请确保您已完成以下准备:

  1. 开通云开发环境开通云开发环境
  2. 开发工具:下载并安装 微信开发者工具
  3. 小游戏账号注册微信小游戏,获取小游戏的 AppID
  4. 游戏引擎:支持 Cocos Creator、Laya、白鹭等主流游戏引擎

第 1 步:创建小游戏项目

  1. 打开微信开发者工具,使用微信扫码登录

  2. 新建小游戏项目:

    • 填入您的小游戏 AppID
    • 选择项目存放目录
    • 后端服务选择「微信云开发」
    • 勾选同意「云开发服务条款」

⚠️ 注意:后端服务必须选择「微信云开发」才能使用云开发功能

第 2 步:初始化云开发

game.js 中初始化云开发:

// game.js
// 初始化云开发
if (!wx.cloud) {
console.error('请使用 2.2.3 或以上的基础库以使用云能力');
} else {
wx.cloud.init({
env: 'your-env-id', // 替换为您的环境 ID
traceUser: true,
});
}

// 游戏主逻辑
class Game {
constructor() {
this.init();
}

init() {
// 游戏初始化逻辑
console.log('游戏初始化完成');
this.loadGameData();
}

// 加载游戏数据
async loadGameData() {
try {
const db = wx.cloud.database();
const result = await db.collection('gameData').get();
console.log('游戏数据加载成功', result.data);
} catch (error) {
console.error('游戏数据加载失败', error);
}
}
}

// 启动游戏
new Game();

第 3 步:集成游戏引擎

Cocos Creator 集成

  1. 安装云开发插件:

    • 在 Cocos Creator 中打开「扩展」>「扩展商店」
    • 搜索并安装「微信小游戏云开发」插件
  2. 配置云开发:

// 在 Cocos Creator 脚本中
cc.Class({
extends: cc.Component,

onLoad() {
// 初始化云开发
if (typeof wx !== 'undefined' && wx.cloud) {
wx.cloud.init({
env: 'your-env-id'
});
}
},

// 保存游戏分数
async saveScore(score) {
try {
const db = wx.cloud.database();
await db.collection('scores').add({
data: {
score: score,
timestamp: new Date(),
openid: '{openid}' // 自动填充
}
});
console.log('分数保存成功');
} catch (error) {
console.error('分数保存失败', error);
}
}
});

第 4 步:实现核心游戏功能

用户系统

// 用户登录和数据管理
class UserManager {
constructor() {
this.userInfo = null;
this.db = wx.cloud.database();
}

// 用户登录
async login() {
try {
// 获取用户信息
const loginResult = await wx.cloud.callFunction({
name: 'login'
});

this.userInfo = loginResult.result;
await this.initUserData();

} catch (error) {
console.error('登录失败', error);
}
}

// 初始化用户数据
async initUserData() {
try {
const userCollection = this.db.collection('users');
const userDoc = await userCollection.doc(this.userInfo.openid).get();

if (userDoc.data.length === 0) {
// 新用户,创建初始数据
await userCollection.add({
data: {
_id: this.userInfo.openid,
nickname: '新玩家',
level: 1,
score: 0,
coins: 100,
createTime: new Date()
}
});
}
} catch (error) {
console.error('用户数据初始化失败', error);
}
}
}

排行榜系统

// 排行榜管理
class LeaderboardManager {
constructor() {
this.db = wx.cloud.database();
}

// 提交分数
async submitScore(score) {
try {
await this.db.collection('leaderboard').add({
data: {
score: score,
timestamp: new Date(),
openid: '{openid}' // 自动填充
}
});

console.log('分数提交成功');
} catch (error) {
console.error('分数提交失败', error);
}
}

// 获取排行榜
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('获取排行榜失败', error);
return [];
}
}
}

第 5 步:体验云开发功能

创建完项目后,您可以体验以下功能:

  • 数据库:存储游戏数据、用户信息、排行榜等
  • 云存储:上传游戏截图、音频资源等
  • 云函数:实现游戏逻辑、数据处理、第三方 API 调用

深入学习

相关资源