Guess Web Application

<< Click to Display Table of Contents >>

Navigation:  Analogues > Vue.js >

Guess Web Application

This Vue application challenges the user to guess a random number between 1 and 100. After each attempt, it provides feedback such as “too low” or “too high” until the correct number is guessed.

 

Before writing the code, let’s first set up a Vue.js project that will serve as the foundation for this application.

 

Editing App.vue

 

Navigate to the src folder and open the file App.vue in any text editor.

 

Replace its contents with the code for our Guess application:

 

<template>

 <div class="app">

   <h1>Guess the Number</h1>

 

  <!-- Input field for user's guess -->

   <input

     ref="guessInput"

     type="text"

     v-model="guess"

     :disabled="!isButtonEnabled"

     placeholder="Enter a number (1-100)"

     @keyup.enter="handleGuess"

   />

 

  <!-- Message to the user (hint, error, or success) -->

   <p>{{ message }}</p>

 

  <!-- Number of attempts -->

   <p>Guess #{{ count }}</p>

 

  <!-- Submit button -->

   <button :disabled="!isButtonEnabled" @click="handleGuess">

     Guess

   </button>

 </div>

</template>

 

<script>

export default {

 name: 'App', // Component name

 

 // Application state

 data() {

   return {

     guess: '',                             // User input

     message: '',                           // Message for the user

     count: 0,                             // Number of attempts

     magicNo: Math.floor(Math.random() * 100) + 1, // Random number from 1 to 100

     isButtonEnabled: true,                 // Flag to enable/disable input and button

   };

 },

 

// Hook that runs after the component is mounted

 mounted() {

   this.$refs.guessInput.focus(); // Set focus to the input field

 

  // Read the MagicNo parameter from the URL (e.g., ?MagicNo=42)

   const params = new URLSearchParams(window.location.search);

   const magicNoParam = params.get('MagicNo');

 

  // If the parameter exists and is a number, override the random number

   if (magicNoParam && !isNaN(parseInt(magicNoParam))) {

     this.magicNo = parseInt(magicNoParam);

   }

 },

 

// Component methods

 methods: {

  // Handler for "Guess" button or pressing Enter

   handleGuess(e) {

    // If Shift is held, reveal the answer (debug mode)

     if (e && e.shiftKey) {

       alert(`The magic number is: ${this.magicNo}`);

       return;

     }

 

    // Clear the previous message

     this.message = '';

 

    // Convert user input to number

     const guessValue = parseInt(this.guess);

 

    // Validate the input

     if (isNaN(guessValue)) {

       this.message = `${this.guess} is not a valid number.`;

     } else if (guessValue < 1 || guessValue > 100) {

       this.message = `${guessValue} is not in the range of 1 to 100.`;

     } else {

      // Increase the attempt counter

       this.count++;

 

      // Hint: too low

       if (guessValue < this.magicNo) {

         this.message = `${guessValue} is too low.`;

 

      // Hint: too high

       } else if (guessValue > this.magicNo) {

         this.message = `${guessValue} is too high.`;

 

      // Correct guess

       } else {

         alert('Congratulations! You guessed the magic number.');

         this.isButtonEnabled = false; // Disable input and button

       }

     }

 

    // Clear input field and return focus

     this.guess = '';

     this.$refs.guessInput.focus();

   },

 },

};

</script>

 

This file contains the logic, layout, and styles all in one place, using the standard Vue Single File Component structure (.vue file).

 

Run the Application

 

Go back to the terminal and start the development server (if it's not already running):

 

npm run serve

 

If everything is set up correctly, your application should now be live at http://localhost:8080/.

 

You can open this URL in your browser to see the fully working Guess the Number game.

 

AD_4nXd7433MGpclTPBSC-YIoo6dUW43Fz7e_iQAhwW0ANwFyVIRuH0OuFavKYjZRKQ1bHVCkubd6j6v_D0Jqk-fzYmdXxLGeeRnxKEVSDc1gNSm_AkicVWRo6Dvo81lIa5qk2KaW5Mm1A

 

See also

Advantages of IntraWeb 17