-
Notifications
You must be signed in to change notification settings - Fork 0
/
script.js
105 lines (86 loc) · 2.97 KB
/
script.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
const wordElem= document.getElementById('word');
const wrongLet= document.getElementById('wrongletter');
const playAgain= document.getElementById('popbtn');
const popUp= document.getElementById('popup');
const notification= document.getElementById('notif');
const finalMsg= document.getElementById('finalMsg');
const figParts= document.querySelectorAll('.fig-part');
const words =['wizard', 'scrutiny', 'hunch', 'heartland', 'scrotching', 'doomsday'];
let selectedWord = words[Math.floor(Math.random()*words.length)];
const correctLetters=[];
const wrongLetters =[];
//show hdden word
function displayWord(){
wordElem.innerHTML=`${selectedWord
.split('') // split is used to convert a string into an array where each letter is an array element
.map(letter=>
` <span class="letter">
${correctLetters.includes(letter)? letter : ''}
</span>
`).join('') // jon will convert an array back to string
}`;
const innerWord=wordElem.innerText.replace(/\n/g, '');
if (innerWord=== selectedWord){
finalMsg.innerText='congratulations! You won!';
popUp.style.display= 'flex';
}
}
//update wrong letter
function updateWrong(){
wrongLet.innerHTML= `
${wrongLetters.length>0 ? '<p>Wrong</p>' : '' }
${wrongLetters.map(letter=> `<span>${letter}</span>`)}
`;
figParts.forEach((part, index)=>{
const errors= wrongLetters.length;
if(index< errors){
part.style.display='block';
}else{
part.style.display='none';
}
})
//checking if game lost
if(wrongLetters.length === figParts.length){
finalMsg.innerText='You lost buddy';
popUp.style.display='flex'
}
}
// show notification
function showNotficaton(){
notification.classList.add('show');
setTimeout(()=>{
notification.classList.remove('show')
}, 2000)
}
//keydown letter press
window.addEventListener('keydown', e=>{
// console.log(e.keyCode);
if(e.keyCode>=65 && e.keyCode<=90){ //keycodes range for alphabets on keyboard
const letter = e.key;
if(selectedWord.includes(letter)){
if(!correctLetters.includes(letter)){
correctLetters.push(letter);
displayWord();
}else{
showNotficaton();
}
}else{
if(!wrongLetters.includes(letter)){
wrongLetters.push(letter);
updateWrong();
}else{
showNotficaton();
}
}
}
})
//RESTART GAME
playAgain.addEventListener('click',()=>{
correctLetters.splice(0);
wrongLetters.splice(0);
selectedWord= words[Math.floor(Math.random()*words.length)];
displayWord();
updateWrong();
popUp.style.display='none';
})
displayWord();