-
Notifications
You must be signed in to change notification settings - Fork 0
/
guess-the-number.js
84 lines (80 loc) · 3.16 KB
/
guess-the-number.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
'use strict';
//Declaring Global values
//generates a random number form 1 to 6.
let secretNum = Math.trunc(Math.random() * 6) + 1;
//to maintain score and high score.
let score = 10;
let highScore = 0;
//Sets 0 as by default value for input field.
document.querySelector('.guess').value = 0;
//Function to reverse the Game Winning effects.
const gotoStart = function(){
changeTextContent('.status', 'Start Guessing...');
changeBg('.line','#FFFFFF');
changeBg('.reveal','#FFFFFF');
changeColor('.status','#FFFFFF');
changeColor('.reveal','#000000');
document.querySelector('.reveal').textContent='?';
changeTextContent('.scoreVal', score);
}
//This function replaces the value of element's text with message.
const changeTextContent = function(el, message){
document.querySelector(el).textContent = message;
}
//This function changes the BG colour of an element.
const changeBg = function(el, colour){
document.querySelector(el).style.backgroundColor = colour;
}
//This function changes the colour of element's text.
const changeColor = function(el, colour){
document.querySelector(el).style.color = colour;
}
//Setting On-Click event for Play Again Button.
document.querySelector('.playAgain').addEventListener('click', function(){
score = 10;
secretNum = Math.trunc(Math.random() * 6) + 1;
document.querySelector('.guess').value = "0";
gotoStart();
});
//Setting On-Click event for Check Button to check guess.
document.querySelector('.check').addEventListener('click', function(){
const guess = document.querySelector('.guess').value;
if(guess == ''){changeTextContent('.status', 'Please Enter a number.')}
else{
//checking if number is between 1 to 6.
if(guess < 1 || guess > 6) {
gotoStart();
changeTextContent('.status', 'The Number is between 1 to 6.')
}
else{
//Winning Condition
if(secretNum == guess){
changeTextContent('.status', 'Correct Number!!🎊🎊');
changeBg('.line','#4FAF44');
changeBg('.reveal','#4FAF44');
changeColor('.status','#4FAF44');
changeColor('.reveal','#FFFFFF');
changeTextContent('.reveal', guess);
if(document.querySelector('.highScoreVal').textContent === '--'){
changeTextContent('.highScoreVal', 0);
}
if( score > highScore){
highScore = score;
changeTextContent('.highScoreVal', highScore);
}
}
//Reducing Score as guess was high.
else if(guess > secretNum && score>0){
score--;
gotoStart();
changeTextContent('.status', 'Too High');
}
//Reducing Score as guess was low.
else if(score>0){
score--;
gotoStart();
changeTextContent('.status', 'Too Low');
};
};
};
});