-
Notifications
You must be signed in to change notification settings - Fork 0
/
guessNO.js
90 lines (79 loc) · 2.4 KB
/
guessNO.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
let randomNumber = parseInt(Math.random() * 100 + 1);
const submit = document.querySelector('#subt');
const userInput = document.querySelector('#guessField');
const guessSlot = document.querySelector('.guesses');
const remaining = document.querySelector('.lastResult');
const lowOrHi = document.querySelector('.lowOrHi');
const startOver = document.querySelector('.resultParas');
const p = document.createElement('p')
let prevGuess = []
let numGuess = 1
let playGame = true;
if(playGame){
submit.addEventListener('click', function (e){
e.preventDefault();
const guess = parseInt(userInput.value);
console.log(guess);
validateGuess(guess);
});
}
function validateGuess(guess){
if(isNaN(guess)){
alert('Please enter a valid number')
}else if(guess < 1){
alert('Please enter a number more than 1')
}else if(guess > 100){
alert('Please enter a number less than 100')
}else{
prevGuess.push(guess)
if(numGuess === 11){
displayGuess(guess)
displayMessage(`Game Over. Random number was ${randomNumber}`)
endGame()
}else{
displayGuess(guess)
checkGuess(guess)
}
}
}
function checkGuess(guess){
if(guess === randomNumber){
displayMessage(`You guessed it right`)
endGame()
}else if(guess < randomNumber){
displayMessage(`Number is Tooo Low`)
}else if(guess > randomNumber){
displayMessage(`Number is Tooo High`)
}
}
function displayGuess(guess){
userInput.value = ''
guessSlot.innerHTML += `${guess}, `
numGuess++;
remaining.innerHTML = `${11 - numGuess} `
}
function displayMessage(message){
lowOrHi.innerHTML = `<h2> ${message} </h2>`
}
function endGame(){
userInput.value = '';
userInput.setAttribute('disabled', '');
p.classList.add('button');
p.innerHTML = `<h2 id= "newGame">start new Game</h2>`;
startOver.appendChild(p)
playGame = false;
newGame();
}
function newGame(){
const newGameButton = document.querySelector('#newGame');
newGameButton.addEventListener('click', function(e){
randomNumber = parseInt(Math.random() * 100 + 1);
prevGuess = [];
numGuess = 1;
guessSlot.innerHTML = '';
remaining.innerHTML = `${11 - numGuess} `;
userInput.removeAttribute('disabled');
startOver.removeChild(p);
playGame = true
})
}