微信答题PK类游戏尝试实现

前言

前阵子头脑王者类的微信答题PK游戏很火,自己也是很痴迷,玩了一阵子之后,想自己尝试来模仿下答题这一部分的实现。服务端打算在下swoole和socket.io之间选择,因为socket.io可以不借助redis直接缓存一些变量,所以选择了socket.io。简单实现了对战这一部分,实现的并不完善,只是一种思路

客户端实现

index.html





    
    
    
    答题

    
    
    



    

选手1

{{score[0]}}

{{remain_time}}

选手2

{{score[1]}}

{{question}}

  • {{item.index}}

{{msg}}

大概长这样,后端的审美,比较不好看
微信答题PK类游戏尝试实现_第1张图片

问题数据的存储方式

我用了redis来保存问题,内容格式如下

{
    "id": 9,
    "content": "9.一年几天",//问题内容
    "options": [  //选项
        "1",
        "2",
        "3",
        "365"
    ],
    "answer_index": 3 //答案的索引
}

选用redis的list格式,顺手自己编几个问题,用php写进去,多编几条,多写几次

$redis = new \Redis();
$redis->connect('127.0.0.1');
$content = ['id' => 1, 'content' => '1.一天有几小时', 'options' => ['1', '2', '3', '48'], 'answer_index' => 3];
$redis->lPush('questions', json_encode($content));

微信答题PK类游戏尝试实现_第2张图片

服务端实现

answerserver.js

const app = require('express')();
const server = require('http').Server(app);
const io = require('socket.io')(server);
const redisModule = require('redis');
const redis = redisModule.createClient(6379, '127.0.0.1');

let playerIndex = 0; //选手索引
let options = []; //选项
let answerIndex = 0; //答案索引
let timer = null; //定时器
let remainTime = 10; //剩余时间
let score = [0, 0]; //得分 ['选手1分数','选手2分数']
let questionCount = 0; //问题数
let startGame = false; //是否已经开始游戏
const maxRemainTime = 10; //最大倒计时秒数

server.listen(1024);

io.on('connection', (socket) => {
    //客户端发送 获取问题
    socket.on('getQuestion', (playerIndex) => {
        if (startGame == false) {
            //首次发送 倒计时开始
            timer = setInterval(() => {
                remainTime--;
                if (remainTime <= 0) {
                    socket.emit('getQuestion', remainTime);
                    remainTime = maxRemainTime;
                }
                socket.emit('updateTime', remainTime);
                socket.broadcast.emit('updateTime', remainTime);

            }, 1000);
            startGame = true;
        }
        //初始化倒计时
        remainTime = maxRemainTime;
        questionCount++;
        redis.lpop('questions', function (err, data) {
            let res = JSON.parse(data);
            let new_options = [];
            answerIndex = res.answer_index;
            res.options.forEach(function (v, k) {
                let o = new Object();
                o.index = v;
                o.class = '' //这里的class供前端使用,为空时,选项是白色背景
                new_options.push(o)
            })
            res.options = new_options;
            options = new_options;
            socket.emit('sendQueston', JSON.stringify(res))
            socket.broadcast.emit('sendQueston', JSON.stringify(res))
        })
    });

    //发送答案结果
    socket.on('sendAnswer', (userSelectIndex, playerIndex) => {
        let result = { msg: '' };
        options.forEach(function (v, k) {
            if (answerIndex == k) {
                //正确的选项 背景改成绿色
                options[k].class = 'correct'
            } else if (k == userSelectIndex && userSelectIndex != answerIndex) {
                //正确的选项 背景改成红色
                result.msg = '选手' + (playerIndex + 1) + '答错了';
                options[k].class = 'wrong'
            }
        })
        //答对的选手+10分
        if (userSelectIndex == answerIndex) {
            score[playerIndex] += 10;
            result.msg = '选手' + (playerIndex + 1) + '答对了';
        }
        result.score = score;
        result.options = options;

        socket.emit('sendResult', JSON.stringify(result));
        socket.emit('getQuestion');
        socket.broadcast.emit('getQuestion');
        socket.broadcast.emit('sendResult', JSON.stringify(result));
        if (questionCount >= 5) {
            let winText = '平局'; //结束时的提示信息
            if (score[0] > score[1]) {
                winText = '选手1获胜'
            } else if (score[0] < score[1]) {
                winText = '选手2获胜'
            }
            socket.emit('gameOver', winText);
            socket.broadcast.emit('gameOver', winText);
            clearInterval(timer);
        }
    });

    //获取选手号数
    socket.on('getPlayerIndex', (data) => {
        socket.emit('getPlayerIndex', playerIndex);
        playerIndex++;
        if (playerIndex >= 2) {
            playerIndex = 0;
        }
    });
});

最终效果

你可能感兴趣的:(socket.io,微信小程序,javascript)