css Audio - Active file-generic CSS - Active Generic - Active HTML - Active JS - Active SVG - Active Text - Active file-generic Video - Active header Love html icon-new-collection icon-person icon-team numbered-list123 pop-out spinner split-screen star tv

Pen Settings

CSS Base

Vendor Prefixing

Add External Stylesheets/Pens

Any URL's added here will be added as <link>s in order, and before the CSS in the editor. If you link to another Pen, it will include the CSS from that Pen. If the preprocessor matches, it will attempt to combine them before processing.

+ add another resource

You're using npm packages, so we've auto-selected Babel for you here, which we require to process imports and make it all work. If you need to use a different JavaScript preprocessor, remove the packages in the npm tab.

Add External Scripts/Pens

Any URL's added here will be added as <script>s in order, and run before the JavaScript in the editor. You can use the URL of any other Pen and it will include the JavaScript from that Pen.

+ add another resource

Use npm Packages

We can make npm packages available for you to use in your JavaScript. We use webpack to prepare them and make them available to import. We'll also process your JavaScript with Babel.

⚠️ This feature can only be used by logged in users.

Code Indentation

     

Save Automatically?

If active, Pens will autosave every 30 seconds after being saved once.

Auto-Updating Preview

If enabled, the preview panel updates automatically as you code. If disabled, use the "Run" button to update.

HTML Settings

Here you can Sed posuere consectetur est at lobortis. Donec ullamcorper nulla non metus auctor fringilla. Maecenas sed diam eget risus varius blandit sit amet non magna. Donec id elit non mi porta gravida at eget metus. Praesent commodo cursus magna, vel scelerisque nisl consectetur et.

            
              <div class="container-fluid header">
	<div class="row row-centered">
	    <div class="col text-center">
			<h1>JavaScript Guessing Game - Fixed Number</h1>
		</div>
	</div>
</div>


<div class="row row-centered">
	<div class="col-sm-5 offset-sm-1 game-purpose text-center">
		<figure>
<img src="minifigtest.jpg" alt="Jar of LEGO Minifigures" height="400">
 <figcaption>Example only. <em>Not</em> the actual jar of minifigs.</figcaption>
</figure>

	</div>

	<div class="col-sm-6 col-md-5 game-directions">
		<div class="col text-center container-fluid">
			<div class="input-group"><input type="text" id="number-input" class="form-control" onkeydown="return validateNumber(event)">

				<button id="btn-guess">Guess</button>
				<button id="btn-play-again">Play Again</button>
			</div>

			<p id="alert"></p>
			<p id="guesses-remaining"></p>
			<p id="numbers-guessed"></p>
	    </div>


			<h2 class="text-center">Directions</h2>
			<p><ul>
				<li>Try to guess how many minifigs are in the mason jar.</li>
				<li>You have 5 guesses.</li>
			</ul></p>
	</div>
</div>


<div class="row row-centered">
	<div class="col-sm-6 col-md-5 offset-md-1 game-purpose ">

		<h2 class="text-center">Purpose</h2>
		<p>The kids and I love LEGO and we have quite a few Minifigs. I thought it would be fun to have people guess how many I could fit into a Mason jar. Since this number isn't ever going to change, it's not something they would play over and over again. I think my site's 404 error page would make a good home for this reason. That way some people will come across it but [hopefully] not very often.</p>
	</div>
    <div class="col-sm-6 col-md-5 offset-md-0 game-features">
		<h2 class="text-center">Guessing Game Features</h2>
		<ul>
			<li>Allow only numbers to be input</li>
			<li>Accept input from the regular number keys and also the number/key pad</li>
			<li>Allow the user to enter a guess by clicking the button or pressing enter</li>
			<li>Allow a maximum of 5 guesses per game</li>
			<li>Allow the user to play again once the game is over</li>
			<li>Prevent a user from guessing the same number twice</li>
			<li>Limit number of digits per guess to 4.  Example: 1234</li>
			<li>Set focus to "Play Again" button when game is over</li>
			<li>Disable input field when game is over</li>
		</ul>
    </div>
</div>
            
          
!
            
              .header {
	margin-bottom: 30px;
}
h1 {
	margin: 10px;
}
img {
	border: 5px solid #000;
}
#alert {
	color: red;
	margin-top: 1em;
}
#btn-play-again {
	display: none;
}
.game-purpose {
	padding: 20px;
}
.game-features {
	padding: 20px;
}
#numbers-guessed {
	min-height: 30px;
}
            
          
!
            
              const maxGuesses = 5;
