First basic efforts with JavaScript, exploring function construction and conditionals, courtesy of the Codecademy Number Guesser Project.

As a basic entry point project, the goal was to code the core functions of a JavaScript program to support a basic web based 2 player guessing game (human vs computer). A “secret” target number between 0 and 9 inclusive is generated. The winner of each round is the player that guesses closest to the secret number. In the event of a tie, the human wins.

The core code keeps check of round numbers and score for each player. “Extra credit” challenges required creation of a helper function and a screen alert if the human player attempted to submit a number outside the possible range.

Here’s some actual gameplay footage, from the full program!

The core functions I produced to run the game; I aimed to keep the function code as compact as possible (ie one line functions where possible):

// JavaScript source code
let humanScore = 0;
let computerScore = 0;
let currentRoundNumber = 1;

// Write your code below:

//Function to generate random number between 0 and 9
const generateTarget = () => Math.floor(Math.random() * 10);

//Extra Credit: Function to identify absolute distance between guess and target
const getAbsoluteDistance = (guess, target) => Math.abs(guess - target);

//Function to test whether computer or human guess is closest to target
//Original one liner with no correction replaced by the Extra Credit function
//const compareGuesses = (human, computer, target) => getAbsoluteDistance(human, target) <= getAbsoluteDistance(computer, target) ? true : false;
//Extra Credit: Update function to alert() if human guess is out of range 0 to 9 inclusive
//I used modulus 10 to correct invalid entries and make them in range

const compareGuesses = (human, computer, target) => {
    if (human < 0 || human > 9) {
        alert('Invalid entry, must be in range 0 to 9. Modulus value will be used.');
    }
    const correctedHuman = human % 10;
    if (getAbsoluteDistance(correctedHuman, target) <= getAbsoluteDistance(computer, target)) {
        return true;
    } else {
        return false;
    }
}

//Function to update relevant score each round; input will be either 'human' or 'computer'
const updateScore = roundWinner => roundWinner === 'human' ? humanScore++ : computerScore++;

//Function to update round number after each round
const advanceRound = () => currentRoundNumber++;