内容摘抄来源:腾讯云开发者实验室视频教程
Step1 实现游戏房间逻辑
创建 /data/release/webapp/game 目录用于存放剪刀石头布小游戏的代码
sudo mkdir -p /data/release/webapp/game
添加 game/Room.js 实现游戏房间逻辑
cd /data/release/webapp/game
sudo touch Room.js
sudo chmod a+rw Room.js
修改 game/Room.js,处理游戏开始、计算结果、积分等逻辑
/**
enum GameChoice {
// 剪刀
Scissors = 1,
// 石头
Rock = 2,
// 布
Paper = 3
}
*/
function judge(choice1, choice2) {
// 和局
if (choice1 == choice2) return 0;
// Player 1 没出,Player 2 胜出
if (!choice1) return 1;
// Player 2 没出,Player 1 胜出
if (!choice2) return -1;
// 都出了就这么算
return (choice1 - choice2 + 3) % 3 == 1 ? -1 : 1;
}
/** @type {Room[]} */
const globalRoomList = [];
// 每个房间最多两人
const MAX_ROOT_MEMBER = 2;
// 游戏时间,单位秒
const GAME_TIME = 3;
let nextRoomId = 0;
/** 表示一个房间 */
module.exports = class Room {
/** 获取所有房间 */
static all() {
return globalRoomList.slice();
}
/** 获取有座位的房间 */
static findRoomWithSeat() {
return globalRoomList.find(x => !x.isFull());
}
/** 创建新房间 */
static create() {
const room = new Room();
globalRoomList.unshift(room);
return room;
}
constructor() {
this.id = `room${nextRoomId++}`;
this.players = [];
}
/** 添加玩家 */
addPlayer(player) {
const { uid, uname } = player.user;
console.log(`Player ${uid}(${uname}) enter ${this.id}`);
this.players.push(player);
if (this.isFull()) {
this.startGame();
}
}
/** 删除玩家 */
removePlayer(player) {
const { uid, uname } = player.user;
console.log(`Player ${uid}(${uname}) leave ${this.id}`);
const playerIndex = this.players.indexOf(player);
if (playerIndex != -1) {
this.players.splice(playerIndex, 1);
}
if (this.players.length === 0) {
console.log(`Room ${this.id} is empty now`);
const roomIndex = globalRoomList.indexOf(this);
if (roomIndex > -1) {
globalRoomList.splice(roomIndex, 1);
}
}
}
/** 玩家已满 */
isFull() {
return this.players.length == MAX_ROOT_MEMBER;
}
/** 开始游戏 */
startGame() {
// 保留这行日志输出可以让实验室检查到实验的完成情况
console.log('game started!');
// 当局积分清零
this.players.forEach(player => player.gameData.roundScore = 0);
// 集合玩家用户和游戏数据
const players = this.players.map(player => Object.assign({}, player.user, player.gameData));
// 通知所有玩家开始
for (let player of this.players) {
player.send('start', {
gameTime: GAME_TIME,
players
});
}
// 计时结束
setTimeout(() => this.finishGame(), GAME_TIME * 1000);
}
/** 结束游戏 */
finishGame() {
const players = this.players;
// 两两对比算分
for (let i = 0; i < MAX_ROOT_MEMBER; i++) {
let p1 = players[i];
if (!p1) break;
for (let j = i + 1; j < MAX_ROOT_MEMBER; j++) {
let p2 = players[j];
const result = judge(p1.gameData.choice, p2.gameData.choice);
p1.gameData.roundScore -= result;
p2.gameData.roundScore += result;
}
}
// 计算连胜奖励
for (let player of players) {
const gameData = player.gameData;
// 胜局积分
if (gameData.roundScore > 0) {
gameData.winStreak++;
gameData.roundScore *= gameData.winStreak;
}
// 败局清零
else if (gameData.roundScore < 0) {
gameData.roundScore = 0;
gameData.winStreak = 0;
}
// 累积总分
gameData.totalScore += gameData.roundScore;
}
// 计算结果
const result = players.map(player => {
const { uid } = player.user;
const { roundScore, totalScore, winStreak, choice } = player.gameData;
return { uid, roundScore, totalScore, winStreak, choice };
});
// 通知所有玩家游戏结果
for (let player of players) {
player.send('result', { result });
}
}
}
Step2 实现玩家逻辑
添加 game/Player.js
cd /data/release/webapp/game
sudo touch Player.js
sudo chmod a+rw Player.js
修改 game/Player.js,处理玩家加入游戏、选择出拳、通知其他玩家等逻辑
const Room = require("./Room");
/**
* 表示一个玩家,处理玩家的公共游戏逻辑,消息处理部分需要具体的玩家实现(请参考 ComputerPlayer 和 HumanPlayer)
*/
module.exports = class Player {
constructor(user) {
this.id = user.uid;
this.user = user;
this.room = null;
this.gameData = {
// 当前的选择(剪刀/石头/布)
choice: null,
// 局积分
roundScore: 0,
// 总积分
totalScore: 0,
// 连胜次数
winStreak: 0
};
}
/**
* 上线当前玩家,并且异步返回给玩家分配的房间
*/
online(room) {
// 处理玩家 'join' 消息
// 为玩家寻找一个可用的房间,并且异步返回
this.receive('join', () => {
if (this.room) {
this.room.removePlayer(this);
}
room = this.room = room || Room.findRoomWithSeat() || Room.create();
room.addPlayer(this);
});
// 处理玩家 'choise' 消息
// 需要记录玩家当前的选择,并且通知到房间里的其它玩家
this.receive('choice', ({ choice }) => {
this.gameData.choice = choice;
this.broadcast('movement', {
uid: this.user.uid,
movement: "choice"
});
});
// 处理玩家 'leave' 消息
// 让玩家下线
this.receive('leave', () => this.offline);
}
/**
* 下线当前玩家,从房间离开
*/
offline() {
if (this.room) {
this.room.removePlayer(this);
this.room = null;
}
this.user = null;
this.gameData = null;
}
/**
* 发送指定消息给当前玩家,需要具体子类实现
* @abstract
* @param {string} message 消息类型
* @param {*} data 消息数据
*/
send(message, data) {
throw new Error('Not implement: AbstractPlayer.send()');
}
/**
* 处理玩家发送的消息,需要具体子类实现
* @abstract
* @param {string} message 消息类型
* @param {Function} handler
*/
receive(message, handler) {
throw new Error('Not implement: AbstractPlayer.receive()');
}
/**
* 给玩家所在房间里的其它玩家发送消息
* @param {string} message 消息类型
* @param {any} data 消息数据
*/
broadcast(message, data) {
if (!this.room) return;
this.others().forEach(neighbor => neighbor.send(message, data));
}
/**
* 获得玩家所在房间里的其他玩家
*/
others() {
return this.room.players.filter(player => player != this);
}
}
2.1 实现电脑玩家ComputerPlayer.js
cd /data/release/webapp/game
sudo touch ComputerPlayer.js
sudo chmod a+rw ComputerPlayer.js
修改 ComputerPlayer.js ,测试游戏逻辑的时候,可能没有其它人可以一起参与,实现一个电脑玩家是不错的选择
const EventEmitter = require('events');
const Player = require('./Player');
let nextComputerId = 0;
/**
* 机器人玩家实现,使用 EventEmitter 接收和发送消息
*/
module.exports = class ComputerPlayer extends Player {
constructor() {
const computerId = `robot-${++nextComputerId}`;
super({
uid: computerId,
uname: computerId,
uavatar: 'http://www.scoutiegirl.com/wp-content/uploads/2015/06/Blue-Robot.png'
});
this.emitter = new EventEmitter();
}
/**
* 模拟玩家行为
*/
simulate() {
this.receive('start', () => this.play());
this.receive('result', () => this.stop());
this.send('join');
}
/**
* 游戏开始后,随机时间后随机选择
*/
play() {
this.playing = true;
const randomTime = () => Math.floor(100 + Math.random() * 2000);
const randomChoice = () => {
if (!this.playing) return;
this.send("choice", {
choice: Math.floor(Math.random() * 10000) % 3 + 1
});
setTimeout(randomChoice, randomTime());
}
setTimeout(randomChoice, 10);
}
/**
* 游戏结束后,标记起来,阻止继续随机选择
*/
stop() {
this.playing = false;
}
/**
* 发送消息给当前玩家,直接转发到 emitter
*/
send(message, data) {
this.emitter.emit(message, data);
}
/**
* 从当前的 emitter 处理消息
*/
receive(message, handle) {
this.emitter.on(message, handle);
}
}
2.2 实现人类玩家HumanPlayer.js
人类玩家通过 WebSocket 信道来实现玩家的输入输出,我们需要添加 game/Tunnel.js 和 game/HumanPlayer.js 来实现人类玩家逻辑
cd /data/release/webapp/game
sudo touch Tunnel.js
sudo touch HumanPlayer.js
sudo chmod a+rw Tunnel.js
sudo chmod a+rw HumanPlayer.js
修改 game/Tunnel.js 文件
const EventEmitter = require('events');
/**
* 封装 WebSocket 信道
*/
module.exports = class Tunnel {
constructor(ws) {
this.emitter = new EventEmitter();
this.ws = ws;
ws.on('message', packet => {
try {
// 约定每个数据包格式:{ message: 'type', data: any }
const { message, data } = JSON.parse(packet);
this.emitter.emit(message, data);
} catch (err) {
console.log('unknown packet: ' + packet);
}
});
}
on(message, handle) {
this.emitter.on(message, handle);
}
emit(message, data) {
this.ws.send(JSON.stringify({ message, data }));
}
}
修改 game/HumanPlayer.js 文件,人类玩家和电脑玩家的逻辑是一致的,但是 IO 不同,人类玩家使用之前实现的 WebSocket 服务进行输入输出,而电脑玩家直接使用 EventEmiter 处理
const co = require('co');
const Player = require('./Player');
const ComputerPlayer = require('./ComputerPlayer');
const Tunnel = require('./Tunnel');
/**
* 人类玩家实现,通过 WebSocket 信道接收和发送消息
*/
module.exports = class HumanPlayer extends Player {
constructor(user, ws) {
super(user);
this.ws = ws;
this.tunnel = new Tunnel(ws);
this.send('id', user);
}
/**
* 人类玩家上线后,还需要监听信道关闭,让玩家下线
*/
online(room) {
super.online(room);
this.ws.on('close', () => this.offline());
// 人类玩家请求电脑玩家
this.receive('requestComputer', () => {
const room = this.room;
while(room && !room.isFull()) {
const computer = new ComputerPlayer();
computer.online(room);
computer.simulate();
}
});
}
/**
* 下线后关闭信道
*/
offline() {
super.offline();
if (this.ws && this.ws.readyState == this.ws.OPEN) {
this.ws.close();
}
this.ws = null;
this.tunnel = null;
if (this.room) {
// 清理房间里面的电脑玩家
for (let player of this.room.players) {
if (player instanceof ComputerPlayer) {
this.room.removePlayer(player);
}
}
this.room = null;
}
}
/**
* 通过 WebSocket 信道发送消息给玩家
*/
send(message, data) {
this.tunnel.emit(message, data);
}
/**
* 从 WebSocket 信道接收玩家的消息
*/
receive(message, callback) {
this.tunnel.on(message, callback);
}
}
Step3 添加游戏服务入口
游戏的实现已经完成了,接下来,编辑 websocket.js 添加服务入口,可参考下面的代码:
// 引入 url 模块用于解析 URL
const url = require('url');
// 引入 ws 支持 WebSocket 的实现
const ws = require('ws');
// 引入人类玩家
const HumanPlayer = require('./game/HumanPlayer');
// 导出处理方法
exports.listen = listen;
/**
* 在 HTTP Server 上处理 WebSocket 请求
* @param {http.Server} server
* @param {wafer.SessionMiddleware} sessionMiddleware
*/
function listen(server, sessionMiddleware) {
// 使用 HTTP Server 创建 WebSocket 服务,使用 path 参数指定需要升级为 WebSocket 的路径
const wss = new ws.Server({ server });
// 同时支持 /ws 和 /game 的 WebSocket 连接请求
wss.shouldHandle = (request) => {
const path = url.parse(request.url).pathname;
request.path = path;
return ['/ws', '/game'].indexOf(path) > -1;
};
// 监听 WebSocket 连接建立
wss.on('connection', (ws, request) => {
// request: 要升级到 WebSocket 协议的 HTTP 连接
// 被升级到 WebSocket 的请求不会被 express 处理,
// 需要使用会话中间节获取会话
sessionMiddleware(request, null, () => {
const session = request.session;
if (!session) {
// 没有获取到会话,强制断开 WebSocket 连接
ws.send(JSON.stringify(request.sessionError) || "No session avaliable");
ws.close();
return;
}
console.log(`WebSocket client connected with openId=${session.userInfo.openId}`);
// 根据请求的地址进行不同处理
switch (request.path) {
case '/ws': return serveMessage(ws, session.userInfo);
case '/game': return serveGame(ws, session.userInfo);
default: return ws.close();
}
});
});
// 监听 WebSocket 服务的错误
wss.on('error', (err) => {
console.log(err);
});
}
/**
* 进行简单的 WebSocket 服务,对于客户端发来的所有消息都回复回去
*/
function serveMessage(ws, userInfo) {
// 监听客户端发来的消息
ws.on('message', (message) => {
console.log(`WebSocket received: ${message}`);
ws.send(`Server: Received(${message})`);
});
// 监听关闭事件
ws.on('close', (code, message) => {
console.log(`WebSocket client closed (code: ${code}, message: ${message || 'none'})`);
});
// 连接后马上发送 hello 消息给会话对应的用户
ws.send(`Server: 恭喜,${userInfo.nickName}`);
}
/**
* 使用 WebSocket 进行游戏服务
*/
function serveGame(ws, userInfo) {
const user = {
uid: userInfo.openId,
uname: userInfo.nickName,
uavatar: userInfo.avatarUrl
};
// 创建玩家
const player = new HumanPlayer(user, ws);
// 玩家上线
player.online();
}
Step4 安装 co 模块
源码中使用到了 co 进行协程管理,启动游戏服务前,需要先安装:
cd /data/release/webapp
sudo npm install co --save
Step5 测试游戏服务
重启 Node 服务:
pm2 restart app
打开配套的小程序,点击 实验四 - 剪刀石头布小游戏,点击 开始 按钮进行游戏。
image.png