JSFiddle - React, Tailwind, and code Playground

by jonchius

JavaScript

function printHangman(count) {

	var man = "";
	var head = "  ( ) \n";
	var arms = " \\|/ \n";
	var belly = "  |  \n";
	var legs = "  /\\ ";
	
	switch(count) {
        case 1: 
			man = man + head;
			break;
        case 2:
			man = man + head + arms;
			break;
        case 3:
			man = man + head + arms + belly;
			break;
        case 4:
			man = man + head + arms + belly + legs;
			break;
		default:
			console.log("Error!");
	}

	alert(man);
}

var game = true;
var start;
var correctGuesses = [];

while (game) {

	// game setup
    if (start == undefined) {

    	// number of cumulative wrong answers
        var count = 0;	

        // number of cumulative right answers
        var win = 0;

        // somebody other than the player picks a word
        var word = prompt("Pick a word!");
        console.log("The word is: " + word);

        // number of right answers required to win
        var gameWin = word.length;

        // reminder
        alert("Welcome to Hangman! 4 wrong answers and you lose!");

        // begin the game
        start = true;

    }

    // prompt the player to pick a letter 
    var guess = prompt("Pick a letter! (type 'quit' to quit)");

    // check if word contains the letter and if so, how often does it contain the letter
    reguess = new RegExp(guess, "gi");
    var matches = [];
    matches = word.match(reguess); 
    console.log(matches);
	
	// if player guessed a letter that is in the word
    if (matches) {
        
        // if the letter was not already guessed
        if (correctGuesses.indexOf(guess) == -1) {

        	// if not add it to the array of correct guesses
            correctGuesses.push(guess);

        	// increment win variable
			win += matches.length;	

			// let users know of their progress
			if (gameWin - win > 1) {
				alert("Correct, you have " + (gameWin - win) + " letters left to match");
			} else if (gameWin - win == 1) {
				alert("Correct, you have 1 more letter left to match");
			}

		// if...