-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathscript.js
69 lines (59 loc) · 2.42 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
const words = ['javascript','dsa', 'github', 'bash', 'cobol', 'ring', 'tom', 'vim', 'typescript', 'unity', 'sql', 'go', 'ruby', 'rust', 'jython', 'matlab', 'lynx', 'lucid', 'kotlin', 'hack', 'coffeescript', 'ecmascript', 'python', 'html', 'css', 'nodejs', 'react', 'java', 'nextjs', 'babbage', 'angular'];
let word = words[Math.floor(Math.random() * words.length)];
let guessedWord = Array(word.length).fill('_');
let attempts = 6;
const wordElement = document.getElementById('word');
const lettersElement = document.getElementById('letters');
const messageElement = document.getElementById('message');
const resetButton = document.getElementById('reset');
function updateWordDisplay() {
wordElement.textContent = guessedWord.join(' ');
}
function updateLettersDisplay() {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
lettersElement.innerHTML = '';
for (let letter of alphabet) {
const letterElement = document.createElement('div');
letterElement.textContent = letter;
letterElement.className = 'letter';
letterElement.addEventListener('click', () => guessLetter(letter));
lettersElement.appendChild(letterElement);
}
}
function guessLetter(letter) {
if (word.includes(letter)) {
for (let i = 0; i < word.length; i++) {
if (word[i] === letter) {
guessedWord[i] = letter;
}
}
updateWordDisplay();
if (!guessedWord.includes('_')) {
messageElement.textContent = 'Congratulations! You guessed the word!';
disableLetters();
}
} else {
attempts--;
if (attempts === 0) {
messageElement.textContent = `Game Over! The word was "${word}".`;
disableLetters();
} else {
messageElement.textContent = `Incorrect guess. Attempts left: ${attempts}`;
}
}
}
function disableLetters() {
const letterElements = document.querySelectorAll('.letter');
letterElements.forEach(element => element.style.pointerEvents = 'none');
}
function resetGame() {
word = words[Math.floor(Math.random() * words.length)];
guessedWord = Array(word.length).fill('_');
attempts = 6;
messageElement.textContent = '';
updateWordDisplay();
updateLettersDisplay();
}
resetButton.addEventListener('click', resetGame);
updateWordDisplay();
updateLettersDisplay();