Professional Documents
Culture Documents
CSS, and JavaScript. Copy and paste this code into separate files (e.g., index.html,
styles.css, script.js), and open the HTML file in a web browser to play the game.
index.html:
htmlCopy code
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta
name="viewport" content="width=device-width, initial-scale=1.0"> <title> Guess the
Number </title> <link rel="stylesheet" href="styles.css"> </head> <body> <div
class="container"> <h1> Guess the Number Game </h1> <p> Try to guess the number
between 1 and 100: </p> <input type="number" id="userGuess" placeholder="Enter your
guess"> <button onclick="checkGuess()"> Submit Guess </button> <p id="message"></p>
</div> <script src="script.js"></script> </body> </html>
styles.css:
cssCopy code
body { font-family : 'Arial' , sans-serif; background-color : #f4f4f4 ; margin : 0 ; display :
flex; align-items : center; justify-content : center; height : 100vh ; } .container { text-align :
center; background-color : #fff ; padding : 20px ; border-radius : 8px ; box-shadow : 0 0
10px rgba ( 0 , 0 , 0 , 0.1 ); } button { padding : 10px ; margin-top : 10px ; cursor : pointer; }
script.js:
jsCopy code
const secretNumber = Math . floor ( Math . random () * 100 ) + 1 ; let attempts = 0 ; function
checkGuess () { const userGuessElement = document . getElementById ( 'userGuess' ); const
messageElement = document . getElementById ( 'message' ); const userGuess =
parseInt (userGuessElement. value ); if ( isNaN (userGuess) || userGuess < 1 || userGuess >
100 ) { messageElement. textContent = 'Please enter a valid number between 1 and 100.' ;
return ; } attempts++; if (userGuess === secretNumber) { messageElement. textContent =
`Congratulations! You guessed the number ${secretNumber} in ${attempts} attempts.` ;
disableInputAndButton (); } else { messageElement. textContent = userGuess >
secretNumber ? 'Too high! Try again.' : 'Too low! Try again.' ; } } function
disableInputAndButton () { const userGuessElement =
document . getElementById ( 'userGuess' ); const submitButton =
document . querySelector ( 'button' ); userGuessElement. disabled = true ;
submitButton. disabled = true ; }
This code sets up a simple webpage where the user can input their guesses to figure
out a randomly generated number between 1 and 100. The game provides feedback
on whether the guess is too high, too low, or correct. Once the correct number is
guessed, it disables further input and displays a congratulatory message.