const numberToGuess = 808;
let guess = '';
let guessesRemaining = maxGuesses;
let numbersGuessed = [];
let alreadyUsed = false;
resetGame();
let numberArray = [];
/**
 * Summary. (use period)
 *
 * Description. (use period)
 *
 * @since      0.1.0
 *
 * @fires   eventName
 * @fires   className#eventName
 * @listens event:eventName
 * @listens className~event:eventName
 *
 * @param {type}   var           Description.
 * @param {type}   [var]         Description of optional variable.
 * @param {type}   [var=default] Description of optional variable with default variable.
 * @param {Object} objectVar     Description.
 * @param {type}   objectVar.key Description of a key in the objectVar parameter.
 *
 * @returns {type} Description.
 */
function validateNumber( e ) {
	// backspace == 8
	// 0-9 == 48-57
	// Number pad 0-9 == 96-105
    var charCode = e.keyCode ? e.keyCode : e.charCode
    if ( ! ( charCode >= 48 && charCode <= 57 ) && ! ( charCode >= 96 && charCode <= 105 ) && ( charCode!=8 ) ) {
		return false;
    }
	checkLength();
}

function checkLength() {
	if (document.getElementById("number-input").value.length >= 4) {
		document.getElementById("number-input").value = document.getElementById("number-input").value.substr( 0, 3 );
		document.getElementById("alert").innerHTML = "You number is limited to 4 digits.";
	}
}

document.getElementById("number-input").addEventListener("keyup", function( event ) {
    event.preventDefault();
	// If the enter key is pressed, register a guess
    if ( event.keyCode === 13 ) {
        document.getElementById("btn-guess").click();
    }
});

function checkGuess() {
	guess = parseInt(document.getElementById("number-input").value);

	if ( guessesRemaining > 0 ) {
		if ( ! ( isNaN( guess ) ) && guess != '' ) {

				//alreadyUsed = numbersGuessed.includes(guess);
				alreadyUsed = numbersGuessed.includes( guess );
			if ( ! alreadyUsed ) {

				guessesRemaining--;
				document.getElementById( "alert" ).innerHTML = "<br>"
				numbersGuessed.push( guess );
				document.getElementById( "numbers-guessed" ).innerHTML =
					"Numbers You've Guessed: " + numbersGuessed.join(", ");
				document.getElementById( "guesses-remaining" ).innerHTML =
				 	"Guesses Remaining: " + guessesRemaining;
				document.getElementById( "number-input" ).value = '';
				document.getElementById( "number-input" ).focus();


				if ( guess === numberToGuess ) {
					document.getElementById( "alert" ).innerHTML = "Congratulations, you guessed it!";
					document.getElementById( "btn-guess" ).style.display = "none";
					document.getElementById( "btn-play-again" ).style.display = "inline";

					document.getElementById( "btn-play-again" ).focus();
					return;
				}

				if ( guessesRemaining === 0 )  {
					gameOver();
				}
			} else {
				document.getElementById("alert").innerHTML = "You already guessed that number!";
				document.getElementById("number-input").select();
			} // if ( ! alreadyUsed )



		}
	} // if ( guessesRemaining > 0 )
} // checkGuess()

/**
 * Summary. Actions to perform when the game is over
 *
 * Description. (use period)
 *
 * @since      0.1.0
 *
 */
function gameOver() {
	document.getElementById( 'numbers-guessed' ).innerHTML =
		"Numbers You've Guessed: " + numbersGuessed;
	document.getElementById( 'btn-guess' ).style.display = 'none'
	document.getElementById( 'btn-play-again' ).style.display = 'inline'
	document.getElementById( 'alert' ).innerHTML =
		"Sorry, you don't have any guesses left.  Better luck next time!";
	document.getElementById( 'number-input' ).value = '';
	document.getElementById( 'number-input' ).disabled = true;
	document.getElementById( 'btn-play-again' ).focus();
}


function resetGame() {
	guessesRemaining = maxGuesses;
	numbersGuessed = [];
	guess = '';
	document.getElementById( 'numbers-guessed' ).innerHTML = "Numbers Guessed: You haven't guessed any numbers yet";
	document.getElementById( 'btn-guess' ).style.display = 'inline'
	document.getElementById( 'btn-play-again' ).style.display = 'none'
	document.getElementById( 'alert' ).innerHTML = '<br>';
	document.getElementById( 'number-input' ).value = '';
	document.getElementById( 'number-input' ).focus();
	document.getElementById( 'number-input' ).disabled = false;
document.getElementById( "guesses-remaining" ).innerHTML =
	"Guesses Remaining: " + guessesRemaining;
}

document.getElementById( 'btn-play-again' ).addEventListener( 'click', resetGame );

document.getElementById( 'btn-guess' ).addEventListener( 'click', checkGuess );
            
          
!
999px
🕑 One or more of the npm packages you are using needs to be built. You're the first person to ever need it! We're building it right now and your preview will start updating again when it's ready.
Loading ..................

Console