Created
June 14, 2021 16:26
-
-
Save phpmaps/1a8728102179361f0508678ca305624e to your computer and use it in GitHub Desktop.
Color game extra
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>Week 3 - Workshop (Color game)</title> | |
| <style> | |
| body { | |
| font-family: Verdana, Arial, sans-serif; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>Color Game</h1> | |
| <button id="runGame" onclick="runGame()">Start Game</button> | |
| <script> | |
| const COLORS_ARRAY = ['blue', 'cyan', 'gold', 'gray', 'green', 'magenta', 'orange', 'red', 'white', 'yellow']; | |
| function changeBackground(target) { | |
| let toggle = true; | |
| return setInterval(() => { | |
| toggle = !toggle | |
| document.body.style.background = toggle ? target : "pink"; | |
| }, 250) | |
| } | |
| 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(target); | |
| do { | |
| console.log("...running"); | |
| guess = prompt("I am thinking on one of these colors: \n\n" + COLORS_ARRAY + | |
| "What color am I thinking of?"); | |
| if (!guess) { | |
| alert("Ok, thanks for playing"); | |
| return; | |
| } | |
| correct = checkGuess(guess, target); | |
| numTries += 1; | |
| } while (!correct); | |
| alert(`You won. It took you ${numTries} ${v = numTries <= 1 ? "try." : "tries."}`); | |
| console.log("target " + target); | |
| const interval = changeBackground(target); | |
| setTimeout(() => { | |
| clearInterval(interval); | |
| }, 5000) | |
| } | |
| function checkGuess(guess, target) { | |
| let correct = false; | |
| if (COLORS_ARRAY.indexOf(guess) < 0) { | |
| alert("Your color is not in the list.") | |
| } else if (guess > target) { | |
| alert("Hint: your color is alphabetically higher than mine.") | |
| } else if (guess < target) { | |
| alert("Hint: your color is alphabetically lower than mine.") | |
| } 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