Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

Some days ago, I learned a rock-paper-scissors game and implemented it locally. When I wanted to hang it on my server and let it form a game accessible from the Internet, something went wrong, which was the wrong interface request path. Now I don’t know what the reason is.

What needs to be prepared

  • Node.js environment (if not, you can go to the official website for a simple installation)
  • Basic HTML, CSS, JS skills
  • Entry level Node.js is good (because I am at that level)
  • A code writing tool that you are familiar with

Get started

First we need an HTML page for the return of game results and player actions.

Demand analysis:

  • We need a place to do the return of game results
  • Three buttons are also needed to interact with the user

Let’s look at the index.html file

<div id="output" style="height: 400px; width: 600px; background: #eee"></div>
<button id="rock" style="height: 40px; width: 80px">stone</button>
<button id="scissor" style="height: 40px; width: 80px">scissors</button>
<button id="paper" style="height: 40px; width: 80px">cloth</button>
Copy the code

I defined a div as a place to display the results of the game, and three buttons representing rock, Paper, and Scissors.

The next thing we should do is to submit our user action via interface and get the result of the game, displaying it in the div we just saw.

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/>'; })})})Copy the code

Then we’ll create a game.js file and write down the game’s decision logic.

module.exports = function (palyerAction){
    if(['rock'.'scissor'.'paper'].indexOf(palyerAction) == -1) {throw new Error('invalid playerAction');
    }
    // Calculate the result of the computer
    var computerAction;
    var random = Math.random() * 3;
    if(random < 1){
        computerAction = "rock"
    }else if(random > 2){
        computerAction = "scissor"
    }else{
        computerAction = "paper"
    }
    if(computerAction == palyerAction){
        return 0;
    }else if(
        (computerAction == "rock" && palyerAction == "scissor") ||
        (computerAction == "scissor" && palyerAction == "paper") ||
        (computerAction == "paper" && palyerAction == "rock")
    ){
        return -1;
    }else{
        return 1; }}Copy the code

The general logic is simple, using random numbers to get the computer to throw a punch, then decide the winner and return.

Here’s a look at the simple interaction written in Node.js,index.js:

const querystring = require('querystring');
const http = require('http');
const url = require('url');
const fs = require('fs');

const game = require('./game');

let playerWon = 0;

let playerLastAction = null;
let sameCount = 0;

http
    .createServer(function (request, response) {
        const parsedUrl = url.parse(request.url);
        if (parsedUrl.pathname == '/favicon.ico') {
            response.writeHead(200);
            response.end();
            return;
        }
        if (parsedUrl.pathname == '/game') {
            const query = querystring.parse(parsedUrl.query);
            const playerAction = query.action;
            if (playerWon >= 3 || sameCount == 9) {
                response.writeHead(500);
                response.end('I'm not playing with you anymore! ');
                return
            }
            if (playerLastAction && playerAction == playerLastAction) {
                sameCount++;
            } else {
                sameCount = 0;
            }
            playerLastAction = playerAction
            if (sameCount >= 3) {
                response.writeHead(400);
                response.end('You cheated! ');
                sameCount = 9;
                return 
            }
            // Execute the game logic
            const gameResult = game(playerAction);
            // Return to the header first
            response.writeHead(200);
            // Returns different instructions for different game results
            if (gameResult == 0) {
                response.end('the draw! ');
            } else if (gameResult == 1) {
                response.end('You won! ');
                // Player win count +1
                playerWon++;
            } else {
                response.end('You lost! '); }}// If the root path is accessed, read out the game page and go back out
        if (parsedUrl.pathname == '/') {
            fs.createReadStream(__dirname + '/index.html').pipe(response);
        }
    })
    .listen(3000)
Copy the code

Enter node index.js in a CMD window and you will see the game in port localhost:3000 of your browser.

For those of you who are basic to Node, this should look easy, since I don’t know much about EMM.

Well, let’s see what happens.

It’s lazy not to beautify.

The last

Want to optimize in the future, hang to his server, hey hey, at least is their first small game ~

Do you have any good suggestions ~