Create a simple Rock-Paper-Scissors game using Node.js and output to the command line

Preface

I'm sure everyone has played Rock Paper Scissors before — it's a very simple game. Today, Mushroom Head will walk you through implementing this simple little game together.

Requirements

Use pure Node.js to implement a simple Rock Paper Scissors game where the player battles against the computer. After each round of battle, output the score result to the command line.

Approach

  1. Get the player's input
  2. Get the computer's input
  3. Compare the inputs of the player and the computer
  4. Print out the score

Full Code

// Get user input from the process object
// Listen for input events on the data event

let score = 0;

process.stdin.on(‘data’, (buffer) => {
// Get the user’s input result and store it in action
const action = buffer.toString().trim();
// Get the outcome of the current round and store it in result
const result = game(action);
if(result==1){
score++
}else if(result==-1){
score–;
}
console.log('Current score: '+score);
})

/*

  • @func Determines win or loss based on user input
  • @return win/lose
    */
    const game = function (action) {
    // Validate user input
    if ([‘rock’, ‘scissor’, ‘paper’].includes(action) == -1) {
    return new Error(‘Invalid user input’);
    }
    let computerAction;
    // Generate the computer’s move using an array + random number
    let random = Math.floor(Math.random() * 3);
    const arr = [‘rock’,‘scissor’,‘paper’];
    computerAction = arr[random];
    console.log("The computer played "+computerAction);
    // Determine the outcome
    if (computerAction == action) {
            console.log(‘Draw’)
            return 0; // Draw
        } else if (
            (computerAction == ‘rock’ && action == ‘scissor’) ||
            (computerAction == ‘scissor’ && action == ‘paper’) ||
            (computerAction == ‘paper’ && action == ‘rock’)
        ) {
            console.log(‘You lose’)
            return -1;
        } else {
            console.log(‘You win’);
            return 1;
        }
    }

Summary

When you get a new requirement, don't jump straight into writing code. First, you should outline a general approach, then break this approach down into specific steps. Think through each step clearly before moving on to the next; don't start working on the next step before you finish the current one. Write code step by step, and keep your logic clear. When you finish the initial version, there will almost certainly be some bugs, some unhandled conditions, and areas that can be optimized. For example, the includes check above: if the user enters 0 or an empty string, it won't return an error. Or the if/else structure is quite verbose and could be optimized. These are all things you can revisit after you finish writing the initial code. Good coding habits are extremely important. OK, that's all from Mushroom Head for today, see you next time.


This is a discussion topic separated from the original post at https://juejin.cn/post/7368761530382647315