使用 Colyseus 创建实时对战游戏:一个简单案例
以下是使用 Colyseus 创建一个实时对战游戏的完整案例,涵盖服务器端和客户端的开发。我们将开发一个简单的“对战小游戏”,其中两个玩家可以实时移动自己的角色并在屏幕上看到彼此的动作。
1. 项目设置
安装 Colyseus 服务器
在 Node.js 环境中,创建一个新的项目并安装 Colyseus 相关依赖:
mkdir colyseus-game
cd colyseus-game
npm init -y
npm install colyseus @colyseus/schema express
设置项目结构
以下是推荐的项目结构:
colyseus-game/
├── server/
│ ├── GameRoom.js
│ └── index.js
├── client/
│ └── main.js
├── package.json
└── README.md
2. 服务器端开发
配置 GameRoom
在 server/GameRoom.js 中定义一个 Colyseus 房间,负责管理玩家的实时数据。
const { Room } = require("colyseus");
const { Schema, type } = require("@colyseus/schema");
// 定义游戏状态
class GameState extends Schema {
@type({ map: "string" }) players = {}; // 记录每个玩家的位置和状态
}
class GameRoom extends Room {
onCreate(options) {
this.setState(new GameState());
// 处理玩家加入
this.onMessage("move", (client, data) => {
const player = this.state.players[client.sessionId];
if (player) {
player.x = data.x;
player.y = data.y;
}
});
}
onJoin(client) {
this.state.players[client.sessionId] = { x: 0, y: 0 }; // 初始化玩家位置
console.log(`${client.sessionId} joined`);
}
onLeave(client) {
delete this.state.players[client.sessionId];
console.log(`${client.sessionId} left`);
}
}
module.exports = { GameRoom };
配置服务器入口
在 server/index.js 中设置 Express 和 Colyseus 服务器:
const express = require("express");
const { Server } = require("colyseus");
const { createServer } = require("http");
const { GameRoom } = require("./GameRoom");
const app = express();
const port = 3000;
const server = createServer(app);
const gameServer = new Server({ server });
gameServer.define("game_room", GameRoom); // 注册房间
app.use(express.static("client")); // 提供客户端静态资源
server.listen(port, () => {
console.log(`Server is running on http://localhost:${port}`);
});
3. 客户端开发
安装依赖
客户端需要安装 Colyseus 客户端库:
npm install colyseus.js
实现客户端逻辑
在 client/main.js 中实现客户端逻辑:
import * as Colyseus from "colyseus.js";
const client = new Colyseus.Client("ws://localhost:3000");
const canvas = document.createElement("canvas");
document.body.appendChild(canvas);
const ctx = canvas.getContext("2d");
canvas.width = 800;
canvas.height = 600;
let myId = null;
let state = {};
async function startGame() {
const room = await client.joinOrCreate("game_room");
myId = room.sessionId;
room.onStateChange((newState) => {
state = newState.players;
draw();
});
room.onMessage("chat", (message) => {
console.log(message);
});
// 捕捉键盘输入
document.addEventListener("keydown", (event) => {
if (event.key === "ArrowUp") move(0, -10);
if (event.key === "ArrowDown") move(0, 10);
if (event.key === "ArrowLeft") move(-10, 0);
if (event.key === "ArrowRight") move(10, 0);
});
function move(dx, dy) {
if (myId && state[myId]) {
room.send("move", { x: state[myId].x + dx, y: state[myId].y + dy });
}
}
}
function draw() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
for (const id in state) {
const player = state[id];
ctx.fillStyle = id === myId ? "blue" : "red";
ctx.fillRect(player.x, player.y, 20, 20);
}
}
startGame();
4. 启动项目
启动服务器
在项目根目录下运行:
node server/index.js
启动客户端
打开 http://localhost:3000 查看游戏。
5. 功能扩展
添加更多玩家信息
- 增加玩家名称或角色类型。
- 同步更多状态,例如生命值、得分。
增加游戏机制
- 实现碰撞检测。
- 添加实时计分系统。
部署到线上
- 使用 Docker 容器化。
- 部署到云服务(如 AWS、DigitalOcean、Vercel)。
以上步骤完成后,您将拥有一个完整的基于 Colyseus 的实时对战游戏框架!
1035

被折叠的 条评论
为什么被折叠?



