Created
June 14, 2021 16:18
-
-
Save phpmaps/99539732b114451b168da2df1f83c152 to your computer and use it in GitHub Desktop.
Color Game
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <!DOCTYPE html> | |
| <html lang="en"> | |
| <head> | |
| <meta charset="utf-8"> | |
| <title>Color Guessing Game</title> | |
| </head> | |
| <body> | |
| <h1>Color Guessing Game</h1> | |
| <button type="button" onclick="runGame()">Start Game</button> | |
| <script> | |
| const COLORS_ARRAY = ['blue', 'cyan', 'gold', 'gray', 'green', 'magenta', 'orange', 'red', 'white', 'yellow']; | |
| function runGame() { | |
| let guess = ''; | |
| let correct = false; | |
| let numTries = 0; | |
| const targetIndex = Math.floor(Math.random() * COLORS_ARRAY.length); | |
| const target = COLORS_ARRAY[targetIndex]; | |
| console.log('The target is: ' + target); | |
| do { | |
| guess = prompt('I am thinking of one of these colors:\n\n' + | |
| COLORS_ARRAY.join(', ') + '\n\nWhat color am I thinking of?\n'); // Note: students could also join the COLORS_ARRAY into a new const before the while loop begins, then use that const here, for maximum efficiency. | |
| numTries += 1; | |
| if (guess === null) { | |
| alert('The game has been aborted.'); | |
| return; | |
| } | |
| correct = checkGuess(guess.toLowerCase(), target); | |
| } while (!correct); // Keep looping until the function checkGuess returns a value of 'true' | |
| document.body.style.background = guess; | |
| alert('Congratulations! You have guessed the color!\n\n' + | |
| 'It took you ' + numTries + ' guesses to finish the game!\n\n' + | |
| 'Hit OK to see the color in the background.'); | |
| } | |
| function checkGuess(guess, target) { | |
| const sorryMsg = 'Sorry, your guess is incorrect.\n\n'; | |
| const tryMsg = '\n\nPlease try again.'; | |
| let correct = false; | |
| if (!COLORS_ARRAY.includes(guess)) { | |
| alert('Sorry, I don\'t recognize your color. ' + tryMsg); | |
| } else if ( guess < target ) { | |
| alert(sorryMsg + 'Hint: your color is alphabetically lower than mine.' + tryMsg); | |
| } else if ( guess > target ) { | |
| alert(sorryMsg + 'Hint: your color is alphabetically higher than mine.' + tryMsg); | |
| } else { | |
| correct = true; | |
| } | |
| return correct; | |
| } | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment