Skip to content

Instantly share code, notes, and snippets.

@nsbingham
Created March 2, 2016 18:26
Show Gist options
  • Save nsbingham/37189c8334ed9d3afccb to your computer and use it in GitHub Desktop.
Save nsbingham/37189c8334ed9d3afccb to your computer and use it in GitHub Desktop.
number-guessing-exercise
<p id="message">Guess a number between 1 and 10</p>
<form id="input">
<input type="text" name="number" id="guess">
<button id="submit">Submit</button>
</form>
<button id="replay" class="hidden">Replay</button>
# Number-guessing
- Write the `init` function to set up an event listener on the form. The event listener should pass the value of the input element to the `check` function.
- Write the `check` function to accept a value from the event listener and check it against the `targetNumber`.
- If the values match, call the `showWin` function
- If the values do not match, call the `showError` function.
- If the values do not match, and the player has made more than five guesses, call the `showLoss` function.
- Write the `showWin` function to remove the form and any error message, and show a message telling the player they win.
- Write the `showError` function to show a message telling the player their guess is incorrect.
- Write the `showLoss` function to remove the form and show a message telling the player they lose.
var attempts = 1;
let targetNumber = Math.floor(Math.random() * 10) + 1;
var submit = document.getElementById('submit'),
guess = document.getElementById('guess'),
input = document.getElementById('input'),
message = document.getElementById('message'),
replay = document.getElementById('replay');
function init () {
submit.onclick= function(e){
e.preventDefault();
check(guess);
}
}
function check (input) {
if (input.value == targetNumber) {
showWin(targetNumber);
} else if (input.value != targetNumber && attempts < 5) {
showError();
} else {
showLoss(targetNumber);
}
}
function showWin (target) {
message.innerHTML = target+' You win!';
message.className = 'green';
allowReplay();
}
function showError () {
console.log('Try Again', attempts);
message.innerHTML = attempts +' attempts. Try again! Guess a number between 1 and 10';
attempts++;
}
function showLoss (target) {
console.log('You lose! ' + target);
message.innerHTML = target + ' You lose!';
message.className = 'red';
allowReplay();
}
function allowReplay(){
input.className += 'hidden';
guess.value = '';
replay.className = '';
replay.onclick = function(e){
e.preventDefault();
message.className = '';
input.className = '';
message.innerHTML = 'Guess a number between 1 and 10';
attempts = 1;
targetNumber = Math.floor(Math.random() * 10) + 1;
}
}
init();
body {
font-family: Helvetica;
}
#replay {
}
.hidden {
display: none;
}
.red {
color: #9d0000;
}
.green {
color: #009d00;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment