Node 入门 - (五)使用http服务完成小游戏

416 阅读2分钟
  • 首页
<!--index.html-->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        button {
            display: inline-block;
        }
    </style>
</head>
<body>
    <div id="output" style="height: 400px;width:600px;background:#eee;"></div>
    <button id="rock" style="height: 40px; width:180px">石头</button>
    <button id="scissor" style="height: 40px; width:180px">剪刀</button>
    <button id="paper" style="height: 40px; width:180px"></button>

    <script>
        const $button = {
            rock: document.getElementById('rock'),
            scissor: document.getElementById('scissor'),
            paper: document.getElementById('paper'),
        }

        const $output = document.getElementById('output');

        Object.keys($button).forEach(key => {
            $button[key].addEventListener('click', function() {
                fetch(`http://${location.host}/game?action=${key}`)
                    .then((res) => {
                        return res.text()
                    })
                    .then((text) => {
                        $output.innerHTML += text + '<br />'
                    })
            })
        })
    </script>
</body>
</html>

当前页面三个button作为用户的操作,output作为结果输出,通过按钮点击请求本地接口传递对应行为

  • 游戏逻辑
module.exports = function(playerAction) {
    var random = Math.random() * 3;
    
    if(random < 1) {
        var computerAction = 'rock';
    } else if (random > 2) {
        var computerAction = 'scissor';
    } else {
        var computerAction = 'paper'
    }

    if (computerAction === playerAction) {
        return 0;
    } else if (
        (computerAction === 'rock' && playerAction === 'paper') ||
        (computerAction === 'scissor' && playerAction === 'rock') ||
        (computerAction === 'paper' && playerAction === 'scissor')
    ) {
        return -1;
    } else {
        return 1;
    }
}

电脑随机出拳返回结果

  • 服务端
const http = require('http'); //导入http
const fs = require('fs'); //文件操作
const url = require('url') //url解析
const queryString = require('queryString') //参数解析
const game = require('./game.js') //导入游戏逻辑

let playerWon = 0; //记录用户赢的次数

let playerLastAction = null; //统计用户上次一出拳
let sameCount = 0; //统计连续出拳次数

http.createServer(function(req, res) {
    const parseUrl = url.parse(req.url); //返回处理url结果
    //判断如果请求的是/favicon.icon则直接返回
    if (parseUrl === '/favicon.ico') {
        res.writeHead(200);
        res.end();
        return;
    }

    //判断当前请求为游戏操作
    if (parseUrl.pathname === '/game') {
        const query = queryString.parse(parseUrl.query); //解析参数
        const playerAction = query.action; //获取对应参数

        //当用户赢了三次退出
        if (playerWon >= 3 || sameCount == 9) {
            res.writeHead(500);
            res.end('我再也不和你玩了!');
            return;
        }

        //当用户连续出同样券三次 提示用户作弊
        if (playerLastAction && playerLastAction == playerAction) {
            sameCount++;
        } else {
            sameCount = 0;
        }

        //记录上一次操作
        playerLastAction = playerAction;

        if (sameCount >= 3) {
            res.writeHead(400);
            res.end('你作弊!');
            sameCount = 9;
            return;
        }

        const gameResult = game(playerAction);

        res.writeHead(200);


        //根据用户行为返回对应结果
        if (gameResult == 0) {
            res.end('平局')
        } else if (gameResult == 1) {
            res.end('你赢了!')
            playerWon++;
        } else if (gameResult == -1) {
            res.end('你输了')
        }
    }

    //判断如果请求/则返回首页
    if (parseUrl.pathname === '/') {
        fs.createReadStream(__dirname + '/index.html')
        .pipe(res)
    }
}).listen(3000)
  1. 创建http服务
  2. 通过url解析来返回对应信息
  3. 通过queryString获取用户操作行为
  4. 导入game.js游戏逻辑
  5. 通过游戏行为返回对应结果
  6. 用户获胜三次退出游戏
  7. 用户连续三次同样出拳退出