部署一个微信小程序4 | 测试剪刀石头布的小游戏

内容摘抄来源:腾讯云开发者实验室视频教程

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
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,589评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,615评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,933评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,976评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,999评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,775评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,474评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,359评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,854评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,007评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,146评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,826评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,484评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,029评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,153评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,420评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,107评论 2 356

推荐阅读更多精彩内